/* ============================================================
   METABOLE — App-surface widgets (floating cards + live demos)
   ============================================================ */

/* ---- Small shared bits ---- */
function CardLabel({ icon, children, right }) {
  return (
    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 12 }}>
      <span style={{ display: "inline-flex", alignItems: "center", gap: 8, fontFamily: "var(--mono)", fontSize: 11, letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--ink-3)" }}>
        {icon && <Icon name={icon} size={14} color="var(--sage)" />}{children}
      </span>
      {right}
    </div>
  );
}

/* ---- Next dose card ---- */
function DoseCard({ active = true, style }) {
  return (
    <div className="appcard" style={{ width: 270, ...style }}>
      <CardLabel icon="syringe" right={<span className="chip chip-mint" style={{ fontSize: 11, padding: "3px 9px" }}>Due today</span>}>Next dose</CardLabel>
      <div style={{ display: "flex", alignItems: "baseline", gap: 8 }}>
        <span style={{ fontSize: 26, fontWeight: 700, letterSpacing: "-0.02em" }}>Tirzepatide</span>
      </div>
      <div style={{ display: "flex", gap: 16, marginTop: 4, color: "var(--ink-2)", fontSize: 14 }}>
        <span><b style={{ color: "var(--ink)" }}>7.5</b> mg</span>
        <span className="mono" style={{ color: "var(--ink-3)" }}>·</span>
        <span><b style={{ color: "var(--ink)" }}>37.5</b> units</span>
        <span className="mono" style={{ color: "var(--ink-3)" }}>·</span>
        <span>10 mg/mL</span>
      </div>
      <hr className="hair" style={{ margin: "14px 0" }} />
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 13, color: "var(--ink-2)" }}>
          <Icon name="pin" size={15} color="var(--clay)" /> Left abdomen · rotated
        </div>
        <button className="btn btn-primary btn-sm" style={{ padding: "8px 14px" }}>Log dose</button>
      </div>
    </div>
  );
}

/* ---- Weight card ---- */
function WeightCard({ active = true, style }) {
  return (
    <div className="appcard" style={{ width: 300, ...style }}>
      <CardLabel icon="trend" right={<span style={{ fontSize: 12, fontWeight: 600, color: "var(--green)" }}>▼ 20.4 lb</span>}>Weight trend</CardLabel>
      <div style={{ display: "flex", alignItems: "baseline", gap: 8, marginBottom: 4 }}>
        <span style={{ fontSize: 30, fontWeight: 700, letterSpacing: "-0.02em" }}>193.6</span>
        <span style={{ color: "var(--ink-3)", fontSize: 14 }}>lb</span>
        <span className="mono" style={{ marginLeft: "auto", fontSize: 11, color: "var(--ink-3)" }}>14 WK</span>
      </div>
      <WeightTrend active={active} h={120} compact />
    </div>
  );
}

/* ---- Check-in card ---- */
function CheckinCard({ active = true, style }) {
  const rows = [
    { k: "Energy", v: 4, icon: "bolt", c: "var(--green)" },
    { k: "Sleep", v: 3, icon: "moon", c: "var(--sage)" },
    { k: "Mood", v: 5, icon: "spark", c: "var(--clay)" },
  ];
  return (
    <div className="appcard" style={{ width: 250, ...style }}>
      <CardLabel icon="grid">Daily check-in</CardLabel>
      <div style={{ display: "flex", flexDirection: "column", gap: 13 }}>
        {rows.map((r, i) => (
          <div key={r.k} style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <Icon name={r.icon} size={16} color={r.c} />
            <span style={{ fontSize: 14, width: 52 }}>{r.k}</span>
            <div style={{ display: "flex", gap: 5, marginLeft: "auto" }}>
              {[1, 2, 3, 4, 5].map(n => (
                <span key={n} style={{
                  width: 12, height: 12, borderRadius: 4,
                  background: n <= r.v ? r.c : "var(--mint)",
                  transform: active ? "scale(1)" : "scale(0)",
                  transition: `transform .4s cubic-bezier(.3,1.4,.5,1) ${(i * 5 + n) * 45}ms`,
                }} />
              ))}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ---- Side effect card ---- */
function SideEffectCard({ active = true, style }) {
  const items = [
    { k: "Nausea", lvl: "Mild", w: 28, c: "var(--amber)" },
    { k: "Fatigue", lvl: "Mild", w: 22, c: "var(--sage)" },
    { k: "Constipation", lvl: "None", w: 6, c: "var(--mint-2)" },
  ];
  return (
    <div className="appcard" style={{ width: 264, ...style }}>
      <CardLabel icon="wave" right={<span className="mono" style={{ fontSize: 10, color: "var(--ink-3)" }}>THIS WK</span>}>Side effects</CardLabel>
      <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
        {items.map((it, i) => (
          <div key={it.k}>
            <div style={{ display: "flex", justifyContent: "space-between", fontSize: 13, marginBottom: 5 }}>
              <span>{it.k}</span><span style={{ color: "var(--ink-3)" }}>{it.lvl}</span>
            </div>
            <div style={{ height: 6, borderRadius: 4, background: "var(--mint-soft)", overflow: "hidden" }}>
              <div style={{ height: "100%", borderRadius: 4, background: it.c, width: active ? it.w + "%" : "0%", transition: `width .9s cubic-bezier(.2,.7,.3,1) ${i * 90}ms` }} />
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ---- Hydration / protein rings ---- */
function VitalsCard({ active = true, style }) {
  return (
    <div className="appcard" style={{ width: 250, ...style }}>
      <CardLabel icon="droplet">Today</CardLabel>
      <div style={{ display: "flex", justifyContent: "space-around", alignItems: "center" }}>
        <Ring active={active} pct={78} value="78%" label="HYDRATION" color="var(--sage)" />
        <Ring active={active} pct={91} value="118g" label="PROTEIN" color="var(--green)" />
      </div>
    </div>
  );
}

/* ---- Insight card ("what changed this week") ---- */
function InsightCard({ active = true, style }) {
  return (
    <div className="appcard" style={{ width: 300, background: "var(--green)", color: "#EDF0E8", border: "none", ...style }}>
      <div style={{ display: "flex", alignItems: "center", gap: 8, fontFamily: "var(--mono)", fontSize: 11, letterSpacing: "0.12em", textTransform: "uppercase", opacity: 0.85, marginBottom: 12 }}>
        <Icon name="spark" size={14} color="var(--clay-soft)" /> What changed this week
      </div>
      <p style={{ fontSize: 15.5, lineHeight: 1.5 }}>
        Your <b>protein</b> averaged 112g/day — up 18% — and <span style={{ color: "var(--clay-soft)" }}>nausea dropped on days you hydrated before noon</span>.
      </p>
      <div style={{ display: "flex", gap: 8, marginTop: 14, fontSize: 11.5 }} className="mono">
        <span style={{ padding: "4px 9px", borderRadius: 99, background: "rgba(255,255,255,0.12)" }}>+18% PROTEIN</span>
        <span style={{ padding: "4px 9px", borderRadius: 99, background: "rgba(255,255,255,0.12)" }}>−1.4 LB</span>
      </div>
    </div>
  );
}

/* ---- Injection-site rotation map (abstract) ---- */
function InjectionSiteMap({ active = true }) {
  const zones = [
    { id: "LA", label: "L abdomen", x: 0, y: 0, days: 0, next: true },
    { id: "RA", label: "R abdomen", x: 1, y: 0, days: 14 },
    { id: "LT", label: "L thigh", x: 0, y: 1, days: 7 },
    { id: "RT", label: "R thigh", x: 1, y: 1, days: 11 },
    { id: "LM", label: "L arm", x: 0, y: 2, days: 4 },
    { id: "RM", label: "R arm", x: 1, y: 2, days: 18 },
  ];
  const fresh = (d) => d === 0 ? "var(--clay)" : `color-mix(in oklab, var(--green) ${Math.min(100, d / 18 * 100)}%, var(--mint-2))`;
  return (
    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
      {zones.map((z, i) => (
        <div key={z.id} style={{
          position: "relative", borderRadius: 14, padding: "13px 14px",
          background: z.next ? "var(--mint-soft)" : "var(--surface-2)",
          border: z.next ? "1.5px solid var(--clay)" : "1px solid var(--line)",
          opacity: active ? 1 : 0, transform: active ? "none" : "translateY(8px)",
          transition: `all .5s cubic-bezier(.2,.7,.3,1) ${i * 60}ms`,
        }}>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
            <span style={{ fontSize: 13.5, fontWeight: 600 }}>{z.label}</span>
            <span style={{ width: 11, height: 11, borderRadius: "50%", background: fresh(z.days) }} />
          </div>
          <div className="mono" style={{ fontSize: 10.5, color: z.next ? "var(--clay-deep)" : "var(--ink-3)", marginTop: 4 }}>
            {z.next ? "USE NEXT →" : z.days + " DAYS AGO"}
          </div>
        </div>
      ))}
    </div>
  );
}

/* ---- Interactive compound level estimator ---- */
const COMPOUNDS = [
  { id: "tirz", name: "Tirzepatide", t12: 120, tmax: 24, interval: 168, dose: "7.5 mg", color: "var(--green)" },
  { id: "sema", name: "Semaglutide", t12: 168, tmax: 30, interval: 168, dose: "1.0 mg", color: "var(--sage)" },
  { id: "lira", name: "Liraglutide", t12: 13, tmax: 11, interval: 24, dose: "1.8 mg", color: "var(--clay)" },
  { id: "bpc", name: "BPC-157", t12: 4, tmax: 1.5, interval: 24, dose: "250 mcg", color: "var(--amber)" },
];
function bateman(t, ke, ka) {
  if (t <= 0) return 0;
  return (ke / (ka - ke)) * (Math.exp(-ke * t) - Math.exp(-ka * t));
}
function CompoundEstimator({ active = true }) {
  const [cid, setCid] = useState("tirz");
  const c = COMPOUNDS.find(x => x.id === cid);
  const [t, setT] = useState(c.tmax);
  useEffect(() => { setT(COMPOUNDS.find(x => x.id === cid).tmax); }, [cid]);

  const ke = Math.log(2) / c.t12;
  const ka = ke * 5.2;
  const interval = c.interval;
  const W = 520, H = 190, padL = 10, padR = 10, padT = 14, padB = 26;
  const innerW = W - padL - padR, innerH = H - padT - padB;
  const N = 120;
  const samples = useMemo(() => Array.from({ length: N + 1 }, (_, i) => bateman((i / N) * interval, ke, ka)), [cid]);
  const peak = Math.max(...samples);
  const pts = samples.map((v, i) => [padL + (i / N) * innerW, padT + (1 - v / peak) * innerH]);
  const line = buildPath(pts);
  const area = line + ` L${pts[pts.length - 1][0]} ${padT + innerH} L${pts[0][0]} ${padT + innerH} Z`;

  const lvl = bateman(t, ke, ka) / peak;
  const markX = padL + (t / interval) * innerW;
  const markY = padT + (1 - lvl) * innerH;
  const pct = Math.round(lvl * 100);
  const phase = t < c.tmax * 0.85 ? "Absorbing" : t < c.tmax * 1.8 ? "Near peak" : lvl > 0.35 ? "Declining" : "Trough";
  const phaseColor = phase === "Near peak" ? "var(--green)" : phase === "Trough" ? "var(--clay)" : "var(--sage)";
  const hoursToNext = Math.max(0, interval - t);

  const fmtT = (h) => h < 48 ? h.toFixed(0) + "h" : (h / 24).toFixed(1) + "d";

  return (
    <div>
      <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginBottom: 18 }}>
        {COMPOUNDS.map(x => (
          <button key={x.id} onClick={() => setCid(x.id)} style={{
            padding: "8px 14px", borderRadius: 99, fontSize: 13.5, fontWeight: 600,
            background: cid === x.id ? "var(--green)" : "var(--surface)",
            color: cid === x.id ? "#EDF0E8" : "var(--ink-2)",
            boxShadow: cid === x.id ? "var(--sh-2)" : "inset 0 0 0 1px var(--line)",
            transition: "all .2s",
          }}>{x.name}</button>
        ))}
      </div>

      <div className="m-estimator-body" style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr", gap: 24, alignItems: "center" }}>
        <div>
          <svg viewBox={`0 0 ${W} ${H}`} width="100%" style={{ display: "block", overflow: "visible" }}>
            <defs>
              <linearGradient id="ce-fill" x1="0" y1="0" x2="0" y2="1">
                <stop offset="0%" stopColor="var(--sage)" stopOpacity="0.30" />
                <stop offset="100%" stopColor="var(--sage)" stopOpacity="0" />
              </linearGradient>
            </defs>
            {[0, 0.5, 1].map((f, i) => (
              <line key={i} x1={padL} x2={W - padR} y1={padT + f * innerH} y2={padT + f * innerH} stroke="var(--line)" strokeDasharray="2 4" />
            ))}
            <path d={area} fill="url(#ce-fill)" />
            <path d={line} fill="none" stroke="var(--green)" strokeWidth="2.4" strokeLinecap="round" />
            <line x1={markX} x2={markX} y1={padT} y2={padT + innerH} stroke={c.color} strokeWidth="1.4" strokeDasharray="3 3" opacity="0.55" />
            <circle cx={markX} cy={markY} r="6" fill="var(--green)" stroke="var(--surface)" strokeWidth="2.5" />
            <text x={padL} y={H - 8} fontSize="10" fill="var(--ink-3)" fontFamily="var(--mono)">DOSE</text>
            <text x={W - padR} y={H - 8} fontSize="10" fill="var(--ink-3)" fontFamily="var(--mono)" textAnchor="end">NEXT · {fmtT(interval)}</text>
          </svg>
          <input type="range" min={0} max={interval} step={interval / 200} value={t}
            onChange={e => setT(Number(e.target.value))}
            style={{ width: "100%", marginTop: 8, accentColor: "var(--green)" }} />
          <div style={{ display: "flex", justifyContent: "space-between", marginTop: 2 }}>
            <span className="mono" style={{ fontSize: 11, color: "var(--ink-3)" }}>Time since dose</span>
            <span className="mono" style={{ fontSize: 11, color: "var(--green)", fontWeight: 600 }}>{fmtT(t)}</span>
          </div>
        </div>

        <div style={{ background: "var(--surface-2)", borderRadius: 18, padding: "20px 22px", border: "1px solid var(--line-2)" }}>
          <div className="mono" style={{ fontSize: 10.5, letterSpacing: "0.12em", color: "var(--ink-3)", textTransform: "uppercase" }}>Estimated level</div>
          <div style={{ display: "flex", alignItems: "baseline", gap: 4, margin: "2px 0 6px" }}>
            <span style={{ fontSize: 48, fontWeight: 700, letterSpacing: "-0.03em", lineHeight: 1 }}>{pct}</span>
            <span style={{ fontSize: 20, color: "var(--ink-3)" }}>%</span>
            <span style={{ fontSize: 11, color: "var(--ink-3)", marginLeft: 4 }}>of peak</span>
          </div>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 7, padding: "5px 11px", borderRadius: 99, background: "var(--surface)", fontSize: 12.5, fontWeight: 600, color: phaseColor, boxShadow: "var(--sh-1)" }}>
            <span className="dot" style={{ background: phaseColor }} /> {phase}
          </span>
          <hr className="hair" style={{ margin: "16px 0" }} />
          <div style={{ display: "flex", flexDirection: "column", gap: 9, fontSize: 13 }}>
            <Row k="Half-life" v={fmtT(c.t12)} />
            <Row k="Peak timing" v={"~" + fmtT(c.tmax)} />
            <Row k="Typical dose" v={c.dose} />
            <Row k="Next dose in" v={fmtT(hoursToNext)} accent />
          </div>
        </div>
      </div>
    </div>
  );
}
function Row({ k, v, accent }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
      <span style={{ color: "var(--ink-3)" }}>{k}</span>
      <span style={{ fontWeight: 600, color: accent ? "var(--clay-deep)" : "var(--ink)", fontFamily: "var(--mono)", fontSize: 12.5 }}>{v}</span>
    </div>
  );
}

Object.assign(window, {
  DoseCard, WeightCard, CheckinCard, SideEffectCard, VitalsCard, InsightCard,
  InjectionSiteMap, CompoundEstimator, CardLabel,
});
