/* Help & Support — the site's help centre. Three parts:
   1. How-to guides for the main things you can do (accounts, adding records,
      valuations, value history, Collection DNA, Your Next Record, wishlist &
      Grail Watch, importing, leaderboards, collector levels, the list, deep dives).
   2. A searchable FAQ (collapsible questions).
   3. Contact us — routes to luca@thelead-in.com.
   Linked from the top nav and the footer. Reuses the legal-/pg- design tokens
   plus a small set of help-* styles in features_css.css. */

const { useState: useHelpState, useMemo: useHelpMemo } = React;

const HELP_CONTACT_EMAIL = "luca@thelead-in.com";

/* ---- How-to guides --------------------------------------------------- */
/* Each guide is a titled, numbered set of steps for one core feature. */
const HELP_GUIDES = [
  {
    id: "account",
    eyebrow: "Getting started",
    title: "Create an account & sign in",
    blurb: "An account lets you save your collection, get valuations and appear on the leaderboards. It's free.",
    steps: [
      "Click Sign in in the top-right of any page, then choose Create account.",
      "Enter your email and a password, or continue with one of the listed sign-in options.",
      "Check your inbox for a confirmation email and click the link to verify your address.",
      "You're in. Your collection, wishlist and preferences now follow you on any device you sign in on.",
    ],
    tip: "Forgotten your password? Choose Sign in → Forgot password and we'll email you a reset link.",
  },
  {
    id: "add-record",
    eyebrow: "Your collection",
    title: "Add a record to your collection",
    blurb: "There are four ways to add a record — pick whichever is fastest for what's in front of you.",
    steps: [
      "Open My Collection and click Add a record.",
      "Scan the barcode — point your phone camera at the sleeve's barcode and we'll match the release automatically.",
      "Snap the cover — take a photo of the front sleeve and we'll identify the album for you.",
      "Search — type the artist and title and choose the right release from the results.",
      "Or add it by hand if it's rare or not yet catalogued — enter the artist, title, label, format and year yourself.",
      "Pick your pressing and set the condition (Mint, Near Mint, VG+, and so on), then save. The record now appears in your collection.",
    ],
    tip: "Not sure which pressing you own? Use the runout/matrix identifier in the Pressing Guide — type the etched code and we'll match it.",
  },
  {
    id: "valuation",
    eyebrow: "Your collection",
    title: "Get a valuation for your records",
    blurb: "Every record you add gets a live market valuation based on its pressing and the condition you chose.",
    steps: [
      "Add a record and set its condition as accurately as you can — condition is the biggest driver of value.",
      "Newly added records show as Pending valuation while we price them; this usually settles within 48 hours.",
      "Open any record to see its current estimated value and the value-over-time chart.",
      "Your collection's total estimated value is shown at the top of My Collection and refreshes automatically.",
    ],
    tip: "Valuations are indicative, drawn from public marketplace data and editorial judgement — not formal appraisals or investment advice.",
  },
  {
    id: "value-history",
    eyebrow: "Your collection",
    title: "Track your collection's value over time",
    blurb: "See how individual records and your whole collection have moved in value.",
    steps: [
      "Open any record in your collection to see its value-over-time chart.",
      "A dashed line is an estimated back-fill from before you added the record; a solid line is live valuation history accruing from when you started tracking it.",
      "We snapshot values weekly, so the longer you track a record the richer its history becomes.",
    ],
    tip: "There's no reliable source of real historical vinyl prices, so early history is an estimate. Real, dated history builds up the longer you keep the record in your collection.",
  },
  {
    id: "collection-dna",
    eyebrow: "Your collection",
    title: "Read your Collection DNA",
    blurb: "Collection DNA is a taste fingerprint at the top of My Collection. It reads your shelf back to you and grows in stages as you add records.",
    steps: [
      "Open My Collection — the DNA panel sits at the top, with a progress ladder showing what unlocks next.",
      "The Fingerprint unlocks at 20 records: your dominant era, genres and the span of years your collection covers.",
      "The Read unlocks at 35 records: a short written verdict on your taste. Tap Open your taste profile to read it.",
      "The Deep Read unlocks at 50 records: your value shape, the condition your shelf skews to, and your single most valuable record.",
      "As your collection shifts, the DNA re-reads itself, and we'll flag when your taste profile has changed.",
    ],
    tip: "Sections above your current count show blurred until you reach the record count that unlocks them — the ladder tells you how many more to go.",
  },
  {
    id: "next-record",
    eyebrow: "Your collection",
    title: "Find your next record",
    blurb: "Your Next Record suggests one record to hunt next, chosen from the gaps in your taste and the canon you don't yet own.",
    steps: [
      "Add at least 10 records — Your Next Record unlocks there, in My Collection.",
      "Tap the face-down card to reveal the pick and a short note on why it suits your collection.",
      "Add it to your wishlist to track its price, or dismiss it.",
      "Once your collection has grown by another 10 or so, use Pick again to get a fresh suggestion.",
    ],
    tip: "The pick leans toward records that fit the eras and genres you already collect, with a nudge toward the more essential entries in the hundred.",
  },
  {
    id: "wishlist",
    eyebrow: "Your collection",
    title: "Build a wishlist & watch your grails",
    blurb: "Keep a list of the records you want, and Grail Watch tracks what they're worth so you know when to buy.",
    steps: [
      "In My Collection, switch to the Wishlist tab and choose Add to wishlist.",
      "Add the records you're hunting the same way you add ones you own — search, snap the cover, or enter by hand.",
      "Each wishlist record is valued and its price tracked over time, so you can see when a grail is climbing or dipping.",
      "When you buy one, add it to your collection and remove it from the wishlist.",
    ],
    tip: "Your wishlist is your own — it doesn't affect your collection's value or where you sit on the leaderboards.",
  },
  {
    id: "leaderboards",
    eyebrow: "Community",
    title: "Climb the collector leaderboards",
    blurb: "Collections are private until you say otherwise. See how you rank by value, genre and how much of the canon you own — under your name if you go public, anonymously if you don't.",
    steps: [
      "Build out your collection — the more (and the better the condition) you add, the higher you rank.",
      "Open Leaderboards to see the rankings by total value, by genre and by share of the canon owned.",
      "Use the Public / Private switch on your collection page to put your name and your shelf on the board.",
      "Find your own row to see where you currently stand — it's marked \"You\".",
      "Click any collector who has gone public to browse their shelf.",
    ],
    tip: "Staying private doesn't cost you your place: your rank still counts, it just reads \"Anonymous collector\" and your total stays hidden. Going public shows your display name, your conditions and your estimated values.",
  },
  {
    id: "levels",
    eyebrow: "Community",
    title: "Level up as a collector",
    blurb: "The more records you own, the higher your collector level. Your level shows as a badge on My Collection and next to your name on the leaderboards.",
    steps: [
      "Add records to your collection — your level is based on how many you own.",
      "You start at Beginner and reach New Spinner at 10 records, Enthusiast at 50, Connoisseur at 100, then Collector, Serious Collector, Archivist, Curator, Master Collector and Grandmaster Collector at 10,000.",
      "Tap your level badge to see the full ladder with your current tier highlighted and how far to the next one.",
      "When you cross a threshold we celebrate the level-up — and your new badge shows wherever your collection appears.",
    ],
    tip: "Level is about how much you've catalogued, not value — so every record you add, however humble, counts toward the next tier.",
  },
  {
    id: "import",
    eyebrow: "Your collection",
    title: "Import an existing collection",
    blurb: "Already track your records elsewhere? Bring them across in one go — connect Discogs directly, or upload a CSV.",
    steps: [
      "Open My Collection and choose Import.",
      "Connect Discogs — sign in to Discogs when prompted and we'll pull your collection across automatically. It's read-only; we never change anything on your Discogs account.",
      "Or upload a CSV — export from Discogs (or any spreadsheet) and include artist, title and, where you can, label, catalogue number, format and condition.",
      "We match each record to a release, show you what we found, and de-duplicate against what you already have before adding anything.",
      "Imported records show as Valuation loading while we price them, then settle automatically — usually within about 48 hours.",
    ],
    tip: "Either way, the more detail you bring across (label, catalogue number, format, condition) the more precisely we can match the exact pressing and value it.",
  },
  {
    id: "invite",
    eyebrow: "Community",
    title: "Invite a friend",
    blurb: "Share The Lead-In with someone who'll appreciate it.",
    steps: [
      "Open My Collection and click Invite a friend.",
      "Use the share sheet to send the link by message, or copy the link and paste it wherever you like.",
      "They land on a welcome view that introduces the site and prompts them to start their own collection.",
    ],
  },
  {
    id: "the-list",
    eyebrow: "Reading the site",
    title: "Read the list & the essays",
    blurb: "The Lead-In is one definitive, ever-evolving ranking of the 100 greatest albums — every placement defended in writing.",
    steps: [
      "Open The List 100→1 to browse the full ranking counted down from 100 to 1.",
      "Click any album to read its full essay, scoring data and pressing guide.",
      "Explore Deep Dives for full album dossiers that sit outside the ranked hundred — a new one every week.",
    ],
  },
];

/* ---- FAQ ------------------------------------------------------------- */
const HELP_FAQS = [
  {
    q: "Is The Lead-In free to use?",
    a: "Yes. Reading the list, the essays and the deep dives is free, and creating an account to track and value your collection is free too.",
  },
  {
    q: "Do I need an account to read the site?",
    a: "No. The whole publication — the ranked hundred, the essays and the deep dives — is open to read without signing in. You only need an account to save a collection, get valuations and appear on the leaderboards.",
  },
  {
    q: "How accurate are the valuations?",
    a: "Valuations are indicative estimates based on the specific pressing you own and the condition you set, drawn from public marketplace data and our own editorial judgement. They're a useful guide, not formal appraisals, and shouldn't be treated as investment advice. Condition is the single biggest factor, so set it as honestly as you can.",
  },
  {
    q: "Why does my new record say “Pending valuation”?",
    a: "When you add a record we queue it for pricing. That usually settles within about 48 hours, after which its estimated value and value chart appear automatically.",
  },
  {
    q: "How do I work out which pressing I own?",
    a: "Open the Pressing Guide and use the runout/matrix identifier: type the artist, the title and the code etched into the record's run-out groove exactly as it appears, and we'll match it to the catalogued pressing along with current prices.",
  },
  {
    q: "Are my collection and ranking public?",
    // This said "every collection on the leaderboards is public" — untrue, and
    // untrue in the direction that matters: collections are private by default,
    // and a private collector ranks anonymously. gen_seo.py's HELP_FAQS was
    // corrected but this copy wasn't, so the crawlable /help fallback told the
    // truth while the app told signed-in readers the opposite. Same defect as
    // REL-03, inverted. Keep the two in sync — gen_seo.py says so too.
    a: "Your ranking is; your collection is only public if you choose. A public collection can be opened by anyone — the records, their condition and their estimated value — and appears on the leaderboards under your display name. Keep it private and you still hold your place on the board, with your rank, your total and your record count shown, but no name, no list of records, and no page anyone can open.",
  },
  {
    q: "Can I import my collection from Discogs or a spreadsheet?",
    a: "Yes. Use Import in My Collection. You can connect Discogs directly — sign in when prompted and we'll pull your collection across (read-only; we never change your Discogs account) — or upload a CSV. A Discogs export works well as a CSV too; include as many columns as you can (artist, title, label, catalogue number, format and condition) for the best matches.",
  },
  {
    q: "What is Collection DNA and when does it unlock?",
    a: "Collection DNA is a taste fingerprint at the top of My Collection that reads your shelf back to you. It grows in stages: the Fingerprint (era, genres and span) unlocks at 20 records, The Read (a short written verdict on your taste) at 35, and the Deep Read (value shape, condition and your most valuable record) at 50. A progress ladder shows how far you are from each. Sections you haven't unlocked yet appear blurred until you reach the record count that opens them.",
  },
  {
    q: "How does Your Next Record work?",
    a: "Once you own at least 10 records, Your Next Record suggests one album to hunt next — chosen from the gaps in your taste and the canon you don't yet own. Tap the card to reveal the pick and why it suits you, then add it to your wishlist. After your collection grows by another 10 or so, you can pick again for a fresh suggestion.",
  },
  {
    q: "What's the difference between my collection and my wishlist?",
    a: "Your collection is what you own; your wishlist is what you want. Switch between them with the Collection / Wishlist tabs in My Collection. Wishlist records are valued and price-tracked too (that's Grail Watch), so you can see when something you're hunting is climbing — but your wishlist doesn't count toward your collection's value or your leaderboard ranking.",
  },
  {
    q: "What are collector levels and badges?",
    a: "As your collection grows you climb prestige tiers — Beginner, then New Spinner at 10 records, Enthusiast at 50, Connoisseur at 100, and on up to Grandmaster Collector at 10,000. Your level shows as a badge on My Collection and beside your name on the leaderboards, and we celebrate each level-up. It's based on how many records you own, not their value.",
  },
  {
    q: "How do I send feedback or report a bug?",
    a: "Use the Feedback tab that floats at the edge of the page on My Collection, the Leaderboards, the Pressing Guide and here in Help — leave a quick note and it comes straight to us. You can also email " + HELP_CONTACT_EMAIL + " any time.",
  },
  {
    q: "How do I change my email, password or display name?",
    a: "Sign in, open the account menu in the top-right and choose Account settings. You can update your details and manage your account there.",
  },
  {
    q: "How do I delete a record, or my whole account?",
    a: "You can remove individual records from your collection at any time. To delete your account and all associated data, email us at " + HELP_CONTACT_EMAIL + " and we'll take care of it.",
  },
  {
    q: "I found a mistake in an essay, ranking or pressing detail. What should I do?",
    a: "We want the site to be right — tell us. Email " + HELP_CONTACT_EMAIL + " with the album and what's wrong, and we'll review it.",
  },
  {
    q: "How do I unsubscribe from emails?",
    a: "Every email we send has an unsubscribe link at the bottom — one click and you're off the list. You can also email us and we'll remove you.",
  },
  {
    q: "Do you use affiliate links?",
    a: "Some links to buy vinyl are affiliate links, so we may earn a small commission at no extra cost to you. It never influences our rankings or what we write — and we always disclose it.",
  },
];

/* A single collapsible FAQ row. */
function HelpFaqItem({ item, open, onToggle }) {
  return (
    <div className={"help-faq-item" + (open ? " help-faq-item--open" : "")}>
      <button className="help-faq-q" onClick={onToggle} aria-expanded={open}>
        <span>{item.q}</span>
        <span className="help-faq-icon" aria-hidden="true">{open ? "−" : "+"}</span>
      </button>
      {open && (
        <div className="help-faq-a">
          <p>{item.a}</p>
        </div>
      )}
    </div>
  );
}

function Help({ onHome, onBack, onCollection, onPressingGuide, onLeaderboards, onList }) {
  const [query, setQuery] = useHelpState("");
  const [openId, setOpenId] = useHelpState(null);

  const q = query.trim().toLowerCase();
  const filteredFaqs = useHelpMemo(() => {
    if (!q) return HELP_FAQS;
    return HELP_FAQS.filter(
      (f) => f.q.toLowerCase().includes(q) || f.a.toLowerCase().includes(q)
    );
  }, [q]);
  const filteredGuides = useHelpMemo(() => {
    if (!q) return HELP_GUIDES;
    return HELP_GUIDES.filter(
      (g) =>
        g.title.toLowerCase().includes(q) ||
        g.blurb.toLowerCase().includes(q) ||
        g.steps.some((s) => s.toLowerCase().includes(q))
    );
  }, [q]);

  const mailto =
    "mailto:" +
    HELP_CONTACT_EMAIL +
    "?subject=" +
    encodeURIComponent("The Lead-In — support request");

  return (
    <main className="help-page">
      <div className="help-wrap">
        <button className="pg-back" onClick={onBack || onHome}>← Back</button>

        <div className="pg-eyebrow">Help &amp; support</div>
        <h1 className="pg-h1">How can we help?</h1>
        <p className="pg-intro">
          Everything you need to get the most out of The Lead-In — step-by-step guides to the main
          features, answers to common questions, and a way to reach a real person if you're stuck.
        </p>

        {/* Search */}
        <div className="help-search">
          <input
            className="help-search-input"
            type="search"
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            placeholder="Search help — e.g. valuation, import, password…"
            aria-label="Search help"
          />
          {q && (
            <button className="help-search-clear" onClick={() => setQuery("")} aria-label="Clear search">
              Clear
            </button>
          )}
        </div>

        {/* Quick links */}
        {!q && (
          <div className="help-quick">
            <span className="help-quick-head">Jump to</span>
            <div className="help-quick-row">
              <a className="help-chip" href="#help-guides">How-to guides</a>
              <a className="help-chip" href="#help-faq">FAQ</a>
              <a className="help-chip" href="#help-contact">Contact us</a>
              {onCollection && <button className="help-chip" onClick={onCollection}>My Collection</button>}
              {onPressingGuide && <button className="help-chip" onClick={onPressingGuide}>Pressing Guide</button>}
              {onLeaderboards && <button className="help-chip" onClick={onLeaderboards}>Leaderboards</button>}
            </div>
          </div>
        )}

        {/* ============ HOW-TO GUIDES ============ */}
        <section id="help-guides" className="help-section">
          <h2 className="help-h2">How-to guides</h2>
          {filteredGuides.length === 0 && (
            <p className="help-empty">No guides match “{query}”. Try the FAQ below, or get in touch.</p>
          )}
          <div className="help-guides">
            {filteredGuides.map((g) => (
              <article className="help-guide" key={g.id} id={"help-" + g.id}>
                <div className="help-guide-eyebrow">{g.eyebrow}</div>
                <h3 className="help-guide-title">{g.title}</h3>
                <p className="help-guide-blurb">{g.blurb}</p>
                <ol className="help-steps">
                  {g.steps.map((s, i) => (
                    <li key={i}>{s}</li>
                  ))}
                </ol>
                {g.tip && <p className="help-tip">{g.tip}</p>}
              </article>
            ))}
          </div>
        </section>

        {/* ============ FAQ ============ */}
        <section id="help-faq" className="help-section">
          <h2 className="help-h2">Frequently asked questions</h2>
          {filteredFaqs.length === 0 && (
            <p className="help-empty">No questions match “{query}”. Try a different word, or contact us below.</p>
          )}
          <div className="help-faq">
            {filteredFaqs.map((f, i) => (
              <HelpFaqItem
                key={i}
                item={f}
                open={openId === f.q}
                onToggle={() => setOpenId(openId === f.q ? null : f.q)}
              />
            ))}
          </div>
        </section>

        {/* ============ CONTACT ============ */}
        <section id="help-contact" className="help-contact">
          <h2 className="help-contact-h">Still need a hand?</h2>
          <p>
            Can't find what you're looking for? Email us and a real person will get back to you. We read
            every message — questions, bug reports, corrections to the list, account help, all of it.
          </p>
          <a className="help-contact-btn" href={mailto}>Email {HELP_CONTACT_EMAIL}</a>
          <p className="help-contact-note">
            Or write to us directly at{" "}
            <a href={"mailto:" + HELP_CONTACT_EMAIL}>{HELP_CONTACT_EMAIL}</a>. We aim to reply within a
            couple of working days.
          </p>
        </section>
      </div>
    </main>
  );
}

window.Help = Help;
