/* Glassmail — section components (exported to window) */
const { useState, useEffect, useRef } = React;

/* ---------- icon set (simple stroke icons) ---------- */
const Ic = {
  mail:    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="5" width="18" height="14" rx="2.5"/><path d="m3 7 9 6 9-6"/></svg>,
  shield:  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><path d="M12 3 5 6v5c0 4.2 2.9 7.6 7 9 4.1-1.4 7-4.8 7-9V6l-7-3Z"/><path d="m9 12 2 2 4-4"/></svg>,
  drive:   <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="4" width="18" height="7" rx="2"/><rect x="3" y="13" width="18" height="7" rx="2"/><path d="M7 7.5h.01M7 16.5h.01"/></svg>,
  eyeoff:  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><path d="M10.6 5.2A9 9 0 0 1 12 5c5 0 9 5 9 7a11 11 0 0 1-2 2.6M6.3 6.3A12 12 0 0 0 3 12c0 2 4 7 9 7a9 9 0 0 0 4-1"/><path d="m3 3 18 18"/><path d="M9.9 9.9a3 3 0 0 0 4.2 4.2"/></svg>,
  at:      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="3.5"/><path d="M15.5 12v1.5a2.5 2.5 0 0 0 5 0V12a8.5 8.5 0 1 0-3.3 6.7"/></svg>,
  search:  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>,
  devices: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><rect x="2" y="5" width="14" height="11" rx="2"/><path d="M2 19h12"/><rect x="17" y="9" width="5" height="11" rx="1.5"/></svg>,
  import:  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><path d="M12 3v12"/><path d="m7 10 5 5 5-5"/><path d="M5 21h14"/></svg>,
  scale:   <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><path d="M12 3v18M7 6h10"/><path d="m7 6-3 6a3 3 0 0 0 6 0L7 6Z"/><path d="m17 6-3 6a3 3 0 0 0 6 0l-3-6Z"/></svg>,
  pin:     <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><path d="M12 21s7-6.3 7-11a7 7 0 1 0-14 0c0 4.7 7 11 7 11Z"/><circle cx="12" cy="10" r="2.6"/></svg>,
  key:     <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><circle cx="8" cy="15" r="4"/><path d="m10.8 12.2 8.2-8.2M16 5l3 3M14 7l2 2"/></svg>,
  plus:    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M12 5v14M5 12h14"/></svg>,
  server:  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><rect x="4" y="4" width="16" height="7" rx="2"/><rect x="4" y="13" width="16" height="7" rx="2"/><path d="M8 7.5h.01M8 16.5h.01M12 7.5h4M12 16.5h4"/></svg>,
};

function Brand({size=21}){
  return (
    <a className="brand" href="#top" style={{fontSize:size}}>
      <span className="mark"></span> Glassmail
    </a>
  );
}

/* ---------- Signup — wired to real /api/waitlist endpoint ---------- */
function Signup({cta="Join the waitlist", note, big, source, onSuccess}){
  const [sent, setSent]         = useState(false);
  const [email, setEmail]       = useState("");
  const [local, setLocal]       = useState("");
  const [reserved, setReserved] = useState("");   // the address the server confirmed
  const [errField, setErrField] = useState(null); // 'email' | 'reserved' | null
  const [loading, setLoading]   = useState(false);
  const [serverErr, setServerErr] = useState(null);
  const [honeypot, setHoneypot] = useState("");

  // Flash the offending field so it is obvious which of the two needs fixing.
  const flag = (field, message) => {
    setErrField(field);
    if (message) setServerErr(message);
    setTimeout(()=>setErrField(null), 1400);
  };

  const submit = async (e) => {
    e.preventDefault();
    const addr = email.trim();
    const want = local.trim().toLowerCase();

    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(addr)) return flag('email');
    // Mirrors the server's rule. The server also turns away addresses it keeps
    // for itself, which it alone knows about.
    if (!/^[a-z0-9]([a-z0-9._-]{0,62}[a-z0-9])?$/.test(want)){
      return flag('reserved', 'Use letters, numbers, dots, hyphens and underscores.');
    }

    setLoading(true);
    setServerErr(null);

    try {
      const res = await fetch('/api/waitlist', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({email: addr, reserved: want, source, website: honeypot}),
      });

      const data = await res.json().catch(()=>({}));

      if (!res.ok){
        flag(data.field || 'email', data.error || 'Something went wrong — please try again.');
        return;
      }

      setReserved(data.reserved || `${want}@glassmail.co.uk`);
      if (typeof data.count === 'number' && onSuccess) onSuccess(data.count);
      setSent(true);
    } catch(e) {
      flag('email', 'Network error — please try again.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className={sent ? "is-sent" : ""} style={{width:'100%'}}>
      {!sent && (
        <form className="signup" onSubmit={submit}>
          {/* Honeypot field — visually hidden, left blank by real users */}
          <input type="text" name="website" aria-hidden="true" tabIndex="-1"
            style={{position:'absolute',left:'-9999px',width:'1px',height:'1px',opacity:0}}
            value={honeypot} onChange={e=>setHoneypot(e.target.value)} autoComplete="off" />
          <label className="field" style={errField==='email'?{borderColor:'#ff8d8d'}:null}>
            <span style={{display:'flex',width:18,height:18,color:'var(--faint)'}}>{Ic.mail}</span>
            <input type="email" inputMode="email" placeholder="you@example.co.uk" aria-label="Your email address"
                   value={email} onChange={e=>setEmail(e.target.value)} disabled={loading} />
          </label>
          <label className="field" style={errField==='reserved'?{borderColor:'#ff8d8d'}:null}>
            <span style={{display:'flex',width:18,height:18,color:'var(--faint)'}}>{Ic.at}</span>
            <input type="text" placeholder="yourname" aria-label="Address to reserve"
                   value={local} onChange={e=>setLocal(e.target.value)} disabled={loading}
                   autoCapitalize="none" autoCorrect="off" spellCheck="false" maxLength={64} />
            <span className="suffix">@glassmail.co.uk</span>
          </label>
          <button className="btn" type="submit" disabled={loading}
                  style={loading?{opacity:0.7,cursor:'default'}:null}>
            {loading ? 'Reserving…' : cta}
          </button>
        </form>
      )}
      {!sent && (serverErr || note) && (
        <div className="form-note" style={serverErr?{color:'#ff8d8d'}:null}>
          {serverErr || note}
        </div>
      )}
      {sent && (
        <div className="success show">
          <span className="tick">✓</span>
          <p><b>{reserved} is yours.</b> <span>We'll email <b>{email.trim()}</b> the moment Glassmail opens.</span></p>
        </div>
      )}
    </div>
  );
}

function Count({n="3,140", label="people already on the Glassmail waitlist"}){
  return (
    <div className="count">
      <span className="avatars"><i></i><i></i><i></i><i></i></span>
      <span><b>{n}</b> {label}</span>
    </div>
  );
}

function Nav(){
  const [scrolled, setScrolled] = useState(false);
  useEffect(()=>{
    const on = () => setScrolled(window.scrollY > 12);
    on(); window.addEventListener('scroll', on, {passive:true});
    return ()=>window.removeEventListener('scroll', on);
  },[]);
  return (
    <header className={"nav"+(scrolled?" scrolled":"")}>
      <div className="inner">
        <Brand/>
        <nav className="navlinks">
          <a href="#features">Features</a>
          <a href="#why-uk">Why UK-hosted</a>
          <a href="#pricing">Pricing</a>
          <a href="#faq">FAQ</a>
        </nav>
        <div className="nav-cta">
          <span className="pill"><span className="dot"></span> Coming 2026</span>
          <a className="btn sm" href="#waitlist">Join waitlist</a>
        </div>
      </div>
    </header>
  );
}

/* Count is server-rendered into window.__WAITLIST_COUNT__; onSuccess updates it after a signup */
function Hero(){
  const [count, setCount] = useState(
    typeof window.__WAITLIST_COUNT__ === 'number' ? window.__WAITLIST_COUNT__ : null
  );

  const fmtCount = count !== null ? count.toLocaleString('en-GB') : '3,140';

  return (
    <section className="hero" id="top">
      <div className="wrap">
        <div className="grid">
          <div className="hero-copy">
            <div className="eyebrow">Private email · coming 2026</div>
            <h1>Simple mail, <em className="serif">simply yours.</em></h1>
            <p className="sub">No ads, no profiling, no scanning your mail. Just <b>60GB of private storage for £4.50 a month</b> — quietly hosted in the UK.</p>
            <div className="form" id="waitlist-top">
              <Signup cta="Reserve your inbox" source="hero" note="No spam. One launch email, then you decide." onSuccess={setCount} />
            </div>
            <div className="trust">
              <span>UK-hosted</span>
              <span>End-to-end encryption</span>
              <span>No ads, no AI</span>
            </div>
            <div className="count-wrap"><Count n={fmtCount}/></div>
          </div>
          <div className="hero-visual">
            <div className="hero-glow"></div>
            <div className="inbox">
              <div className="inbox-top">
                <span className="tl"><i></i><i></i><i></i></span>
                <h4>Inbox</h4>
                <span className="store">2.1 / 60 GB</span>
              </div>
              {[
                ["Sophie Carter","Re: project kickoff notes","09:24",true],
                ["Calendar","Reminder: 1:1 at 3:00pm","08:51",true],
                ["Daniel Reeves","Photos from the weekend","Yesterday",false],
                ["The Weekly","This week's top stories","Mon",false],
              ].map(([nm,sj,tm,un],i)=>(
                <div className={"row"+(un?" unread":"")} key={i}>
                  <span className="av"></span>
                  <div className="rc">
                    <div className="l1"><span className="nm">{nm}</span><span className="tm">{tm}</span></div>
                    <div className="sj">{sj}</div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

const FEATURES = [
  ["drive","60GB to grow into","A whole inbox's worth of mail, attachments and years of archives — included from day one, not an upsell."],
  ["eyeoff","Ad-free and AI-free","No ads, no profiling, and no AI reading or training on your messages. Your mail is never fed to a model — you're the customer, not the dataset."],
  ["shield","End-to-end encryption","Your private mail is encrypted so only you can read it. We can't, and neither can anyone else."],
  ["at","Bring your own domain","Use you@yourname.com alongside your Glassmail address, with as many aliases as you need."],
  ["search","Search that keeps up","Find any message in milliseconds — full-text search across every folder, attachment and year."],
  ["import","Move in, in minutes","Import from Gmail, Outlook or any IMAP provider. Works in every mail app you already use."],
];

function Features(){
  return (
    <section className="sec features" id="features">
      <div className="wrap">
        <div className="sec-head center">
          <div className="eyebrow">What you get</div>
          <h2>Everything an inbox should be — <em className="serif">nothing it shouldn't.</em></h2>
          <p>One simple plan, with the features that actually matter and none of the things that mine your attention.</p>
        </div>
        <div className="feat-grid">
          {FEATURES.map(([ic,t,d],i)=>(
            <article className="feat" key={i}>
              <div className="ic">{Ic[ic]}</div>
              <h3>{t}</h3>
              <p>{d}</p>
            </article>
          ))}
        </div>
      </div>
    </section>
  );
}

const POINTS = [
  ["pin","Hosted on UK soil","Your mail lives on servers physically located in the United Kingdom — not shipped overseas to wherever storage is cheapest."],
  ["scale","Under UK jurisdiction","Glassmail is run from the UK and governed by UK and GDPR data-protection law, with clear rules about who can ask for what."],
];

function WhyUK(){
  return (
    <section className="sec whyuk" id="why-uk">
      <div className="wrap">
        <div className="grid">
          <div>
            <div className="eyebrow">A quiet detail that matters</div>
            <h2 style={{fontSize:'clamp(30px,3.4vw,44px)',lineHeight:1.06,letterSpacing:'-0.025em',fontWeight:700,margin:'16px 0 0'}}>
              Where your email lives <em className="serif">is your business.</em>
            </h2>
            <p style={{margin:'18px 0 0',fontSize:18,lineHeight:1.6,color:'var(--muted)',maxWidth:'44ch'}}>
              We don't lead with it, but it's worth knowing: Glassmail is built and kept entirely in the UK.
            </p>
            <div className="points">
              {POINTS.map(([ic,t,d],i)=>(
                <div className="point" key={i}>
                  <div className="pic">{Ic[ic]}</div>
                  <div><h4>{t}</h4><p>{d}</p></div>
                </div>
              ))}
            </div>
          </div>
          <div>
            <div className="sov">
              <div className="ring r1"></div><div className="ring r2"></div><div className="ring r3"></div>
              <div className="blip b1"></div><div className="blip b2"></div><div className="blip b3"></div>
              <div className="pin">
                <div className="glyph" style={{width:78,height:78}}><span style={{width:34,height:34,display:'flex'}}>{Ic.server}</span></div>
                <div className="lbl"><b>United Kingdom</b><br/>Data residency</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

const SOLO_PLAN = [
  ["60GB of storage","Room for years of mail and attachments"],
  ["Ad-free and AI-free","No ads, no profiling, no AI trained on your mail"],
  ["End-to-end encryption","Private mail only you can read"],
  ["Your own domain + aliases","you@yourname.com, unlimited aliases"],
  ["UK-hosted, UK jurisdiction","Stored and governed in the United Kingdom"],
  ["Works everywhere","IMAP, plus apps for web, iOS and Android"],
];

const DUO_PLAN = [
  ["120GB across two inboxes","60GB each — for two people, one bill"],
  ["Two private mailboxes","Separate logins and inboxes, kept apart"],
  ["Everything in Solo","Ad-free, AI-free, encrypted, your own domains"],
  ["UK-hosted, UK jurisdiction","Stored and governed in the United Kingdom"],
  ["Works everywhere","IMAP, plus apps for web, iOS and Android"],
];

function Pricing(){
  return (
    <section className="sec tight" id="pricing">
      <div className="wrap">
        <div className="sec-head center">
          <div className="eyebrow">Pricing</div>
          <h2>Two plans. <em className="serif">One fair price.</em></h2>
          <p>No tiers that turn into traps, no surprise renewals. Pick a single inbox, or share with someone in your household.</p>
        </div>
        <div className="price-grid">
          <div className="price-card">
            <div className="price-top">
              <div className="plan">Solo</div>
              <div className="price-amt"><span className="num">£4.50</span><span className="per">/ month</span></div>
              <div className="stor"><b>60GB</b> of private storage · one inbox</div>
            </div>
            <ul className="price-list">
              {SOLO_PLAN.map(([t,d],i)=>(
                <li key={i}><span className="ck">✓</span><div>{t}<br/><span>{d}</span></div></li>
              ))}
            </ul>
            <div className="price-foot">
              <a className="btn" href="#waitlist" style={{width:'100%'}}>Reserve your inbox</a>
            </div>
          </div>
          <div className="price-card featured">
            <div className="price-tag">For two</div>
            <div className="price-top">
              <div className="plan">Duo</div>
              <div className="price-amt"><span className="num">£8</span><span className="per">/ month</span></div>
              <div className="stor"><b>120GB</b> shared · two inboxes, 60GB each</div>
            </div>
            <ul className="price-list">
              {DUO_PLAN.map(([t,d],i)=>(
                <li key={i}><span className="ck">✓</span><div>{t}<br/><span>{d}</span></div></li>
              ))}
            </ul>
            <div className="price-foot">
              <a className="btn" href="#waitlist" style={{width:'100%'}}>Reserve two inboxes</a>
            </div>
          </div>
        </div>
        <div className="price-fine">Free while in beta · founding members lock in launch pricing for life.</div>
      </div>
    </section>
  );
}

/* Count is server-rendered into window.__WAITLIST_COUNT__; onSuccess updates it after a signup */
function WaitlistCTA(){
  const [count, setCount] = useState(
    typeof window.__WAITLIST_COUNT__ === 'number' ? window.__WAITLIST_COUNT__ : null
  );

  const fmtCount = count !== null ? count.toLocaleString('en-GB') : '3,140';

  return (
    <section className="cta-band" id="waitlist">
      <div className="wrap">
        <div className="cta-card">
          <div className="glow"></div>
          <h2>Be first to <br/><em className="serif">reserve your inbox.</em></h2>
          <p className="lead">Glassmail opens in 2026. Leave your email and we'll send a single invitation the day it's ready — founding members keep their launch price for life.</p>
          <div className="form"><Signup cta="Reserve your inbox" source="cta" onSuccess={setCount} /></div>
          <div className="count-wrap"><Count n={fmtCount}/></div>
        </div>
      </div>
    </section>
  );
}

const FAQS = [
  ["When does Glassmail launch?","We're opening to founding members in 2026. Join the waitlist and you'll get a single email the day invitations go out — no drip campaign in the meantime."],
  ["How much does Glassmail cost?","£4.50 a month for a single 60GB inbox, or £8 a month for Duo — two inboxes sharing 120GB (60GB each). No add-ons and no surprise price hike at renewal. Founding members lock in their launch price for as long as they stay subscribed."],
  ["How is my mail kept private?","Your messages are end-to-end encrypted, so only you can read them. We don't show ads, build advertising profiles, or scan the contents of your mail — full stop."],
  ["Where is my data stored?","On servers physically located in the United Kingdom, run from the UK under UK and GDPR data-protection law."],
  ["Why do your MX records point to Fastmail?","Because until our own mail servers are established, an external email provider is necessary to receive email sent to glassmail.co.uk at all — and that provider is Fastmail. It carries anything you write to us, and their servers are outside the UK. We name them in our privacy notice rather than leave you to find it in a DNS record. Replacing them with our own infrastructure inside the UK is part of what we are building, and it will be done before the service launches."],
  ["Can I use my own domain?","Yes. You can send and receive from you@yourname.com alongside your Glassmail address, and create as many aliases as you like."],
  ["Can I move my existing email over?","Easily. Glassmail imports from Gmail, Outlook and any IMAP provider, and works with the mail apps you already use on web, iOS and Android."],
];

function FAQ(){
  const [open, setOpen] = useState(0);
  return (
    <section className="sec" id="faq">
      <div className="wrap">
        <div className="sec-head center">
          <div className="eyebrow">Questions</div>
          <h2>Good to know</h2>
        </div>
        <div className="faq-list">
          {FAQS.map(([q,a],i)=>{
            const isOpen = open===i;
            return (
              <div className={"faq-item"+(isOpen?" open":"")} key={i}>
                <button className="faq-q" aria-expanded={isOpen} onClick={()=>setOpen(isOpen?-1:i)}>
                  <span style={{flex:1}}>{q}</span>
                  <span className="pm">{Ic.plus}</span>
                </button>
                <div className="faq-a" style={{maxHeight: isOpen ? '320px' : '0'}}>
                  <div className="inner">{a}</div>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </section>
  );
}

function Footer(){
  return (
    <footer className="footer">
      <div className="wrap">
        <div className="foot-grid">
          <div className="foot-brand">
            <Brand/>
            <p className="blurb">Private, ad-free email from £4.50 a month with 60GB of storage. Quietly hosted in the United Kingdom.</p>
          </div>
          <div className="foot-col">
            <h5>Product</h5>
            <a href="#features">Features</a>
            <a href="#pricing">Pricing</a>
            <a href="#why-uk">Why UK-hosted</a>
            <a href="#faq">FAQ</a>
          </div>
          <div className="foot-col">
            <h5>Company</h5>
            <a href="mailto:hello@glassmail.co.uk">Contact</a>
          </div>
          <div className="foot-col">
            <h5>Legal</h5>
            <a href="legal/privacy.html">Privacy</a>
            <a href="legal/terms.html">Terms</a>
            <a href="legal/data-residency.html">Data residency</a>
            <a href="legal/cookies.html">Cookies</a>
          </div>
        </div>
        <div className="foot-bot">
          <span>© 2026 Glassmail · glassmail.co.uk</span>
          <span className="reg">Data stored and processed in the United Kingdom.</span>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { Brand, Signup, Count, Nav, Hero, Features, WhyUK, Pricing, WaitlistCTA, FAQ, Footer });
