// SleepWise — main app
const { useState, useEffect, useMemo, useRef } = React;

// ---- Hero Sleep Calculator ----
function HeroCalc({ t, lang }) {
  const [mode, setMode] = useState("wake"); // 'wake' or 'bed'
  const [hour, setHour] = useState(7);
  const [minute, setMinute] = useState(0);
  const [ampm, setAmpm] = useState("AM");

  const targetDate = useMemo(() => {
    let h = hour;
    if (lang === "en") {
      if (ampm === "PM" && h !== 12) h += 12;
      if (ampm === "AM" && h === 12) h = 0;
    }
    const d = new Date();
    d.setHours(h, minute, 0, 0);
    if (mode === "wake" && d <= new Date()) d.setDate(d.getDate() + 1);
    return d;
  }, [hour, minute, ampm, lang, mode]);

  const results = mode === "wake"
    ? SleepMath.bedtimesForWake(targetDate)
    : SleepMath.wakesForSleepNow(new Date());

  const titleKey = mode === "wake" ? "results_title" : "results_title_wake";

  return (
    <div className="calc-card">
      <div className="calc-tabs">
        <button className={"calc-tab " + (mode === "wake" ? "active" : "")} onClick={() => setMode("wake")}>{t.calc.tab_wake}</button>
        <button className={"calc-tab " + (mode === "bed" ? "active" : "")} onClick={() => setMode("bed")}>{t.calc.tab_bed}</button>
      </div>

      {mode === "wake" ? (
        <>
          <div className="calc-label">{t.calc.label_wake}</div>
          <div className="time-input-wrap">
            <input className="time-input" type="number" min="1" max={lang === "en" ? 12 : 23} value={hour}
              onChange={(e) => setHour(Math.max(0, Math.min(lang === "en" ? 12 : 23, +e.target.value || 0)))}
              style={{ width: 110, textAlign: "right" }} />
            <span className="time-colon">:</span>
            <input className="time-input" type="number" min="0" max="59" value={String(minute).padStart(2, "0")}
              onChange={(e) => setMinute(Math.max(0, Math.min(59, +e.target.value || 0)))}
              style={{ width: 110 }} />
            {lang === "en" && (
              <div className="ampm-toggle">
                <button className={"ampm-btn " + (ampm === "AM" ? "active" : "")} onClick={() => setAmpm("AM")}>AM</button>
                <button className={"ampm-btn " + (ampm === "PM" ? "active" : "")} onClick={() => setAmpm("PM")}>PM</button>
              </div>
            )}
          </div>
        </>
      ) : (
        <>
          <div className="calc-label">{t.calc.label_bed}</div>
          <div className="time-input-wrap">
            <span className="time-input" style={{ fontSize: 56 }}>{SleepMath.fmtTime(new Date(), lang)}</span>
          </div>
        </>
      )}

      <div className="results-block">
        <div className="results-title">
          <h3>{t.calc[titleKey]}</h3>
          <span>{t.calc.results_sub}</span>
        </div>
        {results.map((r, i) => (
          <div className={"bedtime-row " + (r.cycles === 5 ? "bedtime-recommended" : "")} key={i}>
            <div>
              <div className="bedtime-time">{SleepMath.fmtTime(r.time, lang)}</div>
              <div className="bedtime-meta">{r.hours} {t.calc.hours} · {r.cycles} {t.calc.cycles}</div>
            </div>
            <div className="bedtime-quality">
              {[1,2,3,4,5].map(n => <span key={n} className={"qual-dot " + (n <= r.quality ? "on" : "")} />)}
            </div>
          </div>
        ))}
        <div style={{ marginTop: 16, fontSize: 11, color: "var(--ink-mute)", fontFamily: "var(--mono)", textTransform: "uppercase", letterSpacing: "0.1em" }}>
          {t.calc.latency}
        </div>
      </div>
    </div>
  );
}

// ---- Cycle Visualization (for science section) ----
function CycleViz() {
  // simple SVG hypnogram
  return (
    <svg viewBox="0 0 480 480" style={{ width: "100%", height: "auto" }}>
      <defs>
        <radialGradient id="moonG" cx="0.35" cy="0.35">
          <stop offset="0%" stopColor="oklch(0.92 0.04 85)" />
          <stop offset="100%" stopColor="oklch(0.55 0.08 85)" />
        </radialGradient>
      </defs>
      {/* outer ring */}
      <circle cx="240" cy="240" r="220" fill="none" stroke="var(--line-2)" strokeWidth="1" />
      <circle cx="240" cy="240" r="180" fill="none" stroke="var(--line)" strokeWidth="1" strokeDasharray="2 6" />
      <circle cx="240" cy="240" r="140" fill="none" stroke="var(--line)" strokeWidth="1" />
      <circle cx="240" cy="240" r="100" fill="none" stroke="var(--line)" strokeWidth="1" strokeDasharray="2 6" />
      {/* central moon */}
      <circle cx="240" cy="240" r="60" fill="url(#moonG)" opacity="0.9" />
      <circle cx="222" cy="225" r="6" fill="oklch(0.5 0.05 85)" opacity="0.4" />
      <circle cx="260" cy="250" r="8" fill="oklch(0.5 0.05 85)" opacity="0.4" />
      <circle cx="245" cy="262" r="4" fill="oklch(0.5 0.05 85)" opacity="0.4" />
      {/* hypnogram waveform */}
      {[0,1,2,3,4].map(i => {
        const a = (i / 5) * Math.PI * 2 - Math.PI / 2;
        const r1 = 100, r2 = 180;
        const x1 = 240 + Math.cos(a) * r1, y1 = 240 + Math.sin(a) * r1;
        const x2 = 240 + Math.cos(a) * r2, y2 = 240 + Math.sin(a) * r2;
        return <line key={i} x1={x1} y1={y1} x2={x2} y2={y2} stroke="var(--gold)" strokeWidth="1" opacity="0.5" />;
      })}
      {/* labels */}
      {[
        { a: 0, label: "Cycle 1" },
        { a: 1.25, label: "Cycle 2" },
        { a: 2.5, label: "Cycle 3" },
        { a: 3.75, label: "Cycle 4" },
        { a: 5, label: "Cycle 5" },
      ].map((c, i) => {
        const a = (c.a / 5) * Math.PI * 2 - Math.PI / 2 + 0.3;
        const x = 240 + Math.cos(a) * 200;
        const y = 240 + Math.sin(a) * 200;
        return (
          <text key={i} x={x} y={y} fill="var(--ink-mute)" fontSize="10" fontFamily="var(--mono), monospace" textAnchor="middle" dominantBaseline="middle" letterSpacing="2">
            {c.label.toUpperCase()}
          </text>
        );
      })}
      {/* hypnogram trace */}
      <path
        d="M 60,300 Q 100,260 140,310 T 220,290 Q 260,250 300,300 T 380,280 Q 410,260 420,290"
        fill="none" stroke="var(--gold)" strokeWidth="1.5" opacity="0.7" />
    </svg>
  );
}

// ---- Stages list ----
function Stages() {
  const stages = [
    { num: "01", name: "N1 — Drift", pct: "~5%", desc: "The threshold. Muscles relax, breath slows. You can be woken with a touch." },
    { num: "02", name: "N2 — Light sleep", pct: "~50%", desc: "Body temperature drops, heart rate steadies. Sleep spindles consolidate memory." },
    { num: "03", name: "N3 — Deep sleep", pct: "~20%", desc: "Slow-wave sleep. Tissue repair, immune function, growth hormone release." },
    { num: "04", name: "REM — Dream sleep", pct: "~25%", desc: "Brain near-waking activity. Dreams, emotional processing, learning consolidation." },
  ];
  return (
    <div className="stage-list">
      {stages.map((s, i) => (
        <div key={i} className="stage-item">
          <div className="stage-num">{s.num}</div>
          <div>
            <div className="stage-name">{s.name}</div>
            <div className="stage-desc">{s.desc}</div>
          </div>
          <div className="stage-pct">{s.pct}</div>
        </div>
      ))}
    </div>
  );
}

// ---- Tools Grid ----
function ToolsGrid({ t, onOpen }) {
  const tools = [
    { key: "cycle", icon: "Wake", n: t.tools.t1_n, d: t.tools.t1_d },
    { key: "bed", icon: "Bed", n: t.tools.t2_n, d: t.tools.t2_d },
    { key: "debt", icon: "Debt", n: t.tools.t3_n, d: t.tools.t3_d },
    { key: "nap", icon: "Nap", n: t.tools.t4_n, d: t.tools.t4_d },
    { key: "baby", icon: "Baby", n: t.tools.t5_n, d: t.tools.t5_d },
    { key: "jet", icon: "Plane", n: t.tools.t6_n, d: t.tools.t6_d },
    { key: "quiz", icon: "Quiz", n: t.tools.t7_n, d: t.tools.t7_d },
    { key: "chrono", icon: "Chrono", n: t.tools.t8_n, d: t.tools.t8_d },
  ];
  return (
    <div className="tools-grid">
      {tools.map(tool => {
        const Icon = Icons[tool.icon];
        return (
          <div key={tool.key} className="tool-card" onClick={() => onOpen(tool.key)}>
            <div>
              <div className="tool-icon"><Icon size={40} /></div>
              <div className="tool-name">{tool.n}</div>
              <div className="tool-desc">{tool.d}</div>
            </div>
            <div className="tool-arrow"><Icons.Arrow size={20} /></div>
          </div>
        );
      })}
    </div>
  );
}

// ---- FAQ ----
function FaqList({ t }) {
  const [open, setOpen] = useState(0);
  const items = [1,2,3,4,5,6,7].map(i => ({ q: t.faq[`q${i}`], a: t.faq[`a${i}`] }));
  return (
    <div>
      {items.map((it, i) => (
        <div key={i} className={"faq-item " + (open === i ? "open" : "")}>
          <button className="faq-q" onClick={() => setOpen(open === i ? -1 : i)}>
            <span>{it.q}</span>
            <span className="faq-toggle">+</span>
          </button>
          <div className="faq-a">{it.a}</div>
        </div>
      ))}
    </div>
  );
}

// ---- Starfield ----
function Starfield() {
  const stars = useMemo(() => {
    const arr = [];
    for (let i = 0; i < 80; i++) {
      arr.push({
        top: Math.random() * 100,
        left: Math.random() * 100,
        size: Math.random() * 2 + 0.5,
        dur: Math.random() * 4 + 3,
        delay: Math.random() * 5,
        opaMin: Math.random() * 0.2 + 0.1,
        opaMax: Math.random() * 0.5 + 0.5,
      });
    }
    return arr;
  }, []);
  return (
    <div className="starfield">
      {stars.map((s, i) => (
        <div key={i} className="star" style={{
          top: `${s.top}%`, left: `${s.left}%`,
          width: s.size, height: s.size,
          "--dur": `${s.dur}s`, "--delay": `${s.delay}s`,
          "--opa-min": s.opaMin, "--opa-max": s.opaMax,
        }} />
      ))}
    </div>
  );
}

// ---- Language Dropdown ----
function LangDropdown({ lang, setLang }) {
  const [open, setOpen] = useState(false);
  const langs = [
    { key: "en", label: "EN — English" },
    { key: "de", label: "DE — Deutsch" },
    { key: "es", label: "ES — Español" },
    { key: "fr", label: "FR — Français" },
  ];
  const cur = langs.find(l => l.key === lang) || langs[0];
  useEffect(() => {
    const close = () => setOpen(false);
    if (open) {
      setTimeout(() => document.addEventListener("click", close), 0);
      return () => document.removeEventListener("click", close);
    }
  }, [open]);
  return (
    <div className="dropdown">
      <button className="lang-select" onClick={(e) => { e.stopPropagation(); setOpen(!open); }}>
        <span style={{ fontFamily: "var(--mono)", fontSize: 12 }}>{cur.key.toUpperCase()}</span>
        <span style={{ fontSize: 10, color: "var(--ink-mute)" }}>▾</span>
      </button>
      {open && (
        <div className="dropdown-menu" onClick={(e) => e.stopPropagation()}>
          {langs.map(l => (
            <button key={l.key} className={"dropdown-item " + (l.key === lang ? "active" : "")}
              onClick={() => { setLang(l.key); setOpen(false); }}>
              {l.label}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

// ---- App ----
function App() {
  const [lang, setLang] = useState(window.__LANG || "en");
  const [theme, setTheme] = useState("dark");
  const [openTool, setOpenTool] = useState(null);
  const t = I18N[lang] || I18N["en"];

  useEffect(() => {
    document.documentElement.setAttribute("data-theme", theme);
  }, [theme]);

  // Tweaks panel integration
  useEffect(() => {
    const handler = (e) => {
      if (e.data?.type === "__activate_edit_mode") setTweaksOpen(true);
      if (e.data?.type === "__deactivate_edit_mode") setTweaksOpen(false);
    };
    window.addEventListener("message", handler);
    window.parent.postMessage({ type: "__edit_mode_available" }, "*");
    return () => window.removeEventListener("message", handler);
  }, []);
  const [tweaksOpen, setTweaksOpen] = useState(false);

  const onOpenTool = (key) => setOpenTool(key);

  return (
    <>
      <Starfield />
      <div className="aurora" />

      {/* NAV */}
      <nav className="nav">
        <div className="shell nav-inner">
          <div className="brand">
            <svg className="brand-mark" viewBox="0 0 32 32" fill="none">
              <path d="M22 20a8 8 0 1 1-10-10 6 6 0 0 0 10 10z" fill="oklch(0.82 0.12 85)" />
              <circle cx="24" cy="8" r="1" fill="oklch(0.82 0.12 85)" />
              <circle cx="6" cy="6" r="0.8" fill="oklch(0.82 0.12 85)" opacity="0.6" />
              <circle cx="26" cy="22" r="0.6" fill="oklch(0.82 0.12 85)" opacity="0.5" />
            </svg>
            SleepWise
          </div>
          <ul className="nav-links">
            <li><a href="#tools">{t.nav.tools}</a></li>
            <li><a href="#science">{t.nav.science}</a></li>
            <li><a href="#articles">{t.nav.articles}</a></li>
            <li><a href="#faq">{t.nav.faq}</a></li>
          </ul>
          <div className="nav-right">
            <LangDropdown lang={lang} setLang={setLang} />
            <button className="theme-toggle" onClick={() => setTheme(theme === "dark" ? "light" : "dark")} title="Toggle theme">
              {theme === "dark" ? <Icons.Sun size={16} /> : <Icons.Moon size={16} />}
            </button>
          </div>
        </div>
      </nav>

      {/* HERO */}
      <section className="hero">
        <div className="shell hero-grid">
          <div>
            <div className="eyebrow">{t.hero.eyebrow}</div>
            <h1>{t.hero.title_a} <em>{t.hero.title_em}</em><br/>{t.hero.title_b}</h1>
            <p className="lede">{t.hero.lede}</p>
            <div className="hero-stats">
              <div>
                <div className="stat-num">{t.hero.stat1_v}</div>
                <div className="stat-label">{t.hero.stat1}</div>
              </div>
              <div>
                <div className="stat-num">{t.hero.stat2_v}</div>
                <div className="stat-label">{t.hero.stat2}</div>
              </div>
              <div>
                <div className="stat-num">{t.hero.stat3_v}</div>
                <div className="stat-label">{t.hero.stat3}</div>
              </div>
            </div>
          </div>
          <div style={{ position: "relative" }}>
            <HeroCalc t={t} lang={lang} />
          </div>
        </div>
      </section>

      <div className="shell">
        <div className="adslot adslot-leaderboard">{t.ad} · 728 × 90</div>
      </div>

      {/* TOOLS */}
      <section id="tools">
        <div className="shell">
          <div className="section-head">
            <h2>{t.tools.head_a} <em>{t.tools.head_em}</em> {t.tools.head_b}</h2>
            <p>{t.tools.sub}</p>
          </div>
          <ToolsGrid t={t} onOpen={onOpenTool} />
        </div>
      </section>

      {/* SCIENCE */}
      <section id="science">
        <div className="shell">
          <div className="section-head">
            <h2>{t.science.head_a} <em>{t.science.head_em}</em> {t.science.head_b}</h2>
            <p>{t.science.sub}</p>
          </div>
          <div className="edu-grid">
            <CycleViz />
            <Stages />
          </div>
        </div>
      </section>

      <div className="shell">
        <div className="adslot adslot-banner">{t.ad} · 970 × 250</div>
      </div>

      {/* ARTICLES */}
      <section id="articles">
        <div className="shell">
          <div className="section-head">
            <h2>{t.tips.head_a} <em>{t.tips.head_em}</em></h2>
            <p>{t.tips.sub}</p>
          </div>
          <div className="tips-grid">
            <div className="tip-card feat">
              <div className="tip-tag">{t.tips.feat_tag}</div>
              <div>
                <div className="tip-title">{t.tips.feat_title}</div>
                <div className="tip-meta">{t.tips.feat_meta}</div>
              </div>
            </div>
            <div className="tip-card">
              <div className="tip-tag">{t.tips.a1_tag}</div>
              <div className="tip-title">{t.tips.a1_title}</div>
              <div className="tip-meta">{t.tips.a1_meta}</div>
            </div>
            <div className="tip-card">
              <div className="tip-tag">{t.tips.a2_tag}</div>
              <div className="tip-title">{t.tips.a2_title}</div>
              <div className="tip-meta">{t.tips.a2_meta}</div>
            </div>
            <div className="tip-card">
              <div className="tip-tag">{t.tips.a3_tag}</div>
              <div className="tip-title">{t.tips.a3_title}</div>
              <div className="tip-meta">{t.tips.a3_meta}</div>
            </div>
            <div className="tip-card">
              <div className="tip-tag">{t.tips.a4_tag}</div>
              <div className="tip-title">{t.tips.a4_title}</div>
              <div className="tip-meta">{t.tips.a4_meta}</div>
            </div>
          </div>
        </div>
      </section>

      {/* TESTIMONIALS */}
      <section id="testimonials">
        <div className="shell">
          <div className="section-head">
            <h2>{t.test.head_a} <em>{t.test.head_em}</em> {t.test.head_b}</h2>
            <p>{t.test.sub}</p>
          </div>
          <div className="test-marquee">
            {[1,2,3].map(i => (
              <div key={i} className="test-card">
                <div className="test-quote">"{t.test[`q${i}`]}"</div>
                <div className="test-author">
                  <div className="test-avatar">{t.test[`n${i}`].slice(0,1)}</div>
                  <div>
                    <div className="test-name">{t.test[`n${i}`]}</div>
                    <div className="test-role">{t.test[`r${i}`]}</div>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* FAQ */}
      <section id="faq">
        <div className="shell">
          <div className="faq-grid">
            <div>
              <h2 style={{ fontFamily: "var(--serif)", fontWeight: 400, fontSize: "clamp(36px, 4vw, 56px)", lineHeight: 1.05, letterSpacing: "-0.015em" }}>
                {t.faq.head_a} <em style={{ fontStyle: "italic", color: "var(--gold)", fontWeight: 300 }}>{t.faq.head_em}</em> {t.faq.head_b}
              </h2>
              <p style={{ color: "var(--ink-soft)", marginTop: 24, fontSize: 15, maxWidth: 320 }}>{t.faq.sub}</p>
              <div className="adslot adslot-square" style={{ marginTop: 40 }}>{t.ad} · 300 × 300</div>
            </div>
            <FaqList t={t} />
          </div>
        </div>
      </section>

      {/* NEWSLETTER */}
      <section>
        <div className="shell">
          <div className="newsletter">
            <h2>{t.news.title_a} <em style={{ fontStyle: "italic", color: "var(--gold)", fontWeight: 300 }}>{t.news.title_em}</em></h2>
            <p>{t.news.sub}</p>
            <form className="newsletter-form" onSubmit={(e) => { e.preventDefault(); alert("Subscribed (demo)."); }}>
              <input type="email" placeholder={t.news.placeholder} required />
              <button type="submit" className="btn-primary">{t.news.cta}</button>
            </form>
          </div>
        </div>
      </section>

      {/* FOOTER */}
      <footer className="footer">
        <div className="shell">
          <div className="footer-grid">
            <div className="footer-brand">
              <div className="brand">
                <svg className="brand-mark" viewBox="0 0 32 32" fill="none">
                  <path d="M22 20a8 8 0 1 1-10-10 6 6 0 0 0 10 10z" fill="oklch(0.82 0.12 85)" />
                </svg>
                SleepWise
              </div>
              <p>{t.footer.about}</p>
            </div>
            <div className="footer-col">
              <h4>{t.footer.tools}</h4>
              <ul>
                <li><a href="#tools">{t.tools.t1_n}</a></li>
                <li><a href="#tools">{t.tools.t2_n}</a></li>
                <li><a href="#tools">{t.tools.t3_n}</a></li>
                <li><a href="#tools">{t.tools.t4_n}</a></li>
              </ul>
            </div>
            <div className="footer-col">
              <h4>{t.footer.company}</h4>
              <ul>
                <li><a href="#">About</a></li>
                <li><a href="#">Press</a></li>
                <li><a href="#">Contact</a></li>
              </ul>
            </div>
            <div className="footer-col">
              <h4>{t.footer.resources}</h4>
              <ul>
                <li><a href="#science">Sleep science</a></li>
                <li><a href="#articles">Articles</a></li>
                <li><a href="#faq">FAQ</a></li>
                <li><a href="#">Research</a></li>
              </ul>
            </div>
            <div className="footer-col">
              <h4>{t.footer.legal}</h4>
              <ul>
                <li><a href="#">Privacy</a></li>
                <li><a href="#">Terms</a></li>
                <li><a href="#">Cookies</a></li>
              </ul>
            </div>
          </div>
          <div className="footer-bottom">
            <span>{t.footer.copyright}</span>
            <span>v1.0 · {lang.toUpperCase()}</span>
          </div>
        </div>
      </footer>

      {/* MODALS */}
      {openTool === "cycle" && <SleepCycleModal t={t} lang={lang} onClose={() => setOpenTool(null)} />}
      {openTool === "bed" && <BedtimeModal t={t} lang={lang} onClose={() => setOpenTool(null)} />}
      {openTool === "debt" && <SleepDebtModal t={t} onClose={() => setOpenTool(null)} />}
      {openTool === "nap" && <NapModal t={t} lang={lang} onClose={() => setOpenTool(null)} />}
      {openTool === "baby" && <BabyModal t={t} onClose={() => setOpenTool(null)} />}
      {openTool === "jet" && <JetLagModal t={t} onClose={() => setOpenTool(null)} />}
      {openTool === "quiz" && <QuizModal t={t} onClose={() => setOpenTool(null)} />}
      {openTool === "chrono" && <ChronoModal t={t} onClose={() => setOpenTool(null)} />}

      {/* TWEAKS */}
      {tweaksOpen && (
        <TweaksPanel title="Tweaks" onClose={() => { setTweaksOpen(false); window.parent.postMessage({ type: "__edit_mode_dismissed" }, "*"); }}>
          <TweakSection title="Appearance">
            <TweakRadio label="Theme" value={theme} options={[{value:"dark",label:"Dark"},{value:"light",label:"Light"}]} onChange={setTheme} />
          </TweakSection>
          <TweakSection title="Language">
            <TweakRadio label="Language" value={lang} options={[
              {value:"en",label:"English"},{value:"de",label:"Deutsch"},
              {value:"es",label:"Español"},{value:"fr",label:"Français"},
            ]} onChange={setLang} />
          </TweakSection>
        </TweaksPanel>
      )}
    </>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
