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

// ============================================================
//  Red Light Healer · Ísland edition
//  Naturalist + scientific Icelandic theme
//  Ice meets lava · 64°08'N 21°56'W
// ============================================================

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

const PLEDGES = [
  {
    id: "early",
    name: "Snemmastjarna",
    sub: "Early Star · Snæfellsnes edition",
    price: 1890, strike: 2490,
    tag: "First light · 312 of 500 claimed",
    tagLava: true,
    perks: [
      "1 × Red Light Healer (40 Hz red OLED panel)",
      "Quick-start in Íslenska / Dansk / English",
      "Companion app, lifetime",
      "Free shipping within EU, Nordic & UK",
    ],
    delivery: "Sep 2026", ships: "Worldwide", sold: 312, cap: 500, span: 4,
  },
  {
    id: "healer",
    name: "Læknirinn",
    sub: "The Healer · standard edition",
    price: 2490,
    tag: "Most chosen · winter shipping window",
    tagLava: false,
    perks: [
      "1 × Red Light Healer (40 Hz red OLED panel)",
      "Linen sleeve, woven in Ísafjörður",
      "Quick-start in Íslenska / Dansk / English",
      "Companion app, lifetime",
      "12-month limited warranty",
    ],
    delivery: "Nov 2026", ships: "Worldwide", sold: 2104, cap: 4000, span: 4, selected: true,
  },
  {
    id: "twin",
    name: "Tvíburar",
    sub: "Twin Set · for two homes",
    price: 4290, strike: 4980,
    tag: "Save 690 DKK · for a parent and a child",
    tagLava: false,
    perks: [
      "2 × Red Light Healer",
      "2 × Ísafjörður 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ínik",
    sub: "Clinic Pack · 6 calibrated units",
    price: 11800,
    tag: "For care homes, sleep clinics & research labs",
    tagLava: 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: "Eldfjall",
    sub: "Volcano Edition · numbered 001–100",
    price: 8900,
    tag: "01 of 100 · cast basalt cradle",
    tagLava: true,
    perks: [
      "1 × Red Light Healer, brushed-aluminium body, numbered 001–100",
      "Cast basalt cradle from Reykjanes peninsula, engraved",
      "Studio visit in Reykjavík (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 Icelandic earths · moss, basalt, ash", status: "Unlocked", locked: false },
  { amt: "1.200.000 kr", name: "Companion app in Íslenska, Sámi, Faroese", 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 for every panel shipped", status: "Locked", locked: true },
];

const FAQS = [
  {
    q: "Is this a medical device, or a wellness device?",
    a: "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?",
    a: "Two things. First, our panel is OLED — even, low-heat illumination with no infrared bleed, calibrated to ±0.5 nm at the red peak. Second, it 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 Iceland with collaborators in Copenhagen, 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 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 noon sunlight at our latitude. 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: "Why Iceland?",
    a: "We make this in Iceland because the country knows something about light. Three months a year, the sun barely rises here; the rest of the year it barely sets. Icelandic medicine has spent a century studying how the body answers seasonal light, and our research network — University of Iceland, Landspítali, the Innovation Center Hafnarfjörður — is where this work began. Final assembly is in Reykjavík; OLED panels come from a medical-grade partner in South Korea.",
  },
  {
    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 the Eldfjall edition). Shipping is free within the EU, Nordic region, and UK; we charge a flat 290 DKK elsewhere.",
  },
];

const TEAM = [
  {
    name: "Sigríður Magnúsdóttir",
    role: "Co-founder · Neuroengineering",
    bio: "PhD in photobiology, Háskóli Íslands. Previously led the OLED therapeutics group at a Reykjavík medical-device startup. First-author on the 2025 paper that started this project.",
    seq: "001",
    field: "Reykjavík · Háskóli Íslands",
  },
  {
    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.",
    seq: "002",
    field: "København · KADK",
  },
  {
    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.",
    seq: "003",
    field: "San Francisco · UCSF",
  },
];

// ============================================================
//  Components
// ============================================================

function Topbar({ funding }) {
  const pct = Math.round((funding.pledged / funding.goal) * 100);
  return (
    <div className="topbar">
      <div className="container topbar-inner">
        <div className="left">
          <span className="live">Live broadcast</span>
          <span className="coords">64°08′N · 21°56′W</span>
          <span>Reykjavík · 12:22</span>
        </div>
        <div className="center">
          <span style={{ fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--ice-2)" }}>Kickstarter ·</span>
          <span>Red Light Healer<span className="dot">.</span></span>
          <span style={{ fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--sulfur)" }}>· Ísland</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-inner">
        <div className="wordmark">
          <span className="mark">Red Light <em>Healer</em></span>
          <span className="sup">Ísland Edition · 001</span>
        </div>
        <div className="masthead-coords">
          <div className="row">
            <span>Lat <span className="v">64°08′N</span></span>
            <span>Lon <span className="v">21°56′W</span></span>
            <span>Alt <span className="v">+12 m</span></span>
            <span>Field <span className="v">Reykjavík</span></span>
          </div>
        </div>
        <div className="masthead-actions">
          <span className="tag-pill lava">Live now · {FUNDING.daysLeft}d left</span>
        </div>
      </div>
    </header>
  );
}

function Hero({ onStartSession }) {
  const [intensity, setIntensity] = useState(0.6);
  useEffect(() => {
    let raf, last = performance.now();
    const loop = (t) => {
      if (t - last > 130) {
        setIntensity(0.4 + Math.random() * 0.4);
        last = t;
      }
      raf = requestAnimationFrame(loop);
    };
    raf = requestAnimationFrame(loop);
    return () => cancelAnimationFrame(raf);
  }, []);

  return (
    <section className="hero">
      <div className="hero-stage">
        {/* ICE side */}
        <div className="hero-ice">
          <div className="hero-flexcol">
            <div className="hero-eyebrow">
              <span className="num">§ 001 / Kickstarter</span>
              <span style={{ flex: 1, height: 1, background: "currentColor", opacity: 0.3 }} />
              <span>Ísland edition</span>
            </div>
            <h1 className="hero-title">
              The cold<br />
              <em>that listens.</em>
            </h1>
            <div className="hero-meta">
              <div className="row"><span>State</span><span className="v">Glacial · stable</span></div>
              <div className="row"><span>Hue</span><span className="v">Frost · 8FAFBE</span></div>
              <div className="row"><span>Function</span><span className="v">Quiet receiver of light</span></div>
              <div className="row"><span>Mood</span><span className="v">Slow · listening</span></div>
            </div>
            <div className="spacer" />
            <button className="session-pill" onClick={onStartSession}>Begin a session →</button>
          </div>
        </div>

        {/* FIRE side */}
        <div className="hero-fire">
          <div className="hero-flexcol">
            <div className="hero-eyebrow">
              <span>Volcanic · 40 Hz · 660 nm</span>
              <span style={{ flex: 1, height: 1, background: "currentColor", opacity: 0.3 }} />
              <span className="num">§ 002 / The Healer</span>
            </div>
            <h1 className="hero-title" style={{ textAlign: "right" }}>
              The warmth<br />
              <em>that mends.</em>
            </h1>
            <div className="hero-meta">
              <div className="row"><span>State</span><span className="v"><em>Active · 40 Hz</em></span></div>
              <div className="row"><span>Hue</span><span className="v"><em>Lava · DC3A28</em></span></div>
              <div className="row"><span>Function</span><span className="v">Re-engages memory circuits</span></div>
              <div className="row"><span>Mood</span><span className="v">Bright · rhythmic</span></div>
            </div>
            <div className="spacer" />
            <div style={{ fontFamily: "var(--serif)", fontSize: 22, fontStyle: "italic", color: "var(--ice-2)", maxWidth: "32ch", textAlign: "right", marginLeft: "auto", textWrap: "pretty" }}>
              "Þar sem ís mætir eldi, fer brennsla af stað."<br />
              <span style={{ color: "var(--muted-2)", fontSize: 14, fontStyle: "normal", fontFamily: "var(--mono)", letterSpacing: "0.06em", textTransform: "uppercase" }}>— Where ice meets fire, something kindles.</span>
            </div>
          </div>
        </div>

        {/* the seam, steam, central disc */}
        <div className="hero-seam" />
        <div className="hero-steam" />
        <div className="hero-disc-wrap">
          <div className="hero-disc-ring" />
          <div className="hero-disc" style={{ opacity: intensity * 0.4 + 0.6 }} />
          <div className="hero-disc-ticks">
            <span>↑ Source · OLED 660 nm</span>
            <span>↓ Pulse · 40 Hz square wave</span>
            <span>← Ice · receiver</span>
            <span>Fire · emitter →</span>
          </div>
        </div>
      </div>
    </section>
  );
}

function SpectrumBand() {
  const items = (
    <>
      <span className="spec-item"><span className="dot" /> Peak wavelength <span className="v lava">660 nm</span></span>
      <span className="spec-item"><span className="dot" /> Flicker <span className="v lava">40.000 Hz</span></span>
      <span className="spec-item"><span className="dot" /> Irradiance <span className="v">2,2 mW/cm²</span></span>
      <span className="spec-item"><span className="dot" /> Coordinates <span className="v aurora">64°08′N · 21°56′W</span></span>
      <span className="spec-item"><span className="dot" /> Solar declination <span className="v">+19°27′</span></span>
      <span className="spec-item"><span className="dot" /> Light protocol <span className="v amber">60 min · daily</span></span>
      <span className="spec-item"><span className="dot" /> Calibration tolerance <span className="v">± 0,5 nm</span></span>
      <span className="spec-item"><span className="dot" /> Aurora index tonight <span className="v aurora">Kp 4</span></span>
    </>
  );
  return (
    <div className="spectrum-band">
      <div className="spectrum-track">
        {items}{items}
      </div>
    </div>
  );
}

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>
          <div className="stat">
            <span className="v">{funding.pledged.toLocaleString("is-IS")} <span style={{ fontSize: 14, fontFamily: "var(--mono)", letterSpacing: "0.08em" }}>kr</span></span>
            <span className="l">Pledged of {funding.goal.toLocaleString("is-IS")} kr goal</span>
          </div>
          <div className="bar"><div style={{ width: pct + "%" }} /></div>
        </div>
        <div className="stat"><span className="v lava">{real}%</span><span className="l">Funded</span></div>
        <div className="stat"><span className="v">{funding.backers.toLocaleString("is-IS")}</span><span className="l">Backers</span></div>
        <div className="stat"><span className="v">{funding.daysLeft}</span><span className="l">Days left</span></div>
        <div className="stat"><span className="v glacier">48</span><span className="l">Countries</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>Forsaga · Premise</div>
          <h2>A flickering panel, in a colour the brain <em>remembers in</em>.<span className="is-title">— Ljós sem hjarnan man.</span></h2>
        </div>

        <div className="story-grid">
          <aside className="aside">
            <div>Reading time<br /><b>4 mínútur</b></div>
            <hr />
            <div>Published<br /><b>19 maí 2026</b></div>
            <hr />
            <div>Field site<br /><b>Reykjavík · 64°08′N</b></div>
            <hr />
            <div>Authors<br />S. Magnúsdóttir<br />M. Holm Lauridsen</div>
            <hr />
            <div>Languages<br />Íslenska · Dansk · 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 Iceland — Háskóli Íslands — and the University of Copenhagen 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 a designer in Copenhagen reads that paper in a café on Hverfisgata, walks out into a low Reykjavík sun, 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 ice">
      <div className="container">
        <div className="section-head">
          <div className="label"><span className="num">§ 02</span>Vísindi · Science</div>
          <h2>Four numbers, measured in <em>two harbours</em>.<span className="is-title">— Reykjavík · København</span></h2>
        </div>

        <div className="fact-board">
          <div className="fact">
            <span className="ident"><span className="seq">F-001</span> · Frequency</span>
            <span className="big lava">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="ident"><span className="seq">F-002</span> · Wavelength</span>
            <span className="big">660<sup>nm</sup></span>
            <div className="cap"><b>Deep red.</b> Outperformed white, blue and green light on both behaviour and brain chemistry in repeated trials.</div>
          </div>
          <div className="fact">
            <span className="ident"><span className="seq">F-003</span> · Plaque load</span>
            <span className="big lava">−38<sup>%</sup></span>
            <div className="cap"><b>Amyloid-β reduction.</b> Observed in hippocampal tissue after two weeks of one-hour-per-day exposure (mouse model).</div>
          </div>
          <div className="fact">
            <span className="ident"><span className="seq">F-004</span> · Clearance</span>
            <span className="big glacier">+2,1<sup>×</sup></span>
            <div className="cap"><b>ADAM17 activity.</b> The brain's own clearance enzyme more than doubled. Faucet down, drain open.</div>
          </div>
        </div>

        <SpectrumViz />

        <div style={{ marginTop: 80 }}>
          <div className="section-head" style={{ marginBottom: 28 }}>
            <div className="label"><span className="num">§ 02.1</span>Leiðin · Pathway</div>
            <h2 style={{ fontSize: "clamp(28px, 3.5vw, 44px)" }}>Through three rooms of the <em>brain</em>.<span className="is-title">— Augn · Þalamus · Hippokampus</span></h2>
          </div>
          <div className="pathway-map">
            <div className="path-node">
              <span className="ident">N-01 · Entry</span>
              <h4>Visual <em>Cortex</em></h4>
              <span className="is">Sjónbörkur</span>
              <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="ident">N-02 · Relay</span>
              <h4>The <em>Thalamus</em></h4>
              <span className="is">Stúkan</span>
              <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="ident">N-03 · Memory</span>
              <h4>The <em>Hippocampus</em></h4>
              <span className="is">Dreki · the seahorse</span>
              <div className="desc">Memory circuits begin synchronising. Clearance enzymes rise. Amyloid load falls. The network re-engages.</div>
            </div>
          </div>
        </div>

        <FlickerDemo />

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

function SpectrumViz() {
  // wavelength visualisation: bar heights = relative therapeutic response
  const bars = useMemo(() => {
    const arr = [];
    for (let nm = 380; nm <= 760; nm += 10) {
      let h = 5;
      if (nm < 440) h = 18 + Math.random() * 5;        // violet — small
      else if (nm < 490) h = 24 + Math.random() * 6;   // blue — modest
      else if (nm < 560) h = 22 + Math.random() * 6;   // green — modest
      else if (nm < 620) h = 38 + Math.random() * 5;   // amber — rising
      else if (nm < 680) h = 78 + Math.random() * 4;   // red — peak
      else h = 30 - (nm - 680) * 0.5 + Math.random() * 3;
      if (nm === 660) h = 96;
      arr.push({ nm, h, peak: nm === 660 });
    }
    return arr;
  }, []);

  return (
    <div className="spectrum-viz">
      <div className="header">
        <h3>Therapeutic <em>response</em> by wavelength</h3>
        <span>Fig. 02 · spectrometer log · n = 84 animal-model exposures</span>
      </div>
      <div className="spectrum-graph">
        {bars.map((b, i) => {
          const color = waveColor(b.nm);
          return (
            <div
              key={i}
              className={"bar" + (b.peak ? " peak" : "")}
              style={{ height: b.h + "%", color }}
            />
          );
        })}
        <span className="label" style={{ left: 0 }}>380 nm — violet</span>
        <span className="label" style={{ right: 0 }}>760 nm — far red</span>
      </div>
    </div>
  );
}

function waveColor(nm) {
  if (nm < 440) return "#7B5BD9";
  if (nm < 490) return "#5BBFE4";
  if (nm < 510) return "#00C896";
  if (nm < 560) return "#9EC95B";
  if (nm < 590) return "#E8DA3F";
  if (nm < 620) return "#E8A33F";
  if (nm < 700) return "#DC3A28";
  return "#8E1E14";
}

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

  useEffect(() => {
    if (!orbRef.current) return;
    const orb = orbRef.current;
    const periodMs = 1000 / freq;
    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.4";
        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%, #8DD2EF, #2C7AAB)", glow: "rgba(91,191,228,0.55)" },
    green: { bg: "radial-gradient(circle at 50% 40%, #4EE0AC, #007A5A)", glow: "rgba(0,200,150,0.55)" },
    red:   { bg: "radial-gradient(circle at 50% 40%, #FF6E50, #6E1106)", glow: "rgba(255,70,48,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">
      <div className="flicker-controls">
        <h3>Try the <em>panel.</em></h3>
        <p>The published research found one combination outperforms the rest. Cycle the dials — you'll land where the science did.</p>

        <div className="knob">
          <div className="row">
            <span className="name">Wavelength · Bylgjulengd</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 · Blikk</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 · Birta</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-grid-overlay">
          <div className="crosshair" />
        </div>
        <div className="flicker-readout">
          <span>Fig. 03 · live panel preview</span>
          <span className="live">{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 · Real panel runs 40 Hz with safety interlocks
        </div>
      </div>
    </div>
  );
}

function SeismicTimeline() {
  // generate a seismic-ish waveform
  const path = useMemo(() => {
    const points = [];
    const N = 240;
    for (let i = 0; i < N; i++) {
      const x = (i / (N - 1)) * 100;
      // big spikes at event markers
      const spikePositions = [0.08, 0.28, 0.42, 0.58, 0.74, 0.92];
      let spike = 0;
      for (const sp of spikePositions) {
        const d = Math.abs(i/N - sp);
        if (d < 0.02) spike += Math.sin((sp * 200 + i) * 0.6) * (0.02 - d) * 60;
      }
      const noise = (Math.sin(i * 0.31) + Math.sin(i * 0.97) + Math.sin(i * 1.7)) * 1.4;
      const y = 50 + noise + spike;
      points.push(`${x.toFixed(2)},${y.toFixed(2)}`);
    }
    return "M" + points.join(" L");
  }, []);

  const events = [
    { t: "Day 0", e: "First exposure", m: "1h · 660 nm" },
    { t: "Day 2", e: "Behavioural memory improves", m: "Y-maze" },
    { t: "Day 7", e: "ADAM17 activity rises", m: "Hippocampus" },
    { t: "Day 14", e: "Amyloid-β plaque load falls", m: "−38%" },
    { t: "Day 14", e: "BACE1 enzyme falls", m: "Faucet down" },
    { t: "Day 21", e: "Memory recovers in advanced models", m: "p < 0.01" },
  ];

  return (
    <div className="seismic-timeline">
      <div className="legend">
        <h3>Brain begins to <em>change</em> within days<span className="is">· Heilinn breytist</span></h3>
        <p>Seismograph of measured signals during 21-day exposure protocol. Timeline reflects published animal-model data; human response timing is the subject of ongoing trials.</p>
      </div>
      <div>
        <div className="seismic-track">
          <svg className="seismic-svg" viewBox="0 0 100 100" preserveAspectRatio="none">
            <path d={path} stroke="var(--lava)" strokeWidth="0.4" fill="none" vectorEffect="non-scaling-stroke" />
          </svg>
        </div>
        <div className="seismic-events">
          {events.map((ev, i) => (
            <div key={i} className="seismic-event">
              <span className="t">{ev.t}</span>
              <span className="e">{ev.e}</span>
              <span className="m">{ev.m}</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function Hardware() {
  return (
    <section className="block dark">
      <div className="container">
        <div className="section-head">
          <div className="label"><span className="num">§ 03</span>Tækið · The Instrument</div>
          <h2>An object you keep on the <em>side table</em>, not in a drawer.<span className="is-title">— Hlutur sem tilheyrir heimilinu.</span></h2>
        </div>

        <div className="hw-grid">
          <div className="hw-img">
            <div className="hw-img-grid" />
            <span className="hw-cap tl">Fig. 04 · Industrial design</span>
            <span className="hw-cap tr">● recording 40 Hz</span>
            <div className="hw-visor" />
            <span className="hw-cap br">— Replace with product render —</span>
          </div>

          <div className="hw-specs">
            <h3>Læknirinn<em>.</em><span className="is">The Healer</span></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 · Ísafjörður 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 CPH/RVK · Assembled Reykjavík</span></div>
          </div>
        </div>
      </div>
    </section>
  );
}

function Aurora() {
  return (
    <section className="aurora">
      <div className="container aurora-inner">
        <h2>
          A country that has spent <em>a century</em> studying <span className="lava">light.</span>
          <span className="is">— Land sem þekkir myrkur og morgunsól.</span>
        </h2>
        <div className="aurora-stats">
          <div className="aurora-stat">
            <span className="v">21<em>h</em></span>
            <span className="l">Summer daylight · 21 June</span>
          </div>
          <div className="aurora-stat">
            <span className="v">4<em>h</em></span>
            <span className="l">Winter daylight · 21 December</span>
          </div>
          <div className="aurora-stat">
            <span className="v">64°<em>N</em></span>
            <span className="l">Reykjavík · field site</span>
          </div>
          <div className="aurora-stat">
            <span className="v"><em>Kp4</em></span>
            <span className="l">Aurora index · tonight</span>
          </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>Stuðningsstig · Pledge tiers</div>
          <h2>Five ways to bring The Healer <em>home</em>.<span className="is-title">— Fimm leiðir.</span></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} — <em>{sel.sub}</em></div>
          </div>
          <div className="total">{sel.price.toLocaleString("is-IS")} 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 better <em>the further</em> we go.<span className="is-title">— Hvað við lofum.</span></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.tagLava ? " lava" : "")}>{pledge.tag}</div>
      <h3 className="pledge-name">{pledge.name}<em>{pledge.sub}</em></h3>
      <div className="price-row">
        <span className="price">{pledge.price.toLocaleString("is-IS")}</span>
        <span className="currency">kr · DKK</span>
        {pledge.strike && <span className="strike">{pledge.strike.toLocaleString("is-IS")} 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, color: "var(--muted)" }}>
          <span>{pledge.sold.toLocaleString("is-IS")} / {pledge.cap.toLocaleString("is-IS")} 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>Hópurinn · The team</div>
          <h2>Built between <em>three harbours</em>.<span className="is-title">— Reykjavík · København · San Francisco</span></h2>
        </div>
        <div className="team">
          {TEAM.map(m => (
            <div className="member" key={m.name}>
              <div className="member-photo">
                <span className="id"><span className="seq">M-{m.seq}</span> · field portrait</span>
                <span className="ph">{m.field}</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>Spurningar · FAQ</div>
          <h2>What backers <em>ask us</em> most.<span className="is-title">— Algengar spurningar.</span></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">{f.q}</span>
                <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>Áhætta · Risks</div>
          <h2>What we are <em>honest about</em>.<span className="is-title">— Hreinskilni.</span></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 Reykjavík and Copenhagen.</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 the object into homes, the data flowing, the conversation beginning — we will call it a beginning.</p>
          </div>
        </div>
      </div>
    </section>
  );
}

function Footer() {
  return (
    <footer>
      <div className="container">
        <div className="footer-grid">
          <div className="footer-brand">
            <div className="mark">Red Light <em>Healer</em></div>
            <div className="tagline">Where ice meets fire, something kindles.</div>
            <div className="coords">
              Field site · <span className="v">64°08′N · 21°56′W</span><br />
              Studio · <span className="v">Hverfisgata 32, Reykjavík</span><br />
              Co-studio · <span className="v">Refshalevej 163A, København</span>
            </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>halló@redlighthealer.is</a></li><li><a>+354 580 8000</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 ehf · 2026 · Kt. 440126-7710</span>
          <div className="right">
            <span>Designed in Reykjavík & København</span>
            <span>Assembled in Reykjavík</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 · Ísland</span><span>{funding.daysLeft}d</span></div>
      <div className="mid">{funding.pledged.toLocaleString("is-IS")} kr <em>· {Math.round(pct)}%</em></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: "var(--ice-2)" }}>{funding.backers.toLocaleString("is-IS")} backers</span>
        <a href="#pledge">Back this →</a>
      </div>
    </div>
  );
}

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

  useEffect(() => {
    if (!open || !discRef.current) return;
    const disc = discRef.current;
    let raf, last = performance.now(), state = true;
    const tick = (t) => {
      if (t - last > 130) {
        state = !state;
        disc.style.opacity = state ? "1" : "0.55";
        last = t;
      }
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [open]);

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

  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;
  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">Lota · 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</button>
      <div className="session-ring" />
      <div className="session-disc" ref={discRef} />
      <div className="session-bottom">
        <div className="session-time">
          {mm}:{ss}
          <span className="small">— remaining of 60:00</span>
          <span className="session-coords">64°08′N · 21°56′W · Reykjavík</span>
        </div>
        <div className="session-instruction">
          <span className="is">Sittu þægilega. Augun opin. Mjúkt augnaráð.</span>
          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)} />
      <SpectrumBand />
      <Funding funding={FUNDING} />
      <Story />
      <Science />
      <Aurora />
      <Hardware />
      <Pledges />
      <Team />
      <FAQ />
      <Risks />
      <Footer />
      <StickyPledge funding={FUNDING} />
      <Session open={sessionOpen} onClose={() => setSessionOpen(false)} />
    </>
  );
}

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