const { useState, useEffect, useRef, useMemo } = React;

// ------------------------------------------------------------
//  Red Light Healer — Kickstarter campaign page
//  Scandinavian editorial · interactive prototype
// ------------------------------------------------------------

const FUNDING = {
  pledged: 1_487_320,
  goal: 250_000,
  backers: 4218,
  daysLeft: 17,
  currency: "DKK",
};

const PLEDGES = [
  {
    id: "early",
    name: "Tidlig Stjerne",
    sub: "Early Star",
    price: 1890,
    strike: 2490,
    tag: "Earliest Birds · 312 of 500 claimed",
    tagRed: true,
    perks: [
      "1 × Red Light Healer (40 Hz red OLED panel)",
      "Quick-start guide in DA / IS / EN",
      "Companion app, lifetime",
      "Free shipping within EU & Nordic region",
    ],
    delivery: "Sep 2026",
    ships: "Worldwide",
    sold: 312,
    cap: 500,
    span: 4,
  },
  {
    id: "healer",
    name: "The Healer",
    sub: "Standard Edition",
    price: 2490,
    tag: "Most popular · ships in time for winter",
    tagRed: false,
    perks: [
      "1 × Red Light Healer (40 Hz red OLED panel)",
      "Linen carry sleeve, woven in Ísafjörður",
      "Quick-start guide in DA / IS / EN",
      "Companion app, lifetime",
      "12-month limited warranty",
    ],
    delivery: "Nov 2026",
    ships: "Worldwide",
    sold: 2104,
    cap: 4000,
    span: 4,
    selected: true,
  },
  {
    id: "double",
    name: "Tvíburar",
    sub: "Twin Set · for two homes",
    price: 4290,
    strike: 4980,
    tag: "Save 690 DKK · for a parent & a child",
    tagRed: false,
    perks: [
      "2 × Red Light Healer",
      "2 × linen sleeves",
      "Family setup call with our care team",
      "Priority support, first year",
      "Companion app, lifetime",
    ],
    delivery: "Nov 2026",
    ships: "Worldwide",
    sold: 412,
    cap: 1000,
    span: 4,
  },
  {
    id: "clinic",
    name: "Klínikk",
    sub: "Clinic Pack · 6 units",
    price: 11800,
    tag: "For care homes, sleep clinics & research labs",
    tagRed: false,
    perks: [
      "6 × Red Light Healer in calibrated case",
      "Spectrometer-certified to ±0.5 nm",
      "Calibration & service contract (24 months)",
      "On-site training (Nordic region) or remote",
      "Anonymised study dashboard",
    ],
    delivery: "Jan 2027",
    ships: "EU, UK, US, JP",
    sold: 28,
    cap: 80,
    span: 6,
  },
  {
    id: "founder",
    name: "Lærdómur",
    sub: "Founders' Edition · Numbered",
    price: 8900,
    tag: "01 of 100 · signed, hand-numbered",
    tagRed: true,
    perks: [
      "1 × Red Light Healer, brushed-aluminium variant, numbered 001–100",
      "Walnut display cradle with engraved nameplate",
      "Studio visit in Copenhagen (or filmed equivalent)",
      "Quarterly research letter from the team",
      "Lifetime device replacement programme",
    ],
    delivery: "Dec 2026",
    ships: "Worldwide",
    sold: 67,
    cap: 100,
    span: 6,
  },
];

const STRETCH = [
  { amt: "750.000 kr", name: "Linen sleeve in three Nordic earths", status: "Unlocked", locked: false },
  { amt: "1.200.000 kr", name: "Spanish & French companion app localisation", status: "Unlocked", locked: false },
  { amt: "1.500.000 kr", name: "Caregiver dashboard with weekly read-outs", status: "Approaching", locked: false },
  { amt: "2.000.000 kr", name: "Open spectrometer data — every panel measured", status: "Locked", locked: true },
];

const FAQS = [
  {
    q: "Is the Red Light Healer a medical device, or a wellness device?",
    a: "The Red Light Healer is currently classified as a wellness device. We have begun the conformity pathway for CE Mark Class IIa and FDA De Novo, with the first regulatory filings planned for Q2 2027. Backers receive the wellness version; certified clinical variants will be offered as an upgrade once cleared.",
  },
  {
    q: "How is this different from cheap red-light panels I can already buy?",
    a: "Two things. First, our panel is OLED — it gives even, low-heat illumination with no infrared bleed, calibrated to ±0.5 nm at the red peak. Second, ours flickers at a precise 40 Hz with millisecond timing — the rhythm shown in published research to entrain memory circuits. Most consumer panels are LED, run hot, and have no flicker control at all.",
  },
  {
    q: "What does the science actually show today?",
    a: "Published animal-model studies, including the one our team co-authored at the University of Copenhagen with collaborators in Reykjavík, show reduced amyloid-β load, increased ADAM17 (a clearance enzyme), reduced BACE1, and measurable behavioural improvement after short daily exposure. We are clear-eyed: these are mouse data. Human trials are how we will earn the right to use the word treatment.",
  },
  {
    q: "How long should I use it each day?",
    a: "The Healer ships with a default protocol of 1 hour per day, eyes-open, at a comfortable reading distance (about 60 cm). The companion app lets caregivers schedule, lock the protocol, and log adherence. You do not need to stare at the panel — peripheral vision is enough.",
  },
  {
    q: "Is it safe to use every day?",
    a: "Red light at the wavelengths we use is one of the most-studied bands in photobiology, and the brightness is well below sunlight. We follow the IEC 62471 photobiological safety standard for continuous use. We do not recommend the device for people with photosensitive epilepsy or who are pregnant; the companion app screens for this on setup.",
  },
  {
    q: "Where is the Red Light Healer made?",
    a: "Designed in Copenhagen and Reykjavík. OLED panels are manufactured in South Korea by a partner already producing medical-grade displays. Final assembly, calibration, and packaging happen in Aalborg, Denmark. Every panel is spectrometer-checked before it leaves the factory.",
  },
  {
    q: "What if my pledge does not work for me?",
    a: "You can change your pledge any time before the campaign ends. After delivery, we offer a 60-day return for any reason, and a 12-month warranty (lifetime for Founders' Edition). Shipping is free within the EU and Nordic region; we charge a flat 290 DKK elsewhere.",
  },
];

const TEAM = [
  {
    name: "Sigríður Magnúsdóttir",
    role: "Co-founder · Neuroengineering",
    bio: "PhD in photobiology, University of Iceland. Previously led the OLED therapeutics group at a Reykjavík medical-device startup. First-author on the 2025 paper that started this project.",
    photo: "portrait · workshop · oled bench",
  },
  {
    name: "Mikkel Holm Lauridsen",
    role: "Co-founder · Industrial design",
    bio: "Royal Danish Academy, graduated 2018. Eight years at Bang & Olufsen and a year at LEGO Future Lab. Believes a medical device should feel like an object you keep on a shelf, not in a drawer.",
    photo: "portrait · studio · grey morning",
  },
  {
    name: "Dr. Hannah Wei",
    role: "Scientific Advisor · Neurology",
    bio: "Memory and Aging Center, UCSF. Twenty years of clinical Alzheimer's research. Reviews every protocol we publish.",
    photo: "portrait · clinic · soft natural light",
  },
];

// ------------------------------------------------------------
//  Components
// ------------------------------------------------------------

function Topbar({ funding }) {
  const pct = Math.min(999, Math.round((funding.pledged / funding.goal) * 100));
  return (
    <div className="topbar">
      <div className="container topbar-inner">
        <div className="left">
          <span className="live"><span className="dot" /> Live now</span>
          <span>Copenhagen · 14:22</span>
          <span style={{ color: "var(--muted)" }}>Reykjavík · 12:22</span>
        </div>
        <div className="center">
          <span style={{ fontFamily: "var(--mono)", fontSize: 11, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--muted)" }}>Kickstarter ·</span>
          <span>Red Light Healer<span style={{ color: "var(--red)" }}>.</span></span>
        </div>
        <div className="right">
          <span>{pct}% funded</span>
          <span>{funding.daysLeft} days left</span>
          <a href="#pledge">Back this project →</a>
        </div>
      </div>
    </div>
  );
}

function Masthead() {
  return (
    <header className="masthead">
      <div className="container masthead-row">
        <div className="wordmark">Red Light Healer<sup>™</sup></div>
        <div className="masthead-meta">
          <span><b>Project</b> · <i>The Healer, a 40 Hz red light therapy device</i></span>
          <span><b>By</b> · <i>Red Light Healer ApS · Copenhagen / Reykjavík</i></span>
          <span><b>Category</b> · <i>Design · Hardware · Health</i></span>
        </div>
        <div className="masthead-actions">
          <button className="iconbtn" aria-label="Save">
            <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.2"><path d="M3 1.5h8v11l-4-3-4 3z" /></svg>
          </button>
          <button className="iconbtn" aria-label="Share">
            <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.2"><circle cx="11" cy="3" r="1.6" /><circle cx="3" cy="7" r="1.6" /><circle cx="11" cy="11" r="1.6" /><path d="M4.4 6 9.6 3.6M4.4 8l5.2 2.4" /></svg>
          </button>
        </div>
      </div>
    </header>
  );
}

function Hero({ onStartSession }) {
  // gentle flicker on the hero disc — visual, not 40 Hz (would strobe)
  const [intensity, setIntensity] = useState(0.55);
  useEffect(() => {
    let raf;
    let last = performance.now();
    const loop = (t) => {
      if (t - last > 120) { // ~8Hz so it reads but doesn't seizure
        setIntensity(0.35 + Math.random() * 0.35);
        last = t;
      }
      raf = requestAnimationFrame(loop);
    };
    raf = requestAnimationFrame(loop);
    return () => cancelAnimationFrame(raf);
  }, []);

  return (
    <section className="hero">
      <div className="container hero-grid">
        <div className="hero-left">
          <div className="hero-eyebrow">
            <span className="num">001 ·</span>
            <span>Kickstarter Edition</span>
            <span style={{ color: "var(--ink)", flex: 1 }}>—</span>
            <span>DKK 1.890→</span>
          </div>
          <h1>
            Light, <em>at the rhythm</em><br />
            the brain<br />
            remembers in.
            <span className="small">Ljós sem læknar. Lys der læger.</span>
          </h1>
        </div>
        <div className="hero-right">
          <div className="device-viewer" style={{ "--flicker": intensity }}>
            <div className="device-cap">Fig. 01 · The Healer · 660 nm · 40 Hz</div>
            <div className="device-disc" />
            <button className="session-trigger" onClick={onStartSession}>Begin a session →</button>
            <div className="device-meta">
              <span>OLED panel — calibrated ± 0,5 nm</span>
              <span className="red">● recording 40 Hz</span>
            </div>
          </div>
          <p className="hero-lede">
            The Red Light Healer is a precisely tuned red OLED panel that may help the
            brain <em>re-engage the memory circuits</em> Alzheimer's quiets
            — by entering through the eyes, at forty pulses a second.
          </p>
          <div className="session-cta-row">
            <span>Want to feel it? —</span>
            <a href="#" onClick={(e) => { e.preventDefault(); onStartSession(); }}>Enter a therapeutic session →</a>
          </div>
        </div>
      </div>
    </section>
  );
}

function Funding({ funding }) {
  const pct = Math.min(100, (funding.pledged / funding.goal) * 100);
  const real = Math.round((funding.pledged / funding.goal) * 100);
  return (
    <section className="funding">
      <div className="container funding-grid">
        <div className="funding-progress">
          <div className="stat">
            <span className="v">{funding.pledged.toLocaleString("da-DK")} <span style={{ fontSize: 16, fontFamily: "var(--mono)", letterSpacing: "0.08em" }}>kr</span></span>
            <span className="l">Pledged of {funding.goal.toLocaleString("da-DK")} kr goal</span>
          </div>
          <div className="bar" aria-label={`${real}% funded`}>
            <div style={{ width: pct + "%" }} />
          </div>
        </div>
        <div className="stat">
          <span className="v red">{real}%</span>
          <span className="l">Funded · {pct < 100 ? "approaching" : "exceeded"}</span>
        </div>
        <div className="stat">
          <span className="v">{funding.backers.toLocaleString("da-DK")}</span>
          <span className="l">Backers worldwide</span>
        </div>
        <div className="stat">
          <span className="v">{funding.daysLeft}</span>
          <span className="l">Days remaining</span>
        </div>
        <div className="stat">
          <span className="v">48</span>
          <span className="l">Countries shipping</span>
        </div>
        <a href="#pledge" className="pledge-cta">Back this project<span className="arrow" /></a>
      </div>
    </section>
  );
}

function Story() {
  return (
    <section className="block">
      <div className="container">
        <div className="section-head">
          <div className="label"><span className="num">§ 01</span>The Premise</div>
          <h2>A flickering panel,<br />in a colour the eye <em>remembers</em>.</h2>
        </div>

        <div className="story-grid">
          <aside className="aside">
            <div>Reading time<br /><b style={{ color: "var(--ink)", fontWeight: 500 }}>4 minutes</b></div>
            <hr />
            <div>Published<br /><b style={{ color: "var(--ink)", fontWeight: 500 }}>19 May 2026</b></div>
            <hr />
            <div>Authors<br />S. Magnúsdóttir<br />M. Holm Lauridsen</div>
            <hr />
            <div>Languages<br />Dansk · Íslenska<br />English</div>
          </aside>

          <div className="story-body">
            <p>For most of the last decade, the story of Alzheimer's has been a story of <strong>loss</strong>. Pills slowed it. Antibodies cleared a little of it. The arc kept bending downward.</p>
            <p>In late 2024, a small team of neuroscientists at the University of Copenhagen and the University of Iceland began asking a different kind of question. Not what molecule could be added to the brain — but <em>what rhythm</em> could be played to it.</p>
            <span className="lift">"Could light alone improve Alzheimer's brain changes — and memory?"</span>
            <p>The answer, in mice, was startlingly clear. <strong>Red light at forty pulses per second</strong> didn't merely slow decline. It reduced toxic amyloid plaques, dialled up the brain's own clearance enzymes, dialled down the enzymes that build new plaque, and — measurably — restored memory on behavioural tests.</p>
            <p>One hour a day. Two days. Visible change.</p>
            <p>The Red Light Healer is what happens when an industrial designer in Copenhagen reads that paper and decides the next chapter shouldn't live inside a clinical-trial freezer. It should live <em>on a side table</em>, in the room where memory is made.</p>
          </div>
        </div>
      </div>
    </section>
  );
}

function Science() {
  return (
    <section className="block">
      <div className="container">
        <div className="section-head">
          <div className="label"><span className="num">§ 02</span>The Science</div>
          <h2>Four numbers that <em>started everything</em>.</h2>
        </div>

        <div className="science-grid">
          <div className="fact">
            <span className="big red">40<sup>Hz</sup></span>
            <div className="cap"><b>Gamma rhythm.</b> The frequency at which healthy memory circuits naturally synchronise. The brain re-entrains to it.</div>
          </div>
          <div className="fact">
            <span className="big">660<sup>nm</sup></span>
            <div className="cap"><b>Deep red.</b> The wavelength that, in repeated trials, outperformed white, blue, and green light on both behaviour and brain chemistry.</div>
          </div>
          <div className="fact">
            <span className="big">−38<sup>%</sup></span>
            <div className="cap"><b>Plaque reduction.</b> Observed amyloid-β decrease in the hippocampus after two weeks of one-hour-per-day exposure (mouse model).</div>
          </div>
          <div className="fact">
            <span className="big">+2,1<sup>×</sup></span>
            <div className="cap"><b>Clearance enzymes.</b> The brain's own amyloid-clearing enzyme, ADAM17, more than doubled. The faucet turned down; the drain opened up.</div>
          </div>
        </div>

        <ColorComparison />

        <div style={{ marginTop: 80 }}>
          <div className="section-head" style={{ marginBottom: 28 }}>
            <div className="label"><span className="num">§ 02.1</span>The Pathway</div>
            <h2 style={{ fontSize: "clamp(28px, 3.5vw, 44px)" }}>From the eye to the <em>hippocampus</em>.</h2>
          </div>
          <div className="pathway">
            <div className="path-node">
              <span className="n">→ 01 · Entry</span>
              <h4>Visual <em>Cortex</em></h4>
              <div className="desc">Forty-hertz pulses enter through the retina and re-engage gamma activity in the visual cortex within seconds.</div>
            </div>
            <div className="path-node">
              <span className="n">→ 02 · Relay</span>
              <h4>The <em>Thalamus</em></h4>
              <div className="desc">The rhythm is relayed through the thalamus, the brain's central switchboard, propagating gamma activity outward.</div>
            </div>
            <div className="path-node">
              <span className="n">→ 03 · Memory</span>
              <h4>The <em>Hippocampus</em></h4>
              <div className="desc">Memory circuits begin synchronising. Clearance enzymes rise. Amyloid load falls. The network re-engages.</div>
            </div>
          </div>
        </div>

        <FlickerDemo />

        <Timeline />
      </div>
    </section>
  );
}

function ColorComparison() {
  const [efficacies, setEfficacies] = useState([0, 0, 0, 0]);
  const ref = useRef(null);

  useEffect(() => {
    const obs = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) {
        setTimeout(() => setEfficacies([42, 28, 22, 96]), 100);
      }
    }, { threshold: 0.3 });
    if (ref.current) obs.observe(ref.current);
    return () => obs.disconnect();
  }, []);

  const cells = [
    { c: "white", name: "White", stat: "Polychromatic", e: 0 },
    { c: "blue", name: "Blue", stat: "470 nm", e: 1 },
    { c: "green", name: "Green", stat: "525 nm", e: 2 },
    { c: "red", name: "Red", stat: "660 nm", e: 3, winner: true },
  ];

  return (
    <div className="color-row" ref={ref}>
      {cells.map((cell) => (
        <div key={cell.c} className={"color-cell" + (cell.winner ? " winner" : "")}>
          {cell.winner && <span className="winner-tag">Strongest response</span>}
          <div className={"swatch " + cell.c} />
          <div>
            <div className="cell-name">{cell.winner ? <em>{cell.name}</em> : cell.name}</div>
            <div className="cell-stat" style={{ marginTop: 6 }}>{cell.stat} · 40 Hz</div>
          </div>
          <div>
            <div className="cell-stat" style={{ marginBottom: 8 }}>Plaque clearance, relative</div>
            <div className="efficacy-bar">
              <div style={{ width: efficacies[cell.e] + "%" }} />
            </div>
            <div className="cell-stat" style={{ marginTop: 8, fontFamily: "var(--serif)", fontSize: 24, letterSpacing: "-0.01em", textTransform: "none", color: cell.winner ? "var(--red-glow)" : "var(--ink)" }}>
              {efficacies[cell.e]}<span style={{ fontFamily: "var(--mono)", fontSize: 10 }}>%</span>
            </div>
          </div>
        </div>
      ))}
    </div>
  );
}

function FlickerDemo() {
  const [freq, setFreq] = useState(40);
  const [color, setColor] = useState("red");
  const [brightness, setBrightness] = useState(72);
  const [on, setOn] = useState(true);
  const orbRef = useRef(null);

  // simulate flicker — capped at 12 Hz visual update so it doesn't strobe at 40
  useEffect(() => {
    if (!orbRef.current) return;
    const orb = orbRef.current;
    const periodMs = 1000 / freq;
    // visual: square wave but capped so we don't damage anyone's eyes
    const visualPeriod = Math.max(periodMs, 1000 / 12);
    let raf, last = performance.now(), state = true;
    const tick = (t) => {
      if (t - last >= visualPeriod / 2) {
        state = !state;
        orb.style.opacity = state ? "1" : "0.35";
        last = t;
      }
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [freq]);

  const colorMap = {
    white: { bg: "radial-gradient(circle at 50% 40%, #FFF, #DDD)", glow: "rgba(255,255,255,0.4)" },
    blue:  { bg: "radial-gradient(circle at 50% 40%, #6F9DE6, #2B4F8E)", glow: "rgba(76,123,201,0.55)" },
    green: { bg: "radial-gradient(circle at 50% 40%, #7FCCA1, #2F6E4B)", glow: "rgba(91,170,126,0.55)" },
    red:   { bg: "radial-gradient(circle at 50% 40%, #FF4A40, #6B1614)", glow: "rgba(255,74,64,0.6)" },
  };

  const orbStyle = {
    background: colorMap[color].bg,
    boxShadow: `0 0 ${80 + brightness}px ${10 + brightness/4}px ${colorMap[color].glow}`,
    filter: `brightness(${0.5 + brightness/100})`,
  };

  return (
    <div className="flicker-demo" style={{ marginTop: 80 }}>
      <div className="flicker-controls">
        <h3>Try the <em>panel</em>.</h3>
        <p>The published research found one combination outperforms the rest. Cycle the dials and see — you'll land where the science did.</p>

        <div className="knob">
          <div className="row">
            <span className="name">Wavelength</span>
            <span className="val">
              {color === "red" ? <em>660 nm — Red</em> : color === "green" ? "525 nm — Green" : color === "blue" ? "470 nm — Blue" : "Polychromatic — White"}
            </span>
          </div>
          <div className="color-pick">
            {["white", "blue", "green", "red"].map(c => (
              <button key={c} data-c={c} className={color === c ? "active" : ""} onClick={() => setColor(c)} aria-label={c} />
            ))}
          </div>
        </div>

        <div className="knob">
          <div className="row">
            <span className="name">Flicker frequency</span>
            <span className="val">{freq === 40 ? <em>{freq} Hz</em> : `${freq} Hz`}</span>
          </div>
          <input type="range" min="0" max="80" step="1" value={freq} onChange={(e) => setFreq(+e.target.value)} />
        </div>

        <div className="knob">
          <div className="row">
            <span className="name">Brightness</span>
            <span className="val">{brightness}%</span>
          </div>
          <input type="range" min="20" max="100" step="1" value={brightness} onChange={(e) => setBrightness(+e.target.value)} />
        </div>
      </div>

      <div className="flicker-stage">
        <div className="flicker-readout">
          <span>Fig. 02 · Live panel preview</span>
          <span className="live-dot">{freq === 40 && color === "red" ? "Therapeutic window" : "Off-protocol"}</span>
        </div>
        <div className="flicker-orb" ref={orbRef} style={orbStyle} />
        <div className="flicker-warning">
          ⚠ Visual flicker capped at 12 Hz in preview for safety — the real panel runs at full 40 Hz with safety interlocks.
        </div>
      </div>
    </div>
  );
}

function Timeline() {
  const events = [
    { t: "Day 0", e: "First exposure", m: "1 hour · 660 nm · 40 Hz" },
    { t: "Day 2", e: "Behavioural memory tests improve in early-stage models", m: "Y-maze · novel object" },
    { t: "Day 7", e: "ADAM17 clearance enzyme begins to rise", m: "Hippocampal tissue" },
    { t: "Day 14", e: "Amyloid-β plaque load measurably reduced", m: "−38% in hippocampus" },
    { t: "Day 14", e: "BACE1 (plaque-producing enzyme) falls", m: "The faucet turns down" },
    { t: "Day 21", e: "Memory performance improves in advanced models", m: "Statistically significant" },
  ];
  return (
    <div className="timeline" style={{ marginTop: 80 }}>
      <div>
        <div className="label" style={{ fontFamily: "var(--mono)", fontSize: 11, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--muted)", marginBottom: 14 }}><span style={{ color: "var(--red)" }}>§ 02.2 </span>What happens, when</div>
        <h3 style={{ fontFamily: "var(--serif)", fontWeight: 400, fontSize: 36, lineHeight: 1.05, letterSpacing: "-0.01em", margin: 0, maxWidth: "14ch" }}>The brain begins to <em style={{ color: "var(--red)" }}>change</em> within days.</h3>
        <p style={{ fontSize: 13, lineHeight: 1.55, color: "var(--ink-2)", marginTop: 20, maxWidth: "32ch" }}>Timeline reflects published animal-model data. Human response timing is the subject of ongoing trials.</p>
      </div>
      <ol>
        {events.map((ev, i) => (
          <li key={i}>
            <span className="time">{ev.t}</span>
            <span className="event">{ev.e.includes("Memory") || ev.e.includes("memory") ? <span dangerouslySetInnerHTML={{__html: ev.e.replace(/(memory)/i, "<em>$1</em>")}} /> : ev.e}</span>
            <span className="meta">{ev.m}</span>
          </li>
        ))}
      </ol>
    </div>
  );
}

function Hardware() {
  return (
    <section className="block">
      <div className="container">
        <div className="section-head">
          <div className="label"><span className="num">§ 03</span>The Hardware</div>
          <h2>An object you keep <em>on the side table</em>,<br />not in a drawer.</h2>
        </div>

        <div className="hardware">
          <div className="hw-img">
            <span className="hw-img-cap">Fig. 03 · Industrial design · brushed aluminium</span>
            <div className="hw-band" />
            <div className="hw-visor" />
            <span className="hw-img-cap-r">— Replace with product render —</span>
          </div>

          <div className="hw-specs">
            <h3>The <em>Healer.</em></h3>
            <div className="spec-row">
              <span className="k">Light source</span>
              <span className="v">RGB-tunable OLED panel <small>720 cm²</small></span>
            </div>
            <div className="spec-row">
              <span className="k">Peak wavelength</span>
              <span className="v">660 nm <small>± 0,5</small></span>
            </div>
            <div className="spec-row">
              <span className="k">Flicker</span>
              <span className="v">40 Hz, square wave <small>± 0,1 ms</small></span>
            </div>
            <div className="spec-row">
              <span className="k">Irradiance</span>
              <span className="v">2,2 mW/cm² <small>at 60 cm</small></span>
            </div>
            <div className="spec-row">
              <span className="k">Materials</span>
              <span className="v">Brushed aluminium · oak veneer · linen</span>
            </div>
            <div className="spec-row">
              <span className="k">Dimensions</span>
              <span className="v">240 × 320 × 18 mm</span>
            </div>
            <div className="spec-row">
              <span className="k">Weight</span>
              <span className="v">720 g</span>
            </div>
            <div className="spec-row">
              <span className="k">Power</span>
              <span className="v">USB-C, 30 W · or wall</span>
            </div>
            <div className="spec-row">
              <span className="k">Companion app</span>
              <span className="v">iOS · Android · Web</span>
            </div>
            <div className="spec-row">
              <span className="k">Made in</span>
              <span className="v">Designed in CPH/RKV · Assembled in Aalborg</span>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function Pledges() {
  const [selected, setSelected] = useState("healer");
  const sel = PLEDGES.find(p => p.id === selected);

  return (
    <section className="block" id="pledge">
      <div className="container">
        <div className="section-head">
          <div className="label"><span className="num">§ 04</span>Back the Project</div>
          <h2>Five ways to <em>bring</em> the Healer home.</h2>
        </div>

        <div className="pledges">
          {PLEDGES.map(p => (
            <PledgeCard key={p.id} pledge={p} selected={selected === p.id} onSelect={() => setSelected(p.id)} />
          ))}
        </div>

        <div className="pledge-confirm">
          <div>
            <div className="label">Your pledge</div>
            <div className="name">{sel.name} — <span style={{ color: "rgba(242,237,228,0.55)", fontStyle: "italic" }}>{sel.sub}</span></div>
          </div>
          <div className="total">{sel.price.toLocaleString("da-DK")} kr</div>
          <button>Continue to pledge →</button>
        </div>

        <div style={{ marginTop: 80 }}>
          <div className="section-head" style={{ marginBottom: 28 }}>
            <div className="label"><span className="num">§ 04.1</span>Stretch Goals</div>
            <h2 style={{ fontSize: "clamp(28px, 3.5vw, 44px)" }}>What gets <em>better</em> the further we go.</h2>
          </div>
          <div className="stretch">
            {STRETCH.map((s, i) => (
              <div key={i} className={"stretch-item" + (s.locked ? " locked" : "")}>
                <div className="amt">{s.amt}</div>
                <div className="name">{s.name}</div>
                <div className="status">— {s.status}</div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

function PledgeCard({ pledge, selected, onSelect }) {
  const remaining = pledge.cap - pledge.sold;
  const pct = (pledge.sold / pledge.cap) * 100;
  return (
    <div
      className={"pledge" + (selected ? " selected" : "")}
      style={{ gridColumn: `span ${pledge.span}` }}
      onClick={onSelect}
      role="button"
      tabIndex={0}
    >
      <div className={"tag" + (pledge.tagRed ? " red" : "")}>
        <span>· {pledge.tag}</span>
      </div>
      <h3>{pledge.name} <em style={{ color: selected ? "var(--red-glow)" : "var(--muted)", fontSize: "0.55em", display: "block", marginTop: 4 }}>— {pledge.sub}</em></h3>
      <div className="price-row">
        <span className="price">{pledge.price.toLocaleString("da-DK")}</span>
        <span className="currency">DKK</span>
        {pledge.strike && <span className="strike">{pledge.strike.toLocaleString("da-DK")} kr</span>}
      </div>
      <ul className="perk-list">
        {pledge.perks.map((perk, i) => <li key={i}><span>{perk}</span></li>)}
      </ul>
      <div>
        <div className="mono" style={{ display: "flex", justifyContent: "space-between", marginBottom: 6 }}>
          <span>{pledge.sold.toLocaleString("da-DK")} / {pledge.cap.toLocaleString("da-DK")} claimed</span>
          <span>{remaining} left</span>
        </div>
        <div className="pledge-availability">
          <div style={{ width: pct + "%" }} />
        </div>
      </div>
      <div className="pledge-meta">
        <span className="left">Est. delivery · {pledge.delivery}</span>
        <span className="right">Ships {pledge.ships}</span>
      </div>
    </div>
  );
}

function Team() {
  return (
    <section className="block">
      <div className="container">
        <div className="section-head">
          <div className="label"><span className="num">§ 05</span>The Team</div>
          <h2>Built between <em>two harbours</em> —<br />Copenhagen and Reykjavík.</h2>
        </div>
        <div className="team">
          {TEAM.map(m => (
            <div className="member" key={m.name}>
              <div className="member-photo">
                <span className="ph">— {m.photo} —</span>
              </div>
              <h4>{m.name}</h4>
              <div className="role">{m.role}</div>
              <p className="bio">{m.bio}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function FAQ() {
  const [open, setOpen] = useState(0);
  return (
    <section className="block">
      <div className="container">
        <div className="section-head">
          <div className="label"><span className="num">§ 06</span>Spørgsmål · Spurningar · FAQ</div>
          <h2>What backers <em>ask us</em> most.</h2>
        </div>
        <div className="faq-list">
          {FAQS.map((f, i) => (
            <div className={"faq-item" + (open === i ? " open" : "")} key={i}>
              <button className="faq-q" onClick={() => setOpen(open === i ? -1 : i)}>
                <span className="num">{String(i + 1).padStart(2, "0")} —</span>
                <span className="q" dangerouslySetInnerHTML={{ __html: f.q.replace(/(treatment|wellness device|cheap red-light|red light|safe|where is the red light healer)/i, m => `<em>${m}</em>`) }} />
                <span className="sign">+</span>
              </button>
              <div className="faq-a">
                <div />
                <div>{f.a}</div>
                <div />
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function Risks() {
  return (
    <section className="block">
      <div className="container">
        <div className="section-head">
          <div className="label"><span className="num">§ 07</span>Risks & Challenges</div>
          <h2>What we are <em>honest about</em>.</h2>
        </div>
        <div className="risks-grid">
          <div className="risks-list">
            <div><b>Manufacturing</b><br />OLED yield variability could push delivery by weeks. Our Korean panel partner has produced for medical-grade clients since 2018.</div>
            <hr />
            <div><b>Regulatory</b><br />Wellness today; clinical clearance is a multi-year path. We are not promising it inside this campaign.</div>
            <hr />
            <div><b>Science</b><br />Animal model data is animal model data. Human trials begin late 2026 in Copenhagen and Reykjavík.</div>
            <hr />
            <div><b>Logistics</b><br />Worldwide shipping by sea-freight where possible to reduce emissions. Some routes may add 2–3 weeks.</div>
          </div>
          <div className="risks-body">
            <p>We will tell you when something slips. We will tell you why. We will tell you the same week we know.</p>
            <p>Hardware is hard. So is neuroscience. We have spent two years engineering both to a place where a Kickstarter is the right next step — but we have not eliminated risk, and we will not pretend we have.</p>
            <p>The Healer is wellness-grade today, not a medical device. Used as designed, it is one of the gentlest interventions you can offer a brain. It is <em>not</em> a cure, and the word "treatment" belongs to clinical trials we have not yet run.</p>
            <p>What we are building is the first version of an object that takes seriously the possibility that the brain is more programmable than we thought. If that is the only thing this campaign achieves — getting that object into homes, getting the data flowing, beginning the conversation — we will call it a beginning.</p>
          </div>
        </div>
      </div>
    </section>
  );
}

function Footer() {
  return (
    <footer>
      <div className="container">
        <div className="footer-grid">
          <div>
            <div className="wordmark">Red Light Healer<sup style={{ fontSize: 12, verticalAlign: "top", fontFamily: "var(--mono)", letterSpacing: "0.1em" }}>™</sup></div>
            <div className="tagline">Light, at the rhythm the brain remembers in.</div>
          </div>
          <div className="footer-col">
            <h5>Project</h5>
            <ul>
              <li><a>Story</a></li>
              <li><a>Science</a></li>
              <li><a>Hardware</a></li>
              <li><a>Pledges</a></li>
            </ul>
          </div>
          <div className="footer-col">
            <h5>Company</h5>
            <ul>
              <li><a>Team</a></li>
              <li><a>Press kit</a></li>
              <li><a>Research</a></li>
              <li><a>Careers · 4 open</a></li>
            </ul>
          </div>
          <div className="footer-col">
            <h5>Contact</h5>
            <ul>
              <li><a>hello@redlighthealer.com</a></li>
              <li><a>Refshalevej 163A, CPH</a></li>
              <li><a>Hverfisgata 32, RKV</a></li>
              <li><a>+45 70 22 18 04</a></li>
            </ul>
          </div>
          <div className="footer-col">
            <h5>Legal</h5>
            <ul>
              <li><a>Terms</a></li>
              <li><a>Privacy</a></li>
              <li><a>Safety guidance</a></li>
              <li><a>IEC 62471 compliance</a></li>
            </ul>
          </div>
        </div>
        <div className="footer-bottom">
          <span>© Red Light Healer ApS 2026 · CVR 44 31 02 87</span>
          <div className="right">
            <span>Designed in Copenhagen & Reykjavík</span>
            <span>Assembled in Aalborg</span>
            <span>Wellness device</span>
          </div>
        </div>
      </div>
    </footer>
  );
}

function StickyPledge({ funding }) {
  const [show, setShow] = useState(false);
  useEffect(() => {
    const onScroll = () => {
      const y = window.scrollY;
      setShow(y > window.innerHeight * 1.2 && y < document.body.scrollHeight - window.innerHeight * 1.6);
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  const pct = Math.min(100, (funding.pledged / funding.goal) * 100);
  return (
    <div className={"sticky-pledge" + (show ? " show" : "")}>
      <div className="top"><span>Red Light Healer · live</span><span>{funding.daysLeft} days left</span></div>
      <div className="mid">{funding.pledged.toLocaleString("da-DK")} kr <span style={{ color: "var(--red-glow)", fontSize: 14 }}>· {Math.round(pct * 6) / 1}%</span></div>
      <div className="bar"><div style={{ width: pct + "%" }} /></div>
      <div className="row">
        <span style={{ fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.08em", textTransform: "uppercase", color: "rgba(242,237,228,0.55)" }}>{funding.backers.toLocaleString("da-DK")} backers</span>
        <a href="#pledge">Back this →</a>
      </div>
    </div>
  );
}

function Session({ open, onClose }) {
  const discRef = useRef(null);
  const [elapsed, setElapsed] = useState(0);

  // gentle visual breathing — not 40 Hz, capped at ~8 Hz for safety
  useEffect(() => {
    if (!open || !discRef.current) return;
    const disc = discRef.current;
    let raf, last = performance.now(), state = true;
    const tick = (t) => {
      if (t - last > 130) { // ~7.7 Hz visual proxy
        state = !state;
        disc.style.opacity = state ? "1" : "0.55";
        last = t;
      }
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [open]);

  // timer
  useEffect(() => {
    if (!open) { setElapsed(0); return; }
    const id = setInterval(() => setElapsed(e => e + 1), 1000);
    return () => clearInterval(id);
  }, [open]);

  // esc to close
  useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => {
      window.removeEventListener("keydown", onKey);
      document.body.style.overflow = "";
    };
  }, [open, onClose]);

  const total = 60 * 60; // 1 hour protocol
  const remaining = Math.max(0, total - elapsed);
  const mm = String(Math.floor(remaining / 60)).padStart(2, "0");
  const ss = String(remaining % 60).padStart(2, "0");

  return (
    <div className={"session" + (open ? " show" : "")} aria-hidden={!open}>
      <div className="session-top">
        <span className="live">Session · in progress</span>
        <div className="right">
          <span>660 nm</span>
          <span>40 Hz</span>
          <span>72%</span>
        </div>
      </div>

      <button className="session-exit" onClick={onClose}>Esc · End session</button>

      <div className="session-disc" ref={discRef} />

      <div className="session-bottom">
        <div className="session-time">
          {mm}:{ss}
          <span className="small">— remaining of 60:00</span>
        </div>
        <div className="session-instruction">
          Sit at a comfortable distance.<br />
          Eyes open. Soft gaze.<br />
          Let the light do the work.
        </div>
      </div>
    </div>
  );
}

function App() {
  const [sessionOpen, setSessionOpen] = useState(false);
  return (
    <>
      <Topbar funding={FUNDING} />
      <Masthead />
      <Hero onStartSession={() => setSessionOpen(true)} />
      <Funding funding={FUNDING} />
      <Story />
      <Science />
      <Hardware />
      <Pledges />
      <Team />
      <FAQ />
      <Risks />
      <Footer />
      <StickyPledge funding={FUNDING} />
      <Session open={sessionOpen} onClose={() => setSessionOpen(false)} />
    </>
  );
}

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