/* ============================================================
   METABOLE — Sections B: Feature explorer, grid, estimator
   ============================================================ */

function SectionHead({ eyebrow, title, lead, align = "left", maxw = 640 }) {
  return (
    <div style={{ textAlign: align, maxWidth: align === "center" ? maxw : "none", margin: align === "center" ? "0 auto" : 0 }}>
      {eyebrow && <Reveal><span className="eyebrow">{eyebrow}</span></Reveal>}
      <Reveal delay={60}><h2 className="h2" style={{ marginTop: 16 }}>{title}</h2></Reveal>
      {lead && <Reveal delay={120}><p className="lead" style={{ marginTop: 16, maxWidth: maxw, marginLeft: align === "center" ? "auto" : 0, marginRight: align === "center" ? "auto" : 0 }}>{lead}</p></Reveal>}
    </div>
  );
}

function Placeholder({ label, h = 120, r = 14 }) {
  return (
    <div style={{
      height: h, borderRadius: r, position: "relative", overflow: "hidden",
      background: "repeating-linear-gradient(135deg, var(--mint-soft), var(--mint-soft) 10px, var(--surface-2) 10px, var(--surface-2) 20px)",
      border: "1px solid var(--line)", display: "grid", placeItems: "center",
    }}>
      <span className="mono" style={{ fontSize: 11, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--ink-3)", background: "var(--surface)", padding: "4px 10px", borderRadius: 99, boxShadow: "var(--sh-1)" }}>{label}</span>
    </div>
  );
}

/* ---- Tab preview panels ---- */
function PreviewWeight({ active }) {
  const stats = [["Current", "193.6", "lb"], ["Total change", "−20.4", "lb"], ["This week", "−1.4", "lb"], ["To goal", "5.6", "lb"]];
  return (
    <div style={{ display: "grid", gridTemplateRows: "auto 1fr", gap: 16, height: "100%" }}>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 10 }}>
        {stats.map(([k, v, u], i) => (
          <div key={k} style={{ background: "var(--surface-2)", borderRadius: 14, padding: "12px 14px" }}>
            <div className="mono" style={{ fontSize: 9.5, letterSpacing: "0.1em", color: "var(--ink-3)", textTransform: "uppercase" }}>{k}</div>
            <div style={{ fontSize: 22, fontWeight: 700, marginTop: 3, color: v.startsWith("−") ? "var(--green)" : "var(--ink)" }}>{v}<span style={{ fontSize: 12, color: "var(--ink-3)", fontWeight: 500 }}> {u}</span></div>
          </div>
        ))}
      </div>
      <div className="card" style={{ padding: 18, display: "flex", flexDirection: "column", justifyContent: "center" }}>
        <WeightTrend active={active} h={210} />
      </div>
    </div>
  );
}
function PreviewProgress({ active }) {
  return (
    <div style={{ display: "grid", gridTemplateColumns: "1.1fr 0.9fr", gap: 16, height: "100%" }}>
      <div style={{ display: "grid", gridTemplateRows: "1fr 1fr", gap: 12 }}>
        <Placeholder label="Progress photo · wk 1" h={null} />
        <Placeholder label="Progress photo · wk 14" h={null} />
      </div>
      <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
        <CheckinCard active={active} style={{ width: "100%", boxShadow: "var(--sh-2)" }} />
        <div className="card" style={{ padding: 16, flex: 1, display: "flex", alignItems: "center", justifyContent: "space-around" }}>
          <Ring active={active} pct={86} value="14" label="DAY STREAK" color="var(--clay)" />
          <div style={{ fontSize: 13, color: "var(--ink-2)", lineHeight: 1.5 }}>Side-by-side<br />compare any<br />two check-ins.</div>
        </div>
      </div>
    </div>
  );
}
function PreviewSleep({ active }) {
  return (
    <div style={{ display: "grid", gridTemplateRows: "auto 1fr", gap: 16, height: "100%" }}>
      <div className="card" style={{ padding: 18 }}>
        <CardLabel icon="moon" right={<span className="mono" style={{ fontSize: 10, color: "var(--ink-3)" }}>AVG 7.2H</span>}>This week</CardLabel>
        <WeeklyBars active={active} />
      </div>
      <div className="card" style={{ padding: 18, display: "flex", flexDirection: "column", justifyContent: "center" }}>
        <CardLabel icon="grid" right={<span className="mono" style={{ fontSize: 10, color: "var(--ink-3)" }}>16 WK</span>}>Sleep heatmap</CardLabel>
        <SleepHeatmap active={active} />
      </div>
    </div>
  );
}
function PreviewSideEffects({ active }) {
  const tl = [
    { d: "Mon", n: 2, f: 1 }, { d: "Tue", n: 1, f: 1 }, { d: "Wed", n: 3, f: 2 },
    { d: "Thu", n: 1, f: 0 }, { d: "Fri", n: 0, f: 1 }, { d: "Sat", n: 1, f: 0 }, { d: "Sun", n: 0, f: 0 },
  ];
  return (
    <div style={{ display: "grid", gridTemplateColumns: "0.95fr 1.05fr", gap: 16, height: "100%" }}>
      <SideEffectCard active={active} style={{ width: "100%", boxShadow: "var(--sh-2)" }} />
      <div className="card" style={{ padding: 18, display: "flex", flexDirection: "column" }}>
        <CardLabel icon="clock">Symptom timeline</CardLabel>
        <div style={{ display: "flex", alignItems: "flex-end", gap: 10, flex: 1, paddingTop: 8 }}>
          {tl.map((t, i) => (
            <div key={t.d} style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center", gap: 5, height: "100%", justifyContent: "flex-end" }}>
              <div style={{ width: "100%", maxWidth: 18, display: "flex", flexDirection: "column", justifyContent: "flex-end", gap: 3, height: "78%" }}>
                <div style={{ background: "var(--amber)", borderRadius: 4, height: active ? (t.n / 3 * 60 + 2) + "%" : 0, transition: `height .7s ease ${i * 60}ms` }} />
                <div style={{ background: "var(--sage)", borderRadius: 4, height: active ? (t.f / 3 * 40 + 2) + "%" : 0, transition: `height .7s ease ${i * 60 + 40}ms` }} />
              </div>
              <span className="mono" style={{ fontSize: 9.5, color: "var(--ink-3)" }}>{t.d}</span>
            </div>
          ))}
        </div>
        <div style={{ display: "flex", gap: 16, marginTop: 12, fontSize: 11.5, color: "var(--ink-2)" }}>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}><span className="dot" style={{ background: "var(--amber)" }} /> Nausea</span>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}><span className="dot" style={{ background: "var(--sage)" }} /> Fatigue</span>
        </div>
      </div>
    </div>
  );
}
function PreviewInsights({ active }) {
  return (
    <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gridAutoRows: "1fr", gap: 12, height: "100%" }}>
      <div className="card" style={{ padding: 16, display: "flex", flexDirection: "column", justifyContent: "space-between" }}>
        <CardLabel icon="trend">Weight</CardLabel>
        <Sparkline data={[214, 209, 205, 201, 197, 193]} active={active} w={120} h={40} />
        <div style={{ fontSize: 20, fontWeight: 700, color: "var(--green)" }}>−20.4 lb</div>
      </div>
      <div className="card" style={{ padding: 16, display: "grid", placeItems: "center" }}>
        <Ring active={active} pct={91} value="118g" label="PROTEIN" />
      </div>
      <div className="card" style={{ padding: 16, display: "grid", placeItems: "center" }}>
        <Ring active={active} pct={78} value="78%" label="HYDRATION" color="var(--sage)" />
      </div>
      <div className="card" style={{ padding: 16, gridColumn: "span 2", display: "flex", alignItems: "center", gap: 14 }}>
        <CardLabel icon="moon"><span style={{ display: "none" }}>s</span></CardLabel>
        <div style={{ flex: 1 }}>
          <div className="mono" style={{ fontSize: 9.5, letterSpacing: "0.1em", color: "var(--ink-3)", textTransform: "uppercase" }}>Sleep · 7 days</div>
          <WeeklyBars active={active} data={[7.2, 6.4, 8.1, 5.9, 7.8, 6.7, 8.4]} />
        </div>
      </div>
      <div className="card" style={{ padding: 16, display: "flex", flexDirection: "column", justifyContent: "center", gap: 6, background: "var(--mint-soft)", border: "none" }}>
        <Icon name="medal" size={22} color="var(--clay)" />
        <div style={{ fontSize: 14, fontWeight: 700 }}>9 badges</div>
        <div style={{ fontSize: 11.5, color: "var(--ink-2)" }}>this month</div>
      </div>
    </div>
  );
}
function PreviewAI({ active }) {
  const corr = [
    ["Hydration before noon", "↓ Nausea", "var(--green)", 0.74],
    ["Protein ≥ 100g", "↑ Energy next day", "var(--green)", 0.61],
    ["Sleep < 6h", "↑ Reported fatigue", "var(--clay)", 0.68],
  ];
  return (
    <div style={{ display: "grid", gridTemplateRows: "auto 1fr", gap: 16, height: "100%" }}>
      <InsightCard active={active} style={{ width: "100%" }} />
      <div className="card" style={{ padding: 18 }}>
        <CardLabel icon="spark" right={<span className="chip" style={{ fontSize: 10, padding: "3px 8px" }}>Informational</span>}>Correlations found</CardLabel>
        <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
          {corr.map(([a, b, c, str], i) => (
            <div key={i} style={{ display: "flex", alignItems: "center", gap: 12 }}>
              <span style={{ fontSize: 13.5, flex: 1 }}>{a}</span>
              <span style={{ fontSize: 13.5, fontWeight: 600, color: c, width: 150 }}>{b}</span>
              <div style={{ width: 70, height: 6, borderRadius: 4, background: "var(--mint-soft)", overflow: "hidden" }}>
                <div style={{ height: "100%", background: c, width: active ? str * 100 + "%" : 0, transition: `width .8s ease ${i * 100}ms` }} />
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

const FEATURES = [
  { id: "weight", icon: "trend", name: "Weight Log", blurb: "Track weight over time with trend charts and goal tracking — built for GLP-1 protocols.", render: PreviewWeight },
  { id: "progress", icon: "camera", name: "Progress Tracking", blurb: "Log progress photos and track energy, sleep, and mood with daily check-ins.", render: PreviewProgress },
  { id: "sleep", icon: "moon", name: "Sleep Tracker", blurb: "Log sleep and wake times, track quality, and view weekly charts and monthly heatmaps.", render: PreviewSleep },
  { id: "side", icon: "wave", name: "Side-effect journal", blurb: "Record nausea, fatigue, constipation and more — severity over time, at a glance.", render: PreviewSideEffects },
  { id: "dash", icon: "grid", name: "Insights Dashboard", blurb: "All your tracking in one place — weight, side effects, hydration, nutrition, photos, check-ins.", render: PreviewInsights },
  { id: "ai", icon: "spark", name: "AI Insights", blurb: "Personalized correlations across your data, surfacing patterns. For informational reference only.", render: PreviewAI },
];

function FeatureExplorer() {
  const [active, setActive] = useState("weight");
  const [secRef, inView] = useInView({ threshold: 0.1 });
  const cur = FEATURES.find(f => f.id === active);
  const Preview = cur.render;
  return (
    <section id="features" className="section" style={{ padding: "40px 0 90px" }} ref={secRef}>
      <div className="wrap">
        <SectionHead eyebrow="Everything in one place" title={<>Brutally functional.<br />Quietly beautiful.</>} lead="Twelve tools that respect your time and your data. Tap through a few of them." />
        <div className="m-explorer-grid" style={{ display: "grid", gridTemplateColumns: "340px 1fr", gap: 28, marginTop: 44, alignItems: "stretch" }}>
          <Reveal className="hide-mobile" style={{ display: "flex", flexDirection: "column", gap: 4 }}>
            {FEATURES.map(f => (
              <button key={f.id} className={"ftab" + (active === f.id ? " on" : "")} onClick={() => setActive(f.id)}>
                <span style={{ display: "grid", placeItems: "center", width: 38, height: 38, borderRadius: 10, flexShrink: 0, background: active === f.id ? "var(--green)" : "var(--mint-soft)" }}>
                  <Icon name={f.icon} size={19} color={active === f.id ? "#EDF0E8" : "var(--green)"} />
                </span>
                <span>
                  <span style={{ display: "block", fontWeight: 600, fontSize: 16 }}>{f.name}</span>
                  <span style={{ display: "block", fontSize: 13, color: "var(--ink-2)", lineHeight: 1.4, marginTop: 2 }}>{f.blurb}</span>
                </span>
              </button>
            ))}
          </Reveal>
          <Reveal delay={100} className="card" style={{ padding: 22, minHeight: 440, background: "var(--paper-2)" }}>
            <div key={active} style={{ height: "100%", minHeight: 396, animation: "fadeIn .45s ease" }}>
              <Preview active={inView} />
            </div>
          </Reveal>
        </div>
      </div>
    </section>
  );
}

/* ---- Secondary feature grid ---- */
const GRID = [
  { icon: "chat", name: "Pep Bot", blurb: "Ask general educational questions about peptides and GLP-1s. Not medical advice." },
  { icon: "book", name: "Research Library", blurb: "Browse 75+ peptide and GLP-1 compound profiles with summaries and references." },
  { icon: "medal", name: "Achievements", blurb: "Earn badges for consistency — streaks, hydration, nutrition, and check-ins." },
  { icon: "swatch", name: "Themes", blurb: "Customize the look of your app with multiple calm color themes." },
  { icon: "bell", name: "Reminders", blurb: "Gentle dose, refill, and check-in reminders — on your schedule, never naggy." },
  { icon: "droplet", name: "Apple Health sync", blurb: "Pull weight, sleep, and activity automatically. Two-way, private, optional." },
];
function FeatureGrid() {
  return (
    <section className="section" style={{ paddingBottom: 90 }}>
      <div className="wrap">
        <div className="m-feature-grid" style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 16 }}>
          {GRID.map((g, i) => (
            <Reveal key={g.name} delay={i * 60} className="card" style={{ padding: 24 }}>
              <span style={{ display: "grid", placeItems: "center", width: 44, height: 44, borderRadius: 12, background: "var(--mint-soft)" }}>
                <Icon name={g.icon} size={22} color="var(--green)" />
              </span>
              <h3 style={{ fontSize: 19, marginTop: 16 }}>{g.name}</h3>
              <p style={{ fontSize: 14.5, color: "var(--ink-2)", marginTop: 8, lineHeight: 1.5 }}>{g.blurb}</p>
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---- Compound estimator section ---- */
function EstimatorSection() {
  const [ref, inView] = useInView({ threshold: 0.15 });
  return (
    <section id="estimator" className="section" style={{ padding: "70px 0", background: "var(--surface)", borderTop: "1px solid var(--line)", borderBottom: "1px solid var(--line)" }} ref={ref}>
      <div className="wrap">
        <div className="m-split" style={{ display: "grid", gridTemplateColumns: "0.8fr 1.2fr", gap: 48, alignItems: "center" }}>
          <div>
            <SectionHead eyebrow="Compound level estimator" title={<>Always know where<br />you are in the window.</>} lead="View estimated half-life and peak timing for your peptide or GLP-1 — so a missed day or a dose change never leaves you guessing." />
            <div style={{ marginTop: 22, padding: "13px 16px", borderRadius: 14, background: "var(--mint-soft)", display: "flex", gap: 11, alignItems: "flex-start" }}>
              <Icon name="shield" size={18} color="var(--green)" style={{ flexShrink: 0, marginTop: 1 }} />
              <p style={{ fontSize: 13, color: "var(--green-deep)", lineHeight: 1.45 }}>Estimates are educational and based on population averages — not a measurement of your blood levels or a dosing recommendation.</p>
            </div>
          </div>
          <Reveal delay={80} className="card" style={{ padding: 26 }}>
            <CompoundEstimator active={inView} />
          </Reveal>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { SectionHead, Placeholder, FeatureExplorer, FeatureGrid, EstimatorSection });
