/* Help & Support — the site's help centre. Three parts:
   1. How-to guides for the main things you can do (accounts, adding records,
      valuations, leaderboards, 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: "leaderboards",
    eyebrow: "Community",
    title: "Climb the collector leaderboards",
    blurb: "Every collection is public. See how you rank by value, genre and how much of the canon you own.",
    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.",
      "Click any collector to view their public collection.",
      "Find your own row to see where you currently stand.",
    ],
    tip: "Want to keep something private? You control what's in your collection — only add the records you're happy to show.",
  },
  {
    id: "import",
    eyebrow: "Your collection",
    title: "Import an existing collection",
    blurb: "Already track your records elsewhere? Bring them across in one go with a CSV.",
    steps: [
      "Open My Collection and choose Import.",
      "Upload a CSV with your records — include artist, title and, where you can, label, catalogue number, format and condition.",
      "We match each row to a release and de-duplicate against what you already have.",
      "Imported records show as Pending valuation while we price them, then settle automatically.",
    ],
    tip: "A Discogs export works well as a starting point — the more columns you include, the better the matches.",
  },
  {
    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?",
    a: "Yes — every collection on the leaderboards is public, and other collectors can view what you own, its condition and its estimated value. You decide what goes into your collection, so only add what you're comfortable showing.",
  },
  {
    q: "Can I import my collection from Discogs or a spreadsheet?",
    a: "Yes. Use Import in My Collection and upload a CSV. A Discogs export works well — include as many columns as you can (artist, title, label, catalogue number, format and condition) for the best matches.",
  },
  {
    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;
