// Small reusable bits + section components. All mounted to window.

const { useState, useEffect, useRef } = React;

// ---------- typing hook ----------
function useTyping(text, {speed=55, start=0, loop=true, pauseEnd=1500, onChar}={}){
  const [out, setOut] = useState('');
  const [i, setI] = useState(0);
  useEffect(() => {
    let alive = true;
    let to = setTimeout(function step(){
      if (!alive) return;
      if (i < text.length){
        setOut(text.slice(0, i+1));
        if (onChar) onChar(text[i]);
        setI(i+1);
      } else if (loop){
        to = setTimeout(() => { if (alive){ setOut(''); setI(0);} }, pauseEnd);
        return;
      }
    }, i === 0 ? start : speed + Math.random()*60);
    return () => { alive = false; clearTimeout(to); };
  }, [i, text, speed, loop, pauseEnd]);
  return out;
}

// ---------- HERO ----------
const HEADLINES = [
  ["Sticky notes,", "minus the", "cloud."],
  ["Notes that", "live on your", "desk."],
  ["Your notes.", "Your disk.", "No one else."],
  ["The sticky", "note app", "that stays."],
];

function Hero({ headlineIdx, marginalia }) {
  const h = HEADLINES[headlineIdx] || HEADLINES[0];
  const t1 = useTyping("buy milk — oat, not almond", {speed: 90, start: 400, pauseEnd: 2200});
  const t2 = useTyping("$ git commit -m \"ship it\"", {speed: 55, start: 900, pauseEnd: 2400, onChar: (ch) => {
    if (Math.random() < .5) window.paperSounds && window.paperSounds.playTerm();
  }});
  const t3 = useTyping("# Project Sparkbox\n\nlaunch tasks:\n[ ] DNS\n[ ] copy review\n[x] icons", {speed: 75, start: 1400, pauseEnd: 2600});

  return (
    <section className="hero">
      <div className="wrap">
        <div className="hero-grid">
          <div>
            <div className="eyebrow">v2.4 · Free for personal use</div>
            <h1>
              {h[0]}<br/>
              {h[1]}<br/>
              <span className="ink-underline">{h[2]}</span>
            </h1>
            <p className="sub">
              A free sticky note app for people who like
              their desk quiet and their data local.
            </p>
            <div className="cta-row">
              <a className="btn" href="#download">
                <WindowsGlyph/>
                Download free for Windows
              </a>
              <a className="btn secondary" href="#download">
                <LinuxGlyph/>
                Download for Linux
              </a>
            </div>
            <p className="trust">
              <b>No account. No telemetry.</b> <br/>
              Notes live on your disk as plain JSON.
            </p>
          </div>

          <div className="hero-notes" aria-hidden="true">
            <div
              className="note note-paper"
              onMouseEnter={() => window.paperSounds && window.paperSounds.playPaper()}
            >
              <div className="note-text">
                {t1}<span className="cursor"/>
              </div>
            </div>

            <div
              className="note note-term"
              onMouseEnter={() => window.paperSounds && window.paperSounds.playTerm()}
            >
              <div className="note-text">
                {t2}<span className="cursor"/>
              </div>
            </div>

            <div
              className="note note-grey"
              onMouseEnter={() => window.paperSounds && window.paperSounds.playType()}
            >
              <div className="note-text" style={{whiteSpace:'pre-line'}}>
                {t3}<span className="cursor"/>
              </div>
            </div>

            {marginalia && (
              <>
                <svg style={{position:'absolute', left:'-42px', top:'340px', width:120, height:90}} aria-hidden="true">
                  <path d="M10,10 C 30,60 70,70 110,55" stroke="var(--ink-soft)" strokeWidth="1.5" fill="none" strokeLinecap="round"/>
                  <path d="M105,45 L115,55 L100,58" stroke="var(--ink-soft)" strokeWidth="1.5" fill="none" strokeLinecap="round"/>
                </svg>
                <div className="margin-arrow" style={{left:'-60px', top:'420px', transform:'rotate(-4deg)'}}>
                  real paper feel ↗
                </div>
              </>
            )}
          </div>
        </div>
      </div>
    </section>
  );
}

function WindowsGlyph(){
  return (
    <svg width="14" height="14" viewBox="0 0 14 14" fill="currentColor" aria-hidden="true">
      <rect x="0" y="0" width="6" height="6"/>
      <rect x="8" y="0" width="6" height="6"/>
      <rect x="0" y="8" width="6" height="6"/>
      <rect x="8" y="8" width="6" height="6"/>
    </svg>
  );
}
function LinuxGlyph(){
  return (
    <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.5" aria-hidden="true">
      <circle cx="7" cy="6" r="3.3"/>
      <path d="M4 10 C 4 12, 10 12, 10 10" strokeLinecap="round"/>
    </svg>
  );
}

// ---------- SECTION 2: three papers ----------
function ThreePapers(){
  return (
    <section id="themes-preview">
      <div className="wrap">
        <div className="eyebrow">02 · Paper · Terminal · Typewriter</div>
        <h2 className="section-title">Choose your paper.<br/>Choose your sound.</h2>
        <p className="section-sub">Hover each one. That's the sound it makes when you type.</p>

        <div className="papers-row">
          <PaperCard theme="pc-paper" sound="playPaper" label="Paper" hint="pen scratch"
            sample={"grocery list —\nmilk, bread,\nthe thing Marty\nlikes from Trader Joe's"}/>
          <PaperCard theme="pc-term" sound="playTerm" label="Terminal" hint="mechanical clack"
            sample={"> bugs to fix:\n  - nav flicker\n  - auth redirect\n  - tests flaking"}/>
          <PaperCard theme="pc-type" sound="playType" label="Typewriter" hint="typebar strike"
            sample={"Chapter One.\n\n  It was a quiet\nTuesday morning in\nthe village..."}/>
        </div>
      </div>
    </section>
  );
}

function PaperCard({theme, sound, label, hint, sample}){
  const [armed, setArmed] = useState(false);
  const typed = useTyping(sample, {
    speed: 70, start: 200, pauseEnd: 3000,
    onChar: (ch) => {
      if (armed && ch !== ' ' && ch !== '\n' && Math.random() < 0.45) {
        window.paperSounds && window.paperSounds[sound] && window.paperSounds[sound]();
      }
    }
  });
  return (
    <div className={`paper-card ${theme}`}
         onMouseEnter={() => { setArmed(true); window.paperSounds && window.paperSounds[sound](); }}
         onMouseLeave={() => setArmed(false)}>
      <div className="frame">
        <div className="line" style={{whiteSpace:'pre-line'}}>
          {typed}<span className="cursor"/>
        </div>
      </div>
      <div className="label">
        <span>{label.toUpperCase()}</span>
        <small>♪ {hint}</small>
      </div>
    </div>
  );
}

// ---------- SECTION 3: privacy ----------
function Privacy(){
  const items = [
    { n: "01", h: "No cloud. No account.", p: "Notes are plain JSON files on your computer. Open them in any text editor."},
    { n: "02", h: "Bring your own sync.",  p: "Point at a Syncthing, Dropbox, or OneDrive folder. No servers needed."},
    { n: "03", h: "Encrypt what matters.", p: "AES-256 with a passphrase. Nothing leaves your machine. Ever."},
  ];
  return (
    <section id="privacy">
      <div className="wrap">
        <div className="eyebrow">03 · Privacy</div>
        <h2 className="section-title">Actually private.</h2>
        <p className="section-sub">No dashboards. No analytics SDK. Open your network tools and watch — it doesn't phone home.</p>

        <div className="cols-3">
          {items.map(it => (
            <div className="priv" key={it.n}>
              <div className="num">{it.n}</div>
              <h3>{it.h}</h3>
              <p>{it.p}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ---------- SECTION 4: feature split ----------
function FeatureSplit(){
  const free = [
    "Unlimited notes — stored as plain JSON you own",
    "Paper theme + 5 paper colors, handwriting font, paper typing sound",
    "Always-on-top, resize, auto-save, auto-start with your computer",
    "Rich text + checklists + markdown shortcuts",
    "Wiki links [[like this]] + auto daily note",
    "Redact selection with a black bar",
    "Search across every note",
    "Encrypted notes with a passphrase (AES-256-GCM, offline)",
    "Version history with restore",
    "Global hotkeys — quick capture + boss key",
    "Text file drop-box for mobile capture via Syncthing/Dropbox",
    "JSON import / export — plaintext portability",
  ];
  const sup = [
    "Seven bonus themes: Tech Grey, Terminal, Amber CRT, Typewriter, E-ink, Blueprint, Dossier",
    "Custom sounds: keyboard clacks, typewriter strikes, pencil scratch",
    "Ghost mode — per-note opacity",
    "Snap-to-edge — magnetic note alignment",
    "Paste & drag-drop images",
    "Theme pack imports (coming soon)",
  ];
  return (
    <section id="features">
      <div className="wrap">
        <div className="eyebrow">04 · What's included</div>
        <h2 className="section-title">The free tier is the whole app.<br/>Supporter is how you say thanks.</h2>
        <p className="section-sub">Every essential feature — search, encryption, history, hotkeys, wiki links — is free. Supporter unlocks aesthetic extras and bankrolls development.</p>

        <div className="split">
          <div className="tier">
            <h3>Free</h3>
            <span className="price">forever, for everyone</span>
            <ul>{free.map((f,i) => <li key={i}>{f}</li>)}</ul>
            <a className="btn secondary" href="#download">Download free →</a>
          </div>

          <div className="tier supporter">
            <h3>Supporter</h3>
            <span className="price">$10 · once · lifetime</span>
            <ul>{sup.map((f,i) => <li key={i}>{f}</li>)}</ul>
            <p className="mini">
              Buying this doesn't unlock a paywall on your notes —<br/>
              it funds the developer so the app stays ad-free<br/>
              and account-free.
            </p>
            <a className="btn" href="#pricing">Buy Supporter — $10</a>
          </div>
        </div>
      </div>
    </section>
  );
}

// ---------- SECTION 5: gallery ----------
function Gallery(){
  const tiles = [
    { span: 6, name: "Paper",     klass: "cv-paper",
      body: <>The classic.<br/>Handwriting font,<br/>real paper texture.</>,
      caption: "The classic. Handwriting font, real paper texture, pen scratch sound." },
    { span: 6, name: "Terminal",  klass: "cv-term",
      body: <>{"> notes --tail"}<br/>{">  1 unread from past-self"}<br/>{">  $ _"}</>,
      caption: "Green on black, scanlines, mechanical keyboard clack." },
    { span: 4, name: "Amber CRT", klass: "cv-amber",
      body: <>VT220 READY.<br/>_</>,
      caption: "VT220 amber phosphor. Buckling-spring keys." },
    { span: 4, name: "Typewriter",klass: "cv-type",
      body: <>CHAPTER ONE.<br/><br/>It was a quiet<br/>Tuesday morning...</>,
      caption: "Heavy typebar strike, margin bell, full carriage return." },
    { span: 4, name: "E-ink",     klass: "cv-eink",
      body: <><em>A reading device,</em><br/>not a screen.<br/><br/>Low-contrast. Calm.</>,
      caption: "Quiet, minimal, like a reading device." },
    { span: 6, name: "Blueprint", klass: "cv-blue",
      body: <>sketches &amp;<br/>wiring diagrams<br/>for the garage</>,
      caption: "Navy graph paper with drafting-pen handwriting. Pencil scratch sound." },
    { span: 6, name: "Tech Grey", klass: "cv-grey",
      body: <>
        <div className="h1">Project notes</div>
        Dark mode for builders.<br/>
        <span className="accent">[[wiki links]]</span> · purple caret · <span className="accent">#tags</span><br/>
        Inter font. Pure focus.
      </>,
      caption: "Modern dark theme for code-and-keyboard people. Inter font, purple accents, like the editor you actually use." },
    { span: 6, name: "Dossier",   klass: "cv-doss",
      body: <>
        <div className="stamp">CLASSIFIED</div>
        SUBJECT: <span className="redact">██████████</span><br/>
        LOCATION: <span className="redact">████</span>, VT<br/>
        STATUS: active
      </>,
      caption: "Manila folder, CLASSIFIED stamp. Redact selections with a black bar." },
  ];
  return (
    <section id="themes">
      <div className="wrap">
        <div className="eyebrow">05 · The whole set</div>
        <h2 className="section-title">Eight themes. No subscription.</h2>
        <p className="section-sub">Each one is a full visual + sonic kit. Paper is free. The other seven come with the $10 Supporter pack.</p>

        <div className="gallery">
          {tiles.map((t,i) => (
            <div key={i} className={`tile span-${t.span}`}>
              <div className={`canvas ${t.klass}`}>{t.body}</div>
              <h4>{t.name}</h4>
              <p>{t.caption}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ---------- SECTION 6: power grid ----------
function PowerGrid(){
  const items = [
    ["Ctrl⇧Space", "Quick-capture from anywhere"],
    ["F12",        "Hide everything with the boss key"],
    ["[[link]]",   "Link notes with wiki syntax"],
    ["daily.md",   "Auto-create a daily note"],
    ["[x] done",   "Tick checklists like a to-do app"],
    ["paste IMG",  "Drop images in, they stay local"],
    ["history",    "Browse and restore every saved version"],
    ["snap ⌐",     "Snap notes together like magnets"],
    ["🔒 AES-256", "Encrypt sensitive notes with a passphrase"],
    ["**md**",     "Write Markdown, read it as it types"],
  ];
  return (
    <section id="power">
      <div className="wrap">
        <div className="eyebrow">06 · Marginalia, hotkeys, small joys</div>
        <h2 className="section-title">Features power users<br/>actually use.</h2>

        <div className="power">
          {items.map(([k, t], i) => (
            <div className="pwr" key={i}>
              <span className="k">{k}</span>
              <div className="t">{t}</div>
              <span className="num-tag">{String(i+1).padStart(2,'0')}</span>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ---------- SECTION 7: pricing ----------
function Pricing(){
  return (
    <section id="pricing">
      <div className="wrap">
        <div className="eyebrow">07 · Pricing</div>
        <h2 className="section-title" style={{textAlign:'center'}}>Pay once, or don't.</h2>
        <p className="section-sub" style={{margin:'0 auto 52px', textAlign:'center'}}>
          No subscriptions. No recurring charges. Buy once, use forever.
        </p>

        <div className="pricing">
          <div className="price-card">
            <h3>Free</h3>
            <div className="amt">$0</div>
            <p>forever, for everyone.</p>
            <a className="btn secondary" href="#download">Download free</a>
          </div>
          <div className="price-card pro">
            <h3>Supporter</h3>
            <div className="amt">$10</div>
            <p>one time · lifetime · all themes + extras</p>
            <a className="btn" href="#">Buy license</a>
          </div>
        </div>

        <p className="price-footnote">No subscriptions · No recurring charges · Buy once, use forever</p>
      </div>
    </section>
  );
}

// ---------- SECTION 8: download ----------
function detectOS(){
  if (typeof navigator === 'undefined') return 'Windows';
  const p = navigator.platform || '';
  const ua = navigator.userAgent || '';
  if (/Mac/i.test(p)) return 'macOS';
  if (/Linux/i.test(p) || /Linux/i.test(ua)) return 'Linux';
  return 'Windows';
}

function Download(){
  const [os] = useState(detectOS());
  return (
    <section id="download">
      <div className="wrap">
        <div className="eyebrow">08 · Download</div>
        <h2 className="section-title">Get it on your machine.</h2>

        <div className="dl-wrap">
          <div>
            <div className="dl-big">
              We noticed you're on <u>{os}</u>.<br/>
              One button, no signup.
            </div>
            <a className="btn" href="#" style={{fontSize:17, padding:'16px 24px'}}>
              ↓ Download Tom Spark Notes for {os}
            </a>
            <p className="trust" style={{marginTop:18}}>
              SHA-256 checksums published with every release. <br/>
              Reproducible builds. Signed binaries.
            </p>
          </div>

          <ul className="dl-list">
            <li><b>Windows</b><span><a href="#">Installer (.exe)</a> · <a href="#">Portable (.zip)</a></span></li>
            <li><b>Linux</b><span><a href="#">AppImage</a> · <a href="#">.deb</a> · <a href="#">.rpm</a> · <a href="#">.tar.gz</a></span></li>
            <li><b>macOS</b><span style={{color:'var(--ink-faint)'}}>Coming soon.</span></li>
          </ul>
        </div>
      </div>
    </section>
  );
}

// ---------- SECTION 9: faq ----------
function FAQ(){
  const qs = [
    ["Why pay for sticky notes?",
     "Tom Spark Notes is built and maintained by one developer. Buying Supporter funds new features and keeps the app ad-free, account-free, and free for everyone."],
    ["What happens to my notes if the project ends?",
     "Nothing. They're JSON files you own. Open them in any text editor."],
    ["Do you collect any data?",
     "No. Open your network tools and watch — the app doesn't phone home."],
    ["Does the license check need internet?",
     "No. License keys are verified offline using cryptographic signatures. Works on an airplane."],
    ["Why not macOS yet?",
     "It's coming. Drop your email on the download page and we'll let you know."],
  ];
  return (
    <section id="faq">
      <div className="wrap">
        <div className="eyebrow">09 · Questions</div>
        <h2 className="section-title" style={{textAlign:'center'}}>Things people ask.</h2>

        <div className="faq-wrap">
          {qs.map(([q, a], i) => (
            <details className="faq" key={i} open={i===0}>
              <summary>
                <span>{q}</span>
                <span className="plus">+</span>
              </summary>
              <div className="ans">{a}</div>
            </details>
          ))}
        </div>

        <p className="section-sub" style={{textAlign:'center', marginTop:40}}>
          Question we didn't answer?{' '}
          <a href="https://demox.world/d/tomsparknotes" target="_blank" rel="noopener" style={{color:'var(--ink)', borderBottom:'1px solid var(--ink-soft)'}}>
            Ask in the discussion forum →
          </a>
        </p>
      </div>
    </section>
  );
}

// ---------- FOOTER ----------
function Foot(){
  return (
    <footer className="site">
      <div className="wrap row">
        <div>
          <b style={{fontFamily:'var(--font-hand)', fontSize:22, color:'var(--ink)'}}>Tom Spark Notes</b>
          &nbsp;· handcrafted in a cabin somewhere
        </div>
        <div>
          <a href="https://demox.world/d/tomsparknotes" target="_blank" rel="noopener">Discuss &amp; support</a>
          <a href="#">Privacy (we don't collect anything)</a>
          <a href="#">Press kit</a>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, {
  Hero, ThreePapers, Privacy, FeatureSplit,
  Gallery, PowerGrid, Pricing, Download, FAQ, Foot
});
