// SleepWise — calculator modals (each tool gets a working modal)
const { useState, useMemo, useEffect } = React;

// ---------- Sleep Cycle / Bedtime modals (use hero calc, but offer extended views) ----------
window.SleepCycleModal = function ({ t, lang, onClose }) {
  const [wakeTime, setWakeTime] = useState("07:00");
  const wakeDate = useMemo(() => {
    const [h, m] = wakeTime.split(":").map(Number);
    const d = new Date();
    d.setHours(h, m, 0, 0);
    if (d <= new Date()) d.setDate(d.getDate() + 1);
    return d;
  }, [wakeTime]);
  const beds = SleepMath.bedtimesForWake(wakeDate);
  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <div className="modal-head">
          <div>
            <h3>{t.tools.t1_n}</h3>
            <p>{t.calc.label_wake}</p>
          </div>
          <button className="modal-close" onClick={onClose}>×</button>
        </div>
        <div className="modal-body">
          <input
            type="time"
            value={wakeTime}
            onChange={(e) => setWakeTime(e.target.value)}
            style={{
              background: "var(--card)", border: "1px solid var(--line-2)",
              color: "var(--ink)", padding: "16px 20px", borderRadius: 12,
              fontSize: 24, fontFamily: "var(--serif)", width: "100%", marginBottom: 24,
            }}
          />
          <div style={{ fontFamily: "var(--mono)", fontSize: 11, color: "var(--ink-mute)", textTransform: "uppercase", letterSpacing: "0.15em", marginBottom: 12 }}>
            {t.calc.results_title} · {t.calc.results_sub}
          </div>
          {beds.map((b, i) => (
            <div className={"bedtime-row " + (b.cycles === 5 ? "bedtime-recommended" : "")} key={i}>
              <div>
                <div className="bedtime-time">{SleepMath.fmtTime(b.time, lang)}</div>
                <div className="bedtime-meta">{b.hours} {t.calc.hours} · {b.cycles} {t.calc.cycles}</div>
              </div>
              <div className="bedtime-quality">
                {[1,2,3,4,5].map(n => <span key={n} className={"qual-dot " + (n <= b.quality ? "on" : "")} />)}
              </div>
            </div>
          ))}
          <div style={{ marginTop: 20, fontSize: 12, color: "var(--ink-mute)", fontFamily: "var(--mono)" }}>
            {t.calc.latency}
          </div>
        </div>
      </div>
    </div>
  );
};

// ---------- Sleep Debt Tracker ----------
window.SleepDebtModal = function ({ t, onClose }) {
  const [target, setTarget] = useState(8);
  const [nights, setNights] = useState([7, 6.5, 7.5, 6, 8, 5.5, 7]);
  const debt = nights.reduce((acc, n) => acc + (target - n), 0);
  const status = debt <= 1 ? "Balanced" : debt <= 4 ? "Mild deficit" : debt <= 8 ? "Moderate debt" : "Significant debt";
  const color = debt <= 1 ? "var(--gold)" : debt <= 4 ? "oklch(0.78 0.10 60)" : "oklch(0.70 0.14 30)";
  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <div className="modal-head">
          <div><h3>{t.tools.t3_n}</h3><p>Last 7 nights vs. your target</p></div>
          <button className="modal-close" onClick={onClose}>×</button>
        </div>
        <div className="modal-body">
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 24 }}>
            <span style={{ fontFamily: "var(--mono)", fontSize: 11, color: "var(--ink-mute)", textTransform: "uppercase", letterSpacing: "0.15em" }}>
              Target sleep
            </span>
            <span>
              <input type="range" min="6" max="10" step="0.5" value={target} onChange={(e) => setTarget(+e.target.value)} style={{ width: 200, accentColor: "var(--gold)" }} />
              <span style={{ fontFamily: "var(--serif)", fontSize: 24, marginLeft: 16, color: "var(--gold)" }}>{target}h</span>
            </span>
          </div>

          <div style={{ display: "grid", gridTemplateColumns: "repeat(7, 1fr)", gap: 8, marginBottom: 32, alignItems: "end", height: 180 }}>
            {nights.map((n, i) => {
              const pct = Math.min(100, (n / 10) * 100);
              const tgPct = (target / 10) * 100;
              return (
                <div key={i} style={{ position: "relative", height: "100%", display: "flex", flexDirection: "column", justifyContent: "flex-end", cursor: "pointer" }}
                  onClick={() => {
                    const next = [...nights]; next[i] = Math.max(3, Math.min(10, n + (Math.random() > 0.5 ? 0.5 : -0.5))); setNights(next);
                  }}>
                  <div style={{ position: "absolute", left: 0, right: 0, bottom: `${tgPct}%`, height: 1, background: "var(--gold-soft)", borderTop: "1px dashed var(--gold)" }} />
                  <div style={{ height: `${pct}%`, background: n >= target ? "var(--gold)" : "var(--violet)", borderRadius: 6, opacity: 0.85, transition: "height 0.4s" }} />
                  <div style={{ fontFamily: "var(--mono)", fontSize: 10, color: "var(--ink-mute)", textAlign: "center", marginTop: 6 }}>{["M","T","W","T","F","S","S"][i]}</div>
                  <div style={{ fontFamily: "var(--mono)", fontSize: 11, textAlign: "center" }}>{n}h</div>
                </div>
              );
            })}
          </div>

          <div style={{ borderTop: "1px solid var(--line)", paddingTop: 24, display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
            <div>
              <div style={{ fontFamily: "var(--mono)", fontSize: 11, color: "var(--ink-mute)", textTransform: "uppercase", letterSpacing: "0.15em" }}>Current debt</div>
              <div style={{ fontFamily: "var(--serif)", fontSize: 56, fontWeight: 500, color, lineHeight: 1, marginTop: 4 }}>
                {debt > 0 ? `−${debt.toFixed(1)}h` : `+${(-debt).toFixed(1)}h`}
              </div>
            </div>
            <div style={{ textAlign: "right" }}>
              <div style={{ fontFamily: "var(--mono)", fontSize: 11, color: "var(--ink-mute)", textTransform: "uppercase", letterSpacing: "0.15em" }}>Status</div>
              <div style={{ fontFamily: "var(--serif)", fontSize: 22, marginTop: 4, color }}>{status}</div>
            </div>
          </div>
          <div style={{ marginTop: 16, fontSize: 13, color: "var(--ink-soft)", lineHeight: 1.6 }}>
            Tip — tap any bar to log a different value. Most adults can repay ~1h of debt per long-sleep recovery night.
          </div>
        </div>
      </div>
    </div>
  );
};

// ---------- Nap Calculator ----------
window.NapModal = function ({ t, lang, onClose }) {
  const napTypes = [
    { key: "power", name: "Power Nap", duration: 20, desc: "Boosts alertness; no grogginess. Coffee-nap compatible." },
    { key: "recovery", name: "Recovery", duration: 60, desc: "Improves memory; expect ~10 min of post-nap haze." },
    { key: "full", name: "Full Cycle", duration: 90, desc: "Complete cycle including REM. Wake refreshed." },
  ];
  const [pick, setPick] = useState("power");
  const chosen = napTypes.find(n => n.key === pick);
  const wake = new Date(Date.now() + (chosen.duration + 10) * 60000);
  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <div className="modal-head">
          <div><h3>{t.tools.t4_n}</h3><p>Pick a nap style — we'll set the alarm</p></div>
          <button className="modal-close" onClick={onClose}>×</button>
        </div>
        <div className="modal-body">
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 12, marginBottom: 32 }}>
            {napTypes.map(n => (
              <button key={n.key} onClick={() => setPick(n.key)}
                style={{
                  background: pick === n.key ? "var(--gold-soft)" : "var(--card)",
                  border: "1px solid " + (pick === n.key ? "var(--gold)" : "var(--line-2)"),
                  borderRadius: 16, padding: 20, cursor: "pointer", textAlign: "left",
                  color: "var(--ink)", fontFamily: "var(--sans)",
                }}>
                <div style={{ fontFamily: "var(--mono)", fontSize: 11, color: "var(--gold)", textTransform: "uppercase", letterSpacing: "0.15em" }}>{n.duration} min</div>
                <div style={{ fontFamily: "var(--serif)", fontSize: 20, marginTop: 6, fontWeight: 500 }}>{n.name}</div>
              </button>
            ))}
          </div>
          <div style={{ background: "var(--card)", border: "1px solid var(--line)", borderRadius: 16, padding: 28, textAlign: "center" }}>
            <div style={{ fontFamily: "var(--mono)", fontSize: 11, color: "var(--ink-mute)", textTransform: "uppercase", letterSpacing: "0.15em" }}>If you start now, wake at</div>
            <div style={{ fontFamily: "var(--serif)", fontSize: 64, color: "var(--gold)", fontWeight: 500, lineHeight: 1, margin: "8px 0" }}>{SleepMath.fmtTime(wake, lang)}</div>
            <div style={{ fontSize: 14, color: "var(--ink-soft)", maxWidth: 380, margin: "12px auto 0" }}>{chosen.desc}</div>
          </div>
        </div>
      </div>
    </div>
  );
};

// ---------- Baby Sleep Schedule ----------
window.BabyModal = function ({ t, onClose }) {
  const ages = [
    { age: "0–3 months", wakeWindow: "45–90 min", naps: "4–6 naps", totalSleep: "14–17 h", night: "8–9 h" },
    { age: "4–6 months", wakeWindow: "1.5–2.5 h", naps: "3–4 naps", totalSleep: "12–15 h", night: "10–11 h" },
    { age: "7–9 months", wakeWindow: "2.5–3 h", naps: "2–3 naps", totalSleep: "12–14 h", night: "11 h" },
    { age: "10–12 months", wakeWindow: "3–4 h", naps: "2 naps", totalSleep: "12–14 h", night: "11 h" },
    { age: "13–18 months", wakeWindow: "4–5 h", naps: "1–2 naps", totalSleep: "11–14 h", night: "11 h" },
    { age: "19–24 months", wakeWindow: "5–6 h", naps: "1 nap", totalSleep: "11–14 h", night: "11 h" },
  ];
  const [pick, setPick] = useState(1);
  const cur = ages[pick];
  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <div className="modal-head">
          <div><h3>{t.tools.t5_n}</h3><p>Population averages — adjust to your baby's cues</p></div>
          <button className="modal-close" onClick={onClose}>×</button>
        </div>
        <div className="modal-body">
          <div style={{ display: "flex", flexWrap: "wrap", gap: 8, marginBottom: 28 }}>
            {ages.map((a, i) => (
              <button key={i} onClick={() => setPick(i)}
                style={{
                  background: pick === i ? "var(--ink)" : "transparent",
                  color: pick === i ? "var(--bg)" : "var(--ink-soft)",
                  border: "1px solid " + (pick === i ? "var(--ink)" : "var(--line-2)"),
                  borderRadius: 100, padding: "8px 14px", cursor: "pointer",
                  fontSize: 12, fontFamily: "var(--sans)", fontWeight: 500,
                }}>
                {a.age}
              </button>
            ))}
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 1, background: "var(--line)", border: "1px solid var(--line)", borderRadius: 16, overflow: "hidden" }}>
            {[
              ["Wake window", cur.wakeWindow],
              ["Number of naps", cur.naps],
              ["Total sleep / 24h", cur.totalSleep],
              ["Night sleep", cur.night],
            ].map(([k, v], i) => (
              <div key={i} style={{ background: "var(--bg-2)", padding: 24 }}>
                <div style={{ fontFamily: "var(--mono)", fontSize: 11, color: "var(--ink-mute)", textTransform: "uppercase", letterSpacing: "0.15em" }}>{k}</div>
                <div style={{ fontFamily: "var(--serif)", fontSize: 32, fontWeight: 500, color: "var(--gold)", marginTop: 6 }}>{v}</div>
              </div>
            ))}
          </div>
          <div style={{ marginTop: 16, fontSize: 13, color: "var(--ink-soft)", lineHeight: 1.6 }}>
            Wake window = time between sleeps. The biggest predictor of overtired meltdowns is exceeding the upper end. When in doubt, err shorter.
          </div>
        </div>
      </div>
    </div>
  );
};

// ---------- Jet Lag Planner ----------
window.JetLagModal = function ({ t, onClose }) {
  const [hours, setHours] = useState(7);
  const [direction, setDirection] = useState("east");
  const days = Math.ceil(hours / (direction === "east" ? 1 : 1.5));
  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <div className="modal-head">
          <div><h3>{t.tools.t6_n}</h3><p>Pre-shift your circadian rhythm</p></div>
          <button className="modal-close" onClick={onClose}>×</button>
        </div>
        <div className="modal-body">
          <div style={{ display: "flex", gap: 8, marginBottom: 28 }}>
            <button onClick={() => setDirection("east")} className="btn-ghost" style={{ flex: 1, background: direction === "east" ? "var(--gold-soft)" : "transparent", borderColor: direction === "east" ? "var(--gold)" : "var(--line-2)" }}>← Westward</button>
            <button onClick={() => setDirection("west")} className="btn-ghost" style={{ flex: 1, background: direction === "west" ? "var(--gold-soft)" : "transparent", borderColor: direction === "west" ? "var(--gold)" : "var(--line-2)" }}>Eastward →</button>
          </div>
          <div style={{ marginBottom: 28 }}>
            <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 8 }}>
              <span style={{ fontFamily: "var(--mono)", fontSize: 11, color: "var(--ink-mute)", textTransform: "uppercase", letterSpacing: "0.15em" }}>Time zone shift</span>
              <span style={{ fontFamily: "var(--serif)", fontSize: 22, color: "var(--gold)" }}>{hours}h</span>
            </div>
            <input type="range" min="1" max="12" value={hours} onChange={(e) => setHours(+e.target.value)} style={{ width: "100%", accentColor: "var(--gold)" }} />
          </div>
          <div style={{ background: "var(--card)", border: "1px solid var(--line)", borderRadius: 16, padding: 24 }}>
            <div style={{ fontFamily: "var(--mono)", fontSize: 11, color: "var(--ink-mute)", textTransform: "uppercase", letterSpacing: "0.15em" }}>Recommended pre-shift</div>
            <div style={{ fontFamily: "var(--serif)", fontSize: 40, fontWeight: 500, color: "var(--gold)", marginTop: 6 }}>Start {days} days before</div>
            <ul style={{ marginTop: 16, paddingLeft: 20, color: "var(--ink-soft)", fontSize: 14, lineHeight: 1.7 }}>
              <li>Shift bedtime {direction === "east" ? "earlier" : "later"} by 30–60 min/day</li>
              <li>Get bright light {direction === "east" ? "in the morning" : "in the evening"}</li>
              <li>Avoid caffeine after noon (departure timezone)</li>
              <li>Set watch to destination time at takeoff</li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  );
};

// ---------- Sleep Quality Quiz ----------
window.QuizModal = function ({ t, onClose }) {
  const questions = [
    "I fall asleep within 20 minutes of getting in bed.",
    "I sleep through the night without waking.",
    "I wake feeling refreshed without an alarm.",
    "I keep a consistent bedtime, even on weekends.",
    "I avoid screens for 30+ minutes before bed.",
    "My bedroom is cool, dark, and quiet.",
    "I rarely need caffeine to function.",
    "My energy stays steady through the afternoon.",
  ];
  const [ans, setAns] = useState({});
  const total = Object.values(ans).reduce((a, b) => a + b, 0);
  const max = questions.length * 4;
  const pct = Math.round((total / max) * 100);
  const done = Object.keys(ans).length === questions.length;
  const verdict =
    pct >= 80 ? { label: "Excellent", color: "var(--gold)", note: "Your sleep architecture is strong. Keep your rituals." } :
    pct >= 60 ? { label: "Good", color: "oklch(0.78 0.10 100)", note: "A few small habits could push you to excellent." } :
    pct >= 40 ? { label: "Inconsistent", color: "oklch(0.78 0.10 60)", note: "Likely sleep debt accumulating. Try the cycle calculator." } :
                { label: "Needs attention", color: "oklch(0.70 0.14 30)", note: "Speak with a doctor if persistent. Start with consistent timing." };
  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <div className="modal-head">
          <div><h3>{t.tools.t7_n}</h3><p>{Object.keys(ans).length} / {questions.length} answered</p></div>
          <button className="modal-close" onClick={onClose}>×</button>
        </div>
        <div className="modal-body">
          {questions.map((q, i) => (
            <div key={i} style={{ marginBottom: 20, paddingBottom: 16, borderBottom: "1px solid var(--line)" }}>
              <div style={{ fontFamily: "var(--serif)", fontSize: 17, marginBottom: 12 }}>{i+1}. {q}</div>
              <div style={{ display: "flex", gap: 6 }}>
                {["Never","Rarely","Sometimes","Often","Always"].map((label, v) => (
                  <button key={v} onClick={() => setAns({ ...ans, [i]: v })}
                    style={{
                      flex: 1, padding: "10px 4px",
                      background: ans[i] === v ? "var(--gold)" : "transparent",
                      color: ans[i] === v ? "var(--bg)" : "var(--ink-soft)",
                      border: "1px solid " + (ans[i] === v ? "var(--gold)" : "var(--line-2)"),
                      borderRadius: 8, cursor: "pointer", fontSize: 11, fontFamily: "var(--sans)",
                    }}>
                    {label}
                  </button>
                ))}
              </div>
            </div>
          ))}
          {done && (
            <div style={{ background: "var(--card)", border: "1px solid var(--line)", borderRadius: 16, padding: 28, marginTop: 20, textAlign: "center" }}>
              <div style={{ fontFamily: "var(--mono)", fontSize: 11, color: "var(--ink-mute)", textTransform: "uppercase", letterSpacing: "0.15em" }}>Your sleep score</div>
              <div style={{ fontFamily: "var(--serif)", fontSize: 80, fontWeight: 500, color: verdict.color, lineHeight: 1, margin: "8px 0" }}>{pct}</div>
              <div style={{ fontFamily: "var(--serif)", fontSize: 22, color: verdict.color, marginBottom: 8 }}>{verdict.label}</div>
              <div style={{ fontSize: 14, color: "var(--ink-soft)", maxWidth: 380, margin: "0 auto" }}>{verdict.note}</div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

// ---------- Chronotype Finder ----------
window.ChronoModal = function ({ t, onClose }) {
  const [bedtime, setBedtime] = useState(23);
  const [waketime, setWaketime] = useState(7);
  const types = [
    { key: "lion", name: "Lion", emoji: "🦁", desc: "Early to rise, peak in morning. ~15% of population.", traits: "Bedtime 9–10pm · Wake 5–6am", color: "oklch(0.82 0.13 80)" },
    { key: "bear", name: "Bear", emoji: "🐻", desc: "Solar-aligned. Most common chronotype. ~55% of population.", traits: "Bedtime 11pm · Wake 7am", color: "oklch(0.65 0.10 50)" },
    { key: "wolf", name: "Wolf", emoji: "🐺", desc: "Late riser, peak in evening. ~15% of population.", traits: "Bedtime 12–1am · Wake 8–9am", color: "oklch(0.55 0.10 280)" },
    { key: "dolphin", name: "Dolphin", emoji: "🐬", desc: "Light sleeper, often anxious about sleep. ~10% of population.", traits: "Bedtime variable · Wake 6:30am", color: "oklch(0.65 0.10 220)" },
  ];
  let pick = "bear";
  if (bedtime < 22 && waketime < 6.5) pick = "lion";
  else if (bedtime >= 24 || waketime >= 8) pick = "wolf";
  else if (waketime - bedtime < 7 || waketime - bedtime > 9.5) pick = "dolphin";
  const cur = types.find(x => x.key === pick);
  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <div className="modal-head">
          <div><h3>{t.tools.t8_n}</h3><p>Based on Dr. Breus's chronotype framework</p></div>
          <button className="modal-close" onClick={onClose}>×</button>
        </div>
        <div className="modal-body">
          <div style={{ marginBottom: 24 }}>
            <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 8 }}>
              <span style={{ fontFamily: "var(--mono)", fontSize: 11, color: "var(--ink-mute)", textTransform: "uppercase", letterSpacing: "0.15em" }}>Natural bedtime</span>
              <span style={{ fontFamily: "var(--serif)", fontSize: 22 }}>{bedtime > 24 ? bedtime - 24 : bedtime}:00</span>
            </div>
            <input type="range" min="20" max="26" step="0.5" value={bedtime} onChange={(e) => setBedtime(+e.target.value)} style={{ width: "100%", accentColor: "var(--gold)" }} />
          </div>
          <div style={{ marginBottom: 32 }}>
            <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 8 }}>
              <span style={{ fontFamily: "var(--mono)", fontSize: 11, color: "var(--ink-mute)", textTransform: "uppercase", letterSpacing: "0.15em" }}>Natural wake time</span>
              <span style={{ fontFamily: "var(--serif)", fontSize: 22 }}>{waketime}:00</span>
            </div>
            <input type="range" min="4" max="11" step="0.5" value={waketime} onChange={(e) => setWaketime(+e.target.value)} style={{ width: "100%", accentColor: "var(--gold)" }} />
          </div>
          <div style={{ background: "var(--card)", border: "1px solid var(--line)", borderRadius: 16, padding: 32, textAlign: "center" }}>
            <div style={{ fontSize: 64, marginBottom: 8 }}>{cur.emoji}</div>
            <div style={{ fontFamily: "var(--mono)", fontSize: 11, color: "var(--ink-mute)", textTransform: "uppercase", letterSpacing: "0.15em" }}>You are a</div>
            <div style={{ fontFamily: "var(--serif)", fontSize: 48, fontWeight: 500, color: cur.color, lineHeight: 1.1, margin: "4px 0 12px" }}>{cur.name}</div>
            <div style={{ fontSize: 14, color: "var(--ink-soft)", maxWidth: 380, margin: "0 auto 12px" }}>{cur.desc}</div>
            <div style={{ fontFamily: "var(--mono)", fontSize: 12, color: "var(--gold)" }}>{cur.traits}</div>
          </div>
        </div>
      </div>
    </div>
  );
};

window.BedtimeModal = window.SleepCycleModal; // alias - hero is essentially this
