/* global React, Brand, Icon, ALL_CALCS, fmtUSD */
const { useState } = React;

const CALC_URLS = {
  mortgage: "/calcs/mortgage/",
};

/* ============================================================
   Editorial-index Homepage — pill-list directory
   ============================================================ */

const HERO_STATS = [
  { v: "19", l: "calculators" },
  { v: "4", l: "categories" },
  { v: "0", l: "popups, ever" },
];

const RECENT = [
  {
    cat: "Finance · Mortgage",
    title: "$425,000 home, 20% down, 6.85%",
    result: "$2,228",
    unit: "/mo",
    when: "Yesterday",
  },
  {
    cat: "Health · Calorie",
    title: "Maintain 75kg, moderately active",
    result: "2,420",
    unit: "kcal/day",
    when: "Mar 12",
  },
  {
    cat: "Tax · Sales tax",
    title: "$1,899 purchase, CA",
    result: "$172.90",
    unit: "tax",
    when: "Mar 6",
  },
];

const CAT_DEFS = [
  { id: "finance", label: "Finance",     accent: "#2a6fdb" },
  { id: "health",  label: "Health",      accent: "#1f8a5b" },
  { id: "time",    label: "Time & Date", accent: "#d18a1a" },
  { id: "tax",     label: "Tax",         accent: "#7a5ae0" },
];

// Short label for pills

const FEATURED = [
  {
    id: "mortgage", target: "calc",
    cat: "Finance", accent: "#2a6fdb",
    name: "Mortgage",
    sample: "$2,228",
    unit: "/mo",
    sub: "$425k · 30yr · 6.85%",
  },
  {
    id: "compound", target: "compound",
    cat: "Finance", accent: "#2a6fdb",
    name: "Compound Interest",
    sample: "$489k",
    unit: "@25y",
    sub: "$10k + $500/mo @ 7%",
  },
  {
    id: "bmi", target: "bmi",
    cat: "Health", accent: "#1f8a5b",
    name: "BMI",
    sample: "23.4",
    unit: "healthy",
    sub: "178cm · 74kg",
  },
  {
    id: "tz", target: "tz",
    cat: "Time & Date", accent: "#d18a1a",
    name: "Time Zone",
    sample: "7:00 AM",
    unit: "→ Tokyo",
    sub: "2 PM SF · +17h",
  },
];

const shortName = (calc) => {
  const map = {
    "loan-comp": "Loan Comparison",
    "compound": "Compound Interest",
    "refi": "Refinance",
    "auto": "Auto Loan",
    "calorie": "Calorie",
    "macro": "Macro",
    "bodyfat": "Body Fat",
    "pregnancy": "Pregnancy",
    "age": "Age",
    "countdown": "Countdown",
    "timezone": "Time Zone",
    "datediff": "Date Diff",
    "salestax": "Sales Tax",
    "income-tax": "Income Tax",
    "payroll": "Payroll",
    "roi": "ROI",
    "bmi": "BMI",
    "mortgage": "Mortgage",
    "retirement": "Retirement",
  };
  return map[calc.id] || calc.name.replace(" Calculator", "");
};

const Home = () => {
  return (
    <div className="dc-shell" style={{ paddingTop: 56, paddingBottom: 80 }}>
      <Hero />
      <Directory />
      <RecentStrip />
      <FeatureCallouts />
    </div>
  );
};
window.Home = Home;

/* ---------- Hero ---------- */
const Hero = () => (
  <section style={{
    padding: "32px 0 48px",
    display: "grid",
    gridTemplateColumns: "minmax(0, 1fr) auto",
    gap: 32,
    alignItems: "end",
  }}>
    <div>
      <div className="dc-eyebrow" style={{ marginBottom: 14 }}>
        <span className="dc-pill accent" style={{ marginRight: 10 }}>v0.1 · launching soon</span>
        Calculators that respect your time
      </div>
      <h1 style={{
        fontFamily: "var(--font-display)",
        fontSize: "clamp(44px, 6.4vw, 84px)",
        fontWeight: 800, letterSpacing: "-.045em", lineHeight: ".95",
        margin: "0 0 20px",
      }}>
        Every calculator,<br />on one page.
      </h1>
      <p style={{ color: "var(--muted)", fontSize: 18, maxWidth: 560, margin: 0 }}>
        Free, beautifully built, plainly explained. Pick one and start — no signup, no popups.
      </p>
      <div style={{ display: "flex", gap: 10, marginTop: 24, flexWrap: "wrap" }}>
        <a className="dc-btn primary lg" href="/calcs/mortgage/">
          Try the Mortgage Calculator
          <Icon name="arrow" size={14} />
        </a>
        <button className="dc-btn lg">Browse all 19</button>
      </div>
    </div>
    <div style={{ display: "flex", gap: 28, alignSelf: "end", paddingBottom: 8 }}>
      {HERO_STATS.map((s) => (
        <div key={s.l} style={{ borderLeft: "1px solid var(--rule-strong)", paddingLeft: 14 }}>
          <div className="display num" style={{ fontSize: 32 }}>{s.v}</div>
          <div className="dc-eyebrow" style={{ marginTop: 4 }}>{s.l}</div>
        </div>
      ))}
    </div>
  </section>
);

/* ---------- Directory — pill-list, the new focal point ---------- */
const Directory = () => {
  const grouped = CAT_DEFS.map((c) => ({
    ...c,
    items: ALL_CALCS.filter((x) =>
      (c.id === "finance" && x.cat === "Finance") ||
      (c.id === "health"  && x.cat === "Health") ||
      (c.id === "time"    && x.cat === "Time & Date") ||
      (c.id === "tax"     && x.cat === "Tax & Business")
    ),
  }));

  return (
    <section className="dc-directory">
      <div className="dc-directory-head">
        <h2>Pick a calculator</h2>
        <span className="dc-eyebrow">{ALL_CALCS.length} live · more on the way</span>
      </div>

      <div className="dc-featured-section">
        <div className="dc-featured-head">
          <span className="dc-eyebrow">Most used this week</span>
          <span className="dc-featured-meta">Updated daily</span>
        </div>
        <div className="dc-featured">
          {FEATURED.map((f) => (
            <button
              key={f.id}
              className="dc-feat"
              onClick={() => { if (CALC_URLS[f.id]) window.location.href = CALC_URLS[f.id]; }}
            >
              <div className="dc-feat-head">
                <span className="dc-feat-name">{f.name}</span>
                <span className="dc-feat-popular">popular</span>
              </div>
              <div className="dc-feat-sample">
                <span className="display num">{f.sample}</span>
                {f.unit && <span className="dc-feat-unit">{f.unit}</span>}
              </div>
              <div className="dc-feat-foot">
                <span className="dc-feat-meta-row">
                  <span className="dc-feat-dot" style={{ background: f.accent }} />
                  <span className="dc-feat-cat">{f.cat}</span>
                </span>
                <span className="dc-feat-sub">{f.sub}</span>
              </div>
            </button>
          ))}
        </div>
      </div>

      <div className="dc-dir-block">
        <div className="dc-dir-block-head">
          <span className="dc-eyebrow">Browse by category</span>
        </div>
        <div className="dc-dir-rows">
        {grouped.map((g) => (
          <div key={g.id} className="dc-dir-row">
            <div className="dc-dir-cat">
              <span
                className="dc-dir-dot"
                style={{ background: g.accent }}
                aria-hidden="true"
              />
              <span className="dc-dir-cat-label">{g.label}</span>
            </div>
            <div className="dc-dir-pills">
              {g.items.map((it) => (
                <button
                  key={it.id}
                  className="dc-pill-btn"
                  onClick={() => { if (CALC_URLS[it.id]) window.location.href = CALC_URLS[it.id]; }}
                >
                  {shortName(it)}
                  {it.popular && <span className="dc-pill-dot" aria-label="popular" />}
                </button>
              ))}
            </div>
          </div>
        ))}
        </div>
      </div>
    </section>
  );
};

/* ---------- Recent strip ---------- */
const RecentStrip = () => (
  <section style={{ padding: "48px 0 16px" }}>
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 14 }}>
      <h2 style={{ fontSize: 18, fontWeight: 600, margin: 0, letterSpacing: "-.005em" }}>
        Continue where you left off
      </h2>
      <a href="#" onClick={(e) => e.preventDefault()} style={{ fontSize: 13, color: "var(--muted)" }}>
        View saved results →
      </a>
    </div>
    <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(280px, 1fr))", gap: 12 }}>
      {RECENT.map((r, i) => (
        <button
          key={i}
          onClick={() => { window.location.href = "/calcs/mortgage/"; }}
          className="dc-card"
          style={{
            textAlign: "left", padding: 16, cursor: "pointer", color: "inherit",
            display: "flex", flexDirection: "column", gap: 8,
            transition: "border-color var(--t-fast), transform var(--t-fast)",
          }}
          onMouseEnter={(e) => e.currentTarget.style.borderColor = "var(--rule-strong)"}
          onMouseLeave={(e) => e.currentTarget.style.borderColor = "var(--rule)"}
        >
          <div className="dc-eyebrow">{r.cat}</div>
          <div style={{ fontSize: 13, color: "var(--muted)", fontWeight: 500 }}>{r.title}</div>
          <div style={{ display: "flex", alignItems: "baseline", gap: 6, marginTop: "auto" }}>
            <span className="display num" style={{ fontSize: 26 }}>{r.result}</span>
            <span style={{ fontSize: 12, color: "var(--muted)" }}>{r.unit}</span>
            <span style={{ marginLeft: "auto", fontSize: 11, color: "var(--faint)" }}>{r.when}</span>
          </div>
        </button>
      ))}
    </div>
  </section>
);

/* ---------- Feature callouts ---------- */
const FeatureCallouts = () => (
  <section style={{ padding: "56px 0 0", borderTop: "1px solid var(--rule)", marginTop: 40 }}>
    <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(240px, 1fr))", gap: 24 }}>
      {[
        { icon: "sparkle", title: "AI explains your result", body: "Don't just see a number — understand it. Every result has plain-English commentary you can ask follow-ups on." },
        { icon: "share", title: "Share with a permalink", body: "Every calculation gets its own URL. Send it in Slack, paste it in an email — your inputs travel too." },
        { icon: "code", title: "Embed on your site", body: "Drop any DigiCalc into your blog, listing, or product page. White-label available." },
        { icon: "info", title: "Methodology, not magic", body: "Every formula is documented. Citations to government sources where it matters (taxes, mortgages)." },
      ].map((f) => (
        <div key={f.title} style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          <span style={{ width: 32, height: 32, borderRadius: 8, background: "var(--accent-soft)", color: "var(--accent)", display: "inline-flex", alignItems: "center", justifyContent: "center" }}>
            <Icon name={f.icon} size={16} />
          </span>
          <h3 style={{ fontSize: 15, margin: "8px 0 0", fontWeight: 600 }}>{f.title}</h3>
          <p style={{ color: "var(--muted)", fontSize: 14, margin: 0 }}>{f.body}</p>
        </div>
      ))}
    </div>
  </section>
);
