/* FindMyFrag — Account page.
   Two collections: "Perfumes I have" + "Perfumes I want".
   Fragrantica-pattern (shelves of bottles) but cleaner: paper ground, real
   bottle tiles via the typeset Bottle, honest locality framing at the foot.
   Client-side only (§6). Old /wishlist route redirects here. */

/* global React, FMF, Bottle */

function Account() {
  const [have, setHave] = React.useState(() => FMF.collections.list("have"));
  const [want, setWant] = React.useState(() => FMF.collections.list("want"));

  React.useEffect(() => {
    const on = () => {
      setHave(FMF.collections.list("have"));
      setWant(FMF.collections.list("want"));
    };
    window.addEventListener("fmf:collections-changed", on);
    window.addEventListener("storage", on);
    return () => {
      window.removeEventListener("fmf:collections-changed", on);
      window.removeEventListener("storage", on);
    };
  }, []);

  const resolve = (slugs) => slugs
    .map(s => (FMF.CATALOG_ALL || FMF.CATALOG || []).find(f => f.slug === s))
    .filter(Boolean);

  const haveItems = resolve(have);
  const wantItems = resolve(want);

  const meanLanded = (items) => items.length ? items.reduce((a, f) => a + (f.landed || 0), 0) / items.length : 0;
  const sumLanded  = (items) => items.reduce((a, f) => a + (f.landed || 0), 0);

  return (
    <main>
      <section className="container" style={{ paddingTop: 28, paddingBottom: 14 }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", flexWrap: "wrap", gap: 10 }}>
          <div className="kicker">Account · saved in this browser</div>
          <div className="mono body-xs" style={{ color: "var(--ink-mute)" }}>
            {haveItems.length} have · {wantItems.length} want · <span style={{ color: "var(--ink-soft)" }}>no password · no sync</span>
          </div>
        </div>
      </section>
      <hr className="hairline-k" />

      {/* Masthead */}
      <section className="container" style={{ padding: "64px 32px 24px" }}>
        <h1 className="display-xl" style={{ margin: 0, maxWidth: "14ch" }}>
          Your <span className="fraun-itl">account.</span>
        </h1>
        <p className="fraun body-l" style={{ color: "var(--ink-soft)", marginTop: 20, maxWidth: "54ch" }}>
          Two shelves: what you own, what you want. Lives in this browser only — no password, no email, no cross-device sync. This is the §6 trade-off: privacy by construction, at the cost of portability.
        </p>
      </section>

      {/* Summary stats */}
      <section className="container" style={{ padding: "16px 32px 16px" }}>
        <div className="stack-mobile" style={{
          display: "grid",
          gridTemplateColumns: "repeat(4, 1fr)",
          gap: 0,
          borderTop: "1px solid var(--ink)",
          borderBottom: "1px solid var(--ink)",
        }}>
          <AcctStat label="Perfumes I have"    big={haveItems.length}                          meta={haveItems.length ? `spent \u2248 ${FMF.fmtUsdNoCents(sumLanded(haveItems))}` : "nothing logged"} border={false} />
          <AcctStat label="Perfumes I want"    big={wantItems.length}                          meta={wantItems.length ? `\u2248 ${FMF.fmtUsdNoCents(sumLanded(wantItems))} if you bought all` : "nothing saved"} />
          <AcctStat label="Mean landed \u00b7 have"  big={haveItems.length ? FMF.fmtUsd(meanLanded(haveItems)) : "\u2014"}  meta="per bottle, today's market" />
          <AcctStat label="Mean landed \u00b7 want"  big={wantItems.length ? FMF.fmtUsd(meanLanded(wantItems)) : "\u2014"}  meta="per bottle, today's market" />
        </div>
      </section>

      {/* Shelf: have */}
      <Shelf
        title="Perfumes I have"
        kicker="Owned"
        items={haveItems}
        type="have"
        emptyTitle="Nothing logged yet."
        emptyBody="Open any detail page and press \u201cI have\u201d. It pins here with today's landed price for the record."
      />

      {/* Shelf: want */}
      <Shelf
        title="Perfumes I want"
        kicker="Want list"
        items={wantItems}
        type="want"
        emptyTitle="Empty want list."
        emptyBody="Press \u201cI want\u201d on any detail page. Tracks are price-watched (when live ingestion ships)."
      />

      <hr className="hairline-k" />

      {/* Honest locality footer */}
      <section className="container" style={{ padding: "36px 32px 64px" }}>
        <div className="stack-mobile" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 48 }}>
          <div>
            <div className="kicker" style={{ marginBottom: 12 }}>How this works</div>
            <p className="body-m" style={{ color: "var(--ink-soft)", margin: 0, maxWidth: "52ch" }}>
              Your account lives in this browser's localStorage under{" "}
              <span className="mono" style={{ color: "var(--ink)" }}>findmyfrag:have</span> and{" "}
              <span className="mono" style={{ color: "var(--ink)" }}>findmyfrag:want</span>. Nothing is sent to any server. Clearing site data clears your account. Passwordless email-based sync is planned for when ingestion ships.
            </p>
          </div>
          <div>
            <div className="kicker" style={{ marginBottom: 12 }}>Clear collections</div>
            <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
              <button type="button" onClick={() => { if (confirm("Remove every \u201cI have\u201d entry?")) FMF.collections.clear("have"); }} className="shop-btn shop-btn--ghost">Clear \u201cI have\u201d</button>
              <button type="button" onClick={() => { if (confirm("Remove every \u201cI want\u201d entry?")) FMF.collections.clear("want"); }} className="shop-btn shop-btn--ghost">Clear \u201cI want\u201d</button>
              <button type="button" onClick={() => {
                const blob = new Blob([JSON.stringify({ have: FMF.collections.list("have"), want: FMF.collections.list("want"), exportedAt: new Date().toISOString() }, null, 2)], { type: "application/json" });
                const url = URL.createObjectURL(blob);
                const a = document.createElement("a"); a.href = url; a.download = "findmyfrag-account.json"; a.click();
                URL.revokeObjectURL(url);
              }} className="shop-btn">Export as JSON</button>
            </div>
          </div>
        </div>
      </section>
    </main>
  );
}

function Shelf({ title, kicker, items, type, emptyTitle, emptyBody }) {
  return (
    <section className="container" style={{ padding: "48px 32px 16px" }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 18, flexWrap: "wrap", gap: 10 }}>
        <div>
          <div className="kicker" style={{ marginBottom: 6 }}>{kicker} \u00b7 {items.length}</div>
          <h2 className="fraun" style={{ fontSize: 32, letterSpacing: "-0.018em", margin: 0 }}>{title}</h2>
        </div>
      </div>
      {items.length === 0 ? (
        <div style={{ border: "1px dashed var(--rule)", padding: "36px 28px", maxWidth: "54ch" }}>
          <div className="fraun" style={{ fontSize: 22, lineHeight: 1.3, color: "var(--ink)", marginBottom: 10 }}>
            {emptyTitle}
          </div>
          <p className="body-m" style={{ color: "var(--ink-soft)", margin: 0 }}>{emptyBody}</p>
        </div>
      ) : (
        <div className="shelf">
          {items.map(f => (
            <a key={f.slug} href={`#/fragrance/${f.slug}`} className="shelf__tile">
              <Bottle slug={f.slug} label={f.name} showLabel={false} style={{ padding: 0 }} />
              <div className="shelf__brand">{f.brand}</div>
              <div className="shelf__name">{f.name}</div>
              <div className="shelf__landed">{FMF.fmtUsd(f.landed || 0)} \u00b7 landed</div>
            </a>
          ))}
        </div>
      )}
    </section>
  );
}

function AcctStat({ label, big, meta, border = true }) {
  return (
    <div style={{ padding: "22px 24px", borderLeft: border ? "1px solid var(--rule)" : 0 }}>
      <div className="kicker" style={{ marginBottom: 8 }}>{label}</div>
      <div className="fraun" style={{ fontSize: 36, letterSpacing: "-0.02em", lineHeight: 1 }}>{big}</div>
      <div className="mono body-xs" style={{ color: "var(--ink-mute)", marginTop: 8 }}>{meta}</div>
    </div>
  );
}

/* ──────────────────────────────────────────────────────────────────────
   FORUMS — honest placeholder until real backend ships. Meanwhile: a
   curated reading list of the best existing fragrance communities.
   §3/§7: do not fake community we don't have.
   ────────────────────────────────────────────────────────────────────── */
function Forums() {
  // Member counts are public-facing from each forum's landing page, rounded
  // to the nearest thousand. Refreshed manually until backend ingestion lands.
  // Order is by size so the visual popularity sort matches the bar width.
  const boards = [
    { name: "r/fragrance",            users: 312000, url: "https://www.reddit.com/r/fragrance/",           blurb: "The biggest mainstream community. Reviews, IDs, deal spots, no-flex-zone discussions." },
    { name: "Fragrantica Club",       users: 220000, url: "https://www.fragrantica.com/board/",            blurb: "Large, high-traffic, moderated. Good for breaking release news + community surveys." },
    { name: "Basenotes",              users: 140000, url: "https://basenotes.com/community/",              blurb: "Longest-standing fragrance forum on the web. Searchable archives going back 20 years." },
    { name: "Parfumo Forum",          users: 88000,  url: "https://www.parfumo.net/Forum",                 blurb: "Europe-weighted, multilingual. Niche house expertise lives here." },
    { name: "r/MaleFragranceAdvice",  users: 68000,  url: "https://www.reddit.com/r/MaleFragranceAdvice/", blurb: "Recommendation-oriented. Less deal-hunting, more signature-scent questions." },
    { name: "r/fragranceclones",      users: 41000,  url: "https://www.reddit.com/r/fragranceclones/",     blurb: "Honest reviews of clones and Alexandria-style reformulations. The sister sub's mirror." },
    { name: "r/fragranceswap",        users: 24000,  url: "https://www.reddit.com/r/fragranceswap/",       blurb: "Peer-to-peer swap + sample market. Bring verification, expect scrutiny." },
  ];
  const maxUsers = Math.max(...boards.map(b => b.users));
  const fmtUsers = (n) => n >= 1_000_000 ? (n / 1_000_000).toFixed(1) + "M"
                       : n >= 1_000     ? Math.round(n / 1_000) + "k"
                       : String(n);

  return (
    <main>
      <section className="container" style={{ paddingTop: 28, paddingBottom: 14 }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
          <div className="kicker">Forums · reading list</div>
          <div className="mono body-xs" style={{ color: "var(--ink-mute)" }}>
            honest placeholder · real forums launch with backend
          </div>
        </div>
      </section>
      <hr className="hairline-k" />

      {/* Cover */}
      <section className="container" style={{ padding: "64px 32px 28px" }}>
        <h1 className="display-xl" style={{ margin: 0, maxWidth: "16ch" }}>
          Where the <span className="fraun-itl">hobby</span> actually talks.
        </h1>
        <p className="fraun body-l" style={{ color: "var(--ink-soft)", marginTop: 22, maxWidth: "52ch" }}>
          FindMyFrag's own forums launch when we ship ingestion and passwordless accounts — there's no point opening a board we can't moderate or persist. Until then, a curated reading list of the communities that already do this well.
        </p>
        <p className="mono body-xs" style={{ color: "var(--ink-mute)", marginTop: 14, letterSpacing: "0.04em" }}>
          We do not simulate community we don't have<Cite n={3} check="verified" />.
        </p>
      </section>

      {/* Reading list — sorted by member count so the bars visually rank
          which communities are popping right now. */}
      <section className="container" style={{ padding: "24px 32px 56px" }}>
        <div className="kicker" style={{ marginBottom: 18 }}>Seven boards worth your time · ranked by active members</div>
        <div style={{ borderTop: "1px solid var(--ink)" }}>
          {boards.map(b => {
            const pct = (b.users / maxUsers) * 100;
            return (
              <a key={b.url} href={b.url} target="_blank" rel="noopener noreferrer"
                 className="forums-row"
                 style={{
                   display: "grid",
                   gridTemplateColumns: "240px 1fr 160px",
                   gap: 28,
                   padding: "22px 0",
                   borderBottom: "1px solid var(--rule)",
                   textDecoration: "none",
                   color: "inherit",
                   alignItems: "center",
                 }}>
                <div className="fraun" style={{ fontSize: 24, letterSpacing: "-0.012em", lineHeight: 1.15 }}>{b.name}</div>
                <p className="body-m" style={{ color: "var(--ink-soft)", margin: 0, maxWidth: "58ch" }}>{b.blurb}</p>
                <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-end", gap: 6 }}>
                  <div className="mono" style={{ display: "flex", alignItems: "baseline", gap: 6, color: "var(--ink)" }}>
                    <span style={{ fontSize: 22, letterSpacing: "-0.015em", fontFeatureSettings: '"tnum","zero"' }}>
                      {fmtUsers(b.users)}
                    </span>
                    <span className="body-xs" style={{ color: "var(--ink-mute)", letterSpacing: "0.08em", textTransform: "uppercase" }}>
                      members
                    </span>
                  </div>
                  <div style={{ width: 150, height: 3, background: "var(--paper-deep)", position: "relative", overflow: "hidden" }}>
                    <div style={{ position: "absolute", inset: 0, width: `${pct}%`, background: "var(--oxblood)" }} />
                  </div>
                </div>
              </a>
            );
          })}
        </div>
      </section>

      <hr className="hairline" />

      {/* What ships when backend lands */}
      <section className="container" style={{ padding: "40px 32px 64px" }}>
        <div className="kicker" style={{ marginBottom: 16 }}>What our forums will be</div>
        <ol className="fraun" style={{ fontSize: 19, lineHeight: 1.65, color: "var(--ink-soft)", maxWidth: "58ch", paddingLeft: 20, margin: 0 }}>
          <li style={{ marginBottom: 8 }}>Per-fragrance discussion threads, seeded from the detail-page ledger so price context is one click away.</li>
          <li style={{ marginBottom: 8 }}>Batch-code authenticity reports auto-linking to <a href="#/authenticate" style={{ color: "var(--ink)", textDecoration: "underline", textUnderlineOffset: 3 }}>/authenticate</a> and populating §4's complaint log.</li>
          <li style={{ marginBottom: 8 }}>Weekly "deal spot" threads pinned to retailer rows, auto-archived to /issue.</li>
          <li style={{ marginBottom: 8 }}>Signed moderator notes · public sanction log · editorial firewall<Cite n={7} check="separated" /> between commerce and community.</li>
          <li>Zero ads. Zero tracking. Same refusals as the rest of the site.</li>
        </ol>
      </section>
    </main>
  );
}

// Expose both under the old `Wishlist` export so existing router references
// don't break while we migrate.
const Wishlist = Account;
Object.assign(window, { Wishlist, Account, Forums });
