// web-system.jsx — 1518.coffee marketing site · layout system
// Nav, buttons, section shell, phone frame, footer.
// Ember palette via useP(). Needs shared.jsx + brand1518.jsx + ig-illustrations.jsx.

(function injectWebCss(){
  if(document.getElementById('web-css')) return;
  const s = document.createElement('style'); s.id='web-css';
  s.textContent = `
    html,body{margin:0;background:#191410}
    .web-root{background:#211B16;color:#F4ECDD;overflow-x:hidden}
    a{color:inherit;text-decoration:none}
    @media (prefers-reduced-motion: reduce){.reveal-init{opacity:1 !important;transform:none !important}}
    .web-btn{transition:opacity .15s, background .15s, border-color .15s}
    .web-btn:hover{opacity:.9}
    .web-link{transition:color .15s}
    .web-link:hover{color:#F3905A}
  `;
  document.head.appendChild(s);
})();

// Scroll-reveal hook
function useReveal(delay){
  const ref = React.useRef(null);
  React.useEffect(()=>{
    const el = ref.current; if(!el) return;
    setTimeout(()=>{
      el.style.opacity = '1';
      el.style.transform = 'none';
    }, (delay||0) + 50);
  },[]);
  return ref;
}
function Reveal({ children, delay=0, style={}, as='div' }){
  const ref = useReveal(delay);
  const El = as;
  return <El ref={ref} style={{ opacity:0, transform:'translateY(16px)', ...style }}>{children}</El>;
}

// ── Buttons ─────────────────────────────────────────────────
function CTAButton({ label, sub, kind='primary', onClick, style={} }){
  const P = useP();
  const primary = kind==='primary';
  return (
    <button className="web-btn sans" onClick={onClick} style={{
      display:'inline-flex', alignItems:'center', justifyContent:'center', gap:10,
      padding:'15px 26px', borderRadius:14, cursor:'pointer', border:'none',
      background: primary ? P.sage : 'transparent',
      color: primary ? '#1C1611' : P.ink,
      boxShadow: primary ? '0 12px 26px rgba(184,83,39,0.32)' : 'none',
      borderWidth: primary ? 0 : 1, borderStyle:'solid', borderColor: P.line,
      fontSize:15.5, fontWeight:700, letterSpacing:'0.01em', whiteSpace:'nowrap', ...style }}>
      {kind==='store' && <AppleLogo />}
      <span>{label}</span>
      {sub && <span style={{ fontWeight:500, opacity:0.7, fontSize:13 }}>{sub}</span>}
    </button>
  );
}
function AppleLogo(){
  return (
    <svg width="17" height="20" viewBox="0 0 17 20" fill="currentColor" aria-hidden>
      <path d="M14.1 10.6c0-2.2 1.8-3.3 1.9-3.3-1-1.5-2.6-1.7-3.2-1.7-1.4-.1-2.7.8-3.3.8-.7 0-1.7-.8-2.8-.8-1.5 0-2.8.8-3.5 2.1-1.5 2.6-.4 6.5 1.1 8.6.7 1 1.6 2.2 2.7 2.1 1.1 0 1.5-.7 2.8-.7s1.6.7 2.8.7c1.1 0 1.9-1 2.6-2.1.8-1.2 1.2-2.3 1.2-2.4-.1 0-2.3-.9-2.3-3.4zM11.9 4.1c.6-.7 1-1.7.9-2.7-.9 0-1.9.6-2.5 1.3-.5.6-1 1.6-.9 2.6 1 .1 2-.5 2.5-1.2z"/>
    </svg>
  );
}

// ── Section shell ───────────────────────────────────────────
function Section({ children, bg, pad='110px 0', id, style={} }){
  const P = useP();
  const { isMobile } = useViewport();
  return (
    <section id={id} style={{ position:'relative', background: bg||'transparent', padding: isMobile ? '64px 0' : pad, ...style }}>
      <div style={{ maxWidth:1160, margin:'0 auto', padding: isMobile ? '0 20px' : '0 32px', position:'relative' }}>
        {children}
      </div>
    </section>
  );
}

function Kicker({ children, color, style={} }){
  const P = useP();
  return <div className="sans" style={{ fontSize:11.5, fontWeight:600, letterSpacing:'0.22em',
    textTransform:'uppercase', color: color||P.sage, ...style }}>{children}</div>;
}

// ── Nav ─────────────────────────────────────────────────────
function WebNav(){
  const P = useP();
  const { isMobile } = useViewport();
  const [scrolled, setScrolled] = React.useState(false);
  React.useEffect(()=>{
    const el = document.querySelector('.web-scroll') || window;
    const onScroll = ()=>{
      const y = el===window ? window.scrollY : el.scrollTop;
      setScrolled(y > 24);
    };
    el.addEventListener('scroll', onScroll, { passive:true });
    return ()=>el.removeEventListener('scroll', onScroll);
  },[]);
  const links = ['How it works','Features','Origins'];
  return (
    <div style={{ position:'sticky', top:0, zIndex:50,
      background: scrolled ? 'rgba(25,20,16,0.82)' : 'transparent',
      backdropFilter: scrolled ? 'blur(14px)' : 'none',
      borderBottom: scrolled ? '1px solid '+P.lineSoft : '1px solid transparent',
      transition:'background .3s, border-color .3s' }}>
      <div style={{ maxWidth:1160, margin:'0 auto', padding: isMobile ? '0 20px' : '0 32px', height:74,
        display:'flex', alignItems:'center', justifyContent:'space-between' }}>
        <Logo1518 size={26} />
        <div className="sans" style={{ display:'flex', alignItems:'center', gap:34 }}>
          {!isMobile && links.map(l=>(
            <a key={l} className="web-link" href={'#'+l.toLowerCase().replace(/ /g,'-')}
              style={{ fontSize:14, fontWeight:500, color:P.inkSoft, whiteSpace:'nowrap' }}>{l}</a>
          ))}
          <CTAButton label={isMobile ? 'Join' : 'Join the waitlist'} kind="primary" style={{ padding:'10px 18px', fontSize:14 }} />
        </div>
      </div>
    </div>
  );
}

// ── Footer ──────────────────────────────────────────────────
function WebFooter(){
  const P = useP();
  const { isMobile } = useViewport();
  // Only links that go to real, on-page content.
  const explore = [
    ['How it works', '#how-it-works'],
    ['Features', '#features'],
    ['The codex', '#codex'],
    ['Origins', '#origins'],
  ];
  const hpad = isMobile ? '0 20px' : '0 32px';
  return (
    <footer style={{ borderTop:'1px solid '+P.line, padding: isMobile ? '48px 0 36px' : '72px 0 48px' }}>
      <div style={{ maxWidth:1160, margin:'0 auto', padding:hpad,
        display:'flex', flexWrap:'wrap', gap:40 }}>
        <div style={{ flex:'1 1 260px', minWidth:240 }}>
          <Logo1518 size={30} />
          <div className="serif" style={{ fontStyle:'italic', fontSize:16, color:P.stone,
            marginTop:16, lineHeight:1.5, maxWidth:280 }}>
            Fifteen for drip. Eighteen for espresso. The two doses every great cup begins with.
          </div>
        </div>
        <div style={{ flex:'0 1 160px' }}>
          <div className="sans" style={{ fontSize:11, fontWeight:600, letterSpacing:'0.16em',
            textTransform:'uppercase', color:P.stoneLt, marginBottom:18 }}>Explore</div>
          <div style={{ display:'flex', flexDirection:'column', gap:11 }}>
            {explore.map(([label,href])=>(
              <a key={label} className="web-link sans" href={href}
                style={{ fontSize:14, color:P.inkSoft }}>{label}</a>
            ))}
          </div>
        </div>
        <div style={{ flex:'0 1 200px' }}>
          <div className="sans" style={{ fontSize:11, fontWeight:600, letterSpacing:'0.16em',
            textTransform:'uppercase', color:P.stoneLt, marginBottom:18 }}>Say hello</div>
          <div style={{ display:'flex', flexDirection:'column', gap:13 }}>
            <a className="web-link sans" href="mailto:hello@1518.coffee"
              style={{ fontSize:14, color:P.inkSoft }}>hello@1518.coffee</a>
            <a className="web-link sans" href="https://instagram.com/1518.coffee" target="_blank" rel="noopener noreferrer"
              style={{ fontSize:14, color:P.inkSoft, display:'flex', alignItems:'center', gap:8 }}>
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
                <rect x="3" y="3" width="18" height="18" rx="5"/>
                <circle cx="12" cy="12" r="4.2"/>
                <circle cx="17.3" cy="6.7" r="1.1" fill="currentColor" stroke="none"/>
              </svg>
              @1518.coffee
            </a>
          </div>
        </div>
      </div>
      <div style={{ maxWidth:1160, margin: isMobile ? '36px auto 0' : '48px auto 0', padding:`24px ${isMobile?'20px':'32px'} 0`,
        borderTop:'1px solid '+P.lineSoft, display:'flex', flexWrap:'wrap', gap:10, justifyContent:'space-between',
        alignItems:'center' }}>
        <span className="sans" style={{ fontSize:12.5, color:P.stoneLt }}>© 2026 1518.coffee — brewed with care.</span>
        <span className="sans" style={{ fontSize:12.5, letterSpacing:'0.14em', color:P.stoneLt }}>1518.coffee</span>
      </div>
    </footer>
  );
}

// ── Waitlist email input ─────────────────────────────────────
// Saves to the 1518 Supabase `waitlist` table (insert-only, anon publishable key).
const WAITLIST_URL = 'https://gansdsyxmtpmyxaxdukg.supabase.co/rest/v1/waitlist';
const WAITLIST_KEY = 'sb_publishable_yBOewuzdk1Aioz0FGYUOrA_IHHqdAQ8';
const EMAIL_RE = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;

function WaitlistInput({ centered }){
  const P = useP();
  const [email, setEmail] = React.useState('');
  const [state, setState] = React.useState('idle'); // idle | loading | done | error
  const [err, setErr] = React.useState('');

  const submit = async (e)=>{
    e.preventDefault();
    const v = email.trim();
    if(!EMAIL_RE.test(v)){ setErr('Please enter a valid email.'); setState('error'); return; }
    setState('loading'); setErr('');
    try {
      const r = await fetch(WAITLIST_URL, {
        method:'POST',
        headers:{
          'Content-Type':'application/json',
          apikey: WAITLIST_KEY,
          Authorization: 'Bearer '+WAITLIST_KEY,
          Prefer:'return=minimal',
        },
        body: JSON.stringify({ email: v, source:'website' }),
      });
      // 409 = already on the list → still a success for the visitor
      if(r.ok || r.status===409){ setState('done'); }
      else { setErr('Something went wrong — please try again.'); setState('error'); }
    } catch(_){ setErr('Network error — please try again.'); setState('error'); }
  };

  if(state==='done') return (
    <div style={{ display:'flex', alignItems:'center', gap:10,
      marginTop: centered ? 0 : 36 }}>
      <div style={{ width:8, height:8, borderRadius:'50%', background:P.sage,
        boxShadow:`0 0 10px ${P.sage}88` }} />
      <span className="serif" style={{ fontStyle:'italic', fontSize:17, color:P.ink }}>
        You're on the list. We'll be in touch.
      </span>
    </div>
  );

  const loading = state==='loading';
  return (
    <div style={{ marginTop: centered ? 0 : 36, maxWidth:440, width:'100%' }}>
      <form onSubmit={submit} style={{ display:'flex', gap:10, flexWrap:'wrap' }}>
        <input type="email" placeholder="Your email" value={email} autoComplete="email"
          onChange={e=>{ setEmail(e.target.value); if(state==='error') setState('idle'); }}
          className="sans" style={{ flex:'1 1 220px', padding:'14px 18px', borderRadius:14,
            border:'1px solid '+(state==='error'?P.sage:P.line), background:P.card, color:P.ink, fontSize:15,
            outline:'none', fontFamily:'inherit' }} />
        <button type="submit" disabled={loading} className="web-btn sans" style={{ padding:'14px 24px',
          borderRadius:14, border:'none', background:P.sage, color:'#1C1611',
          fontSize:15, fontWeight:700, cursor: loading?'default':'pointer', whiteSpace:'nowrap', opacity: loading?0.7:1 }}>
          {loading ? 'Joining…' : 'Join the waitlist'}
        </button>
      </form>
      {state==='error' && (
        <div className="sans" style={{ marginTop:10, fontSize:13, color:P.sageDeep||P.sage }}>{err}</div>
      )}
    </div>
  );
}

Object.assign(window, {
  useReveal, Reveal, CTAButton, AppleLogo, Section, Kicker, WebNav, WebFooter, WaitlistInput,
});
