// Seymoura marketing site — shared tokens + primitives.
// Audience: schools, investors, potential hires.
const { useState, useEffect } = React;

const PALETTE = {
  paper: '#FBF8F3',
  paper2: '#F4EFE6',
  line: '#E6DFD2',
  ink: '#0E1A2B',
  ink2: '#3A4656',
  ink3: '#6B7689',
  navy: '#002A5C',
  navy2: '#001F46',
  navy100: '#E3ECF8',
  navy200: '#B7C4D6',
  coral: '#FF3B3F',
  coral50: '#FFF1F1',
  coral200: '#FFD3D4',
  mustard: '#FFC845',
  mustard50: '#FFF8E1',
  mustard200: '#FBE4A8',
  mustard600: '#B88A12',
};

const FONT_D = 'Fraunces, Georgia, serif';
const FONT_T = 'Poppins, -apple-system, sans-serif';

// --- Shared primitives ---
function Eyebrow({ children, color = PALETTE.coral, style = {} }) {
  return (
    <div style={{fontFamily:FONT_T,fontWeight:700,fontSize:13,letterSpacing:'0.18em',textTransform:'uppercase',color,display:'inline-flex',alignItems:'center',gap:12,...style}}>
      <span style={{width:24,height:2,background:color,display:'inline-block'}}/>
      <span>{children}</span>
    </div>
  );
}

function CtaPrimary({ children, onClick, style = {}, disabled = false, type }) {
  return (
    <button onClick={onClick} disabled={disabled} type={type} style={{fontFamily:FONT_T,fontWeight:700,fontSize:15,background:PALETTE.coral,color:'#fff',border:0,borderRadius:999,padding:'14px 24px',cursor:disabled?'not-allowed':'pointer',boxShadow:'0 4px 12px rgba(255,59,63,0.25)',opacity:disabled?0.6:1,...style}}>{children}</button>
  );
}

function CtaSecondary({ children, onClick, style = {} }) {
  return (
    <button onClick={onClick} style={{fontFamily:FONT_T,fontWeight:600,fontSize:15,background:'transparent',color:PALETTE.navy,border:`1px solid ${PALETTE.line}`,borderRadius:999,padding:'13px 22px',cursor:'pointer',...style}}>{children}</button>
  );
}

function Chip({ children, variant = 'coral' }) {
  const styles = {
    coral: { bg: PALETTE.coral50, color: PALETTE.coral, border: PALETTE.coral200 },
    mustard: { bg: PALETTE.mustard50, color: PALETTE.mustard600, border: PALETTE.mustard200 },
    navy: { bg: PALETTE.navy100, color: PALETTE.navy, border: PALETTE.navy200 },
  }[variant];
  return (
    <span style={{display:'inline-flex',alignItems:'center',gap:8,fontFamily:FONT_T,fontWeight:600,fontSize:14,padding:'8px 16px',borderRadius:999,background:styles.bg,color:styles.color,border:`1px solid ${styles.border}`}}>{children}</span>
  );
}

function useNavMobile() {
  const query = '(max-width: 960px)';
  const [mobile, setMobile] = useState(() => typeof window !== 'undefined' && window.matchMedia(query).matches);
  useEffect(() => {
    const mq = window.matchMedia(query);
    const onChange = (e) => setMobile(e.matches);
    mq.addEventListener('change', onChange);
    return () => mq.removeEventListener('change', onChange);
  }, []);
  return mobile;
}

function Nav({ current, onNav, onPilot }) {
  const links = [
    { key:'home', label:'Home' },
    { key:'product', label:'Product' },
    { key:'schools', label:'For schools' },
    { key:'research', label:'Research' },
    { key:'company', label:'About' },
  ];
  const mobile = useNavMobile();

  if (mobile) {
    return (
      <header style={{position:'sticky',top:0,zIndex:10,background:'rgba(251,248,243,0.92)',backdropFilter:'blur(12px)',borderBottom:`1px solid ${PALETTE.line}`}}>
        <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',padding:'12px 16px'}}>
          <a onClick={() => onNav('home')} style={{display:'flex',alignItems:'center',gap:8,cursor:'pointer',textDecoration:'none',borderBottom:'none'}}>
            <img src="./assets/logo-coral.svg" alt="" style={{width:30,height:26}}/>
            <span style={{fontFamily:FONT_D,fontWeight:600,fontSize:20,color:PALETTE.navy,letterSpacing:'-0.01em'}}>Seymoura</span>
          </a>
        </div>
        <nav style={{display:'flex',gap:6,padding:'0 16px 10px',overflowX:'auto',WebkitOverflowScrolling:'touch',fontFamily:FONT_T,fontSize:13,scrollbarWidth:'none'}}>
          {links.map(l => {
            const active = current === l.key;
            return (
              <a key={l.key} onClick={() => onNav(l.key)} style={{
                cursor:'pointer',flexShrink:0,padding:'7px 14px',borderRadius:999,
                background: active ? PALETTE.navy : 'transparent',
                color: active ? '#fff' : PALETTE.ink,
                border: active ? `1px solid ${PALETTE.navy}` : `1px solid ${PALETTE.line}`,
                fontWeight: active ? 700 : 500,
              }}>{l.label}</a>
            );
          })}
          <button onClick={onPilot} style={{
            flexShrink:0,padding:'7px 14px',borderRadius:999,
            background:PALETTE.coral,color:'#fff',border:0,cursor:'pointer',
            fontFamily:FONT_T,fontSize:13,fontWeight:700,
            boxShadow:'0 3px 8px rgba(255,59,63,0.25)',
          }}>Request a pilot</button>
        </nav>
      </header>
    );
  }

  return (
    <header style={{position:'sticky',top:0,zIndex:10,display:'flex',alignItems:'center',justifyContent:'space-between',padding:'18px 32px',background:'rgba(251,248,243,0.88)',backdropFilter:'blur(12px)',borderBottom:`1px solid ${PALETTE.line}`,gap:16}}>
      <a onClick={() => onNav('home')} style={{display:'flex',alignItems:'center',gap:10,cursor:'pointer',flexShrink:0,textDecoration:'none',borderBottom:'none'}}>
        <img src="./assets/logo-coral.svg" alt="" style={{width:36,height:32}}/>
        <span style={{fontFamily:FONT_D,fontWeight:600,fontSize:22,color:PALETTE.navy,letterSpacing:'-0.01em'}}>Seymoura</span>
      </a>
      <nav style={{display:'flex',gap:'clamp(12px, 2.2vw, 28px)',fontFamily:FONT_T,fontWeight:500,fontSize:14.5,color:PALETTE.ink,flexWrap:'nowrap',minWidth:0}}>
        {links.map(l => {
          const active = current === l.key;
          return (
            <a key={l.key} onClick={() => onNav(l.key)} style={{cursor:'pointer',whiteSpace:'nowrap',color: active ? PALETTE.coral : PALETTE.ink,borderBottom: active ? `2px solid ${PALETTE.coral}` : '2px solid transparent',paddingBottom:2,fontWeight: active ? 700 : 500}}>{l.label}</a>
          );
        })}
      </nav>
      <CtaPrimary onClick={onPilot} style={{whiteSpace:'nowrap',flexShrink:0}}>Request a pilot</CtaPrimary>
    </header>
  );
}

function Footer({ onNav, onPilot }) {
  const groups = [
    { h:'Product', items:[
      { label:'Overview', page:'product' },
      { label:'How it works', page:'home', hash:'how-it-works' },
      { label:'Personal reading coach', page:'product', hash:'personal-reading-coach' },
      { label:'Cross-subject reading', page:'product', hash:'cross-subject-reading' },
      { label:'Hardware', page:'product', hash:'hardware' },
      { label:'Privacy', page:'product', hash:'privacy' },
    ] },
    { h:'For schools', items:[
      { label:'Overview', page:'schools' },
      { label:'Science of Reading', page:'research' },
      { label:'Request a pilot', action: 'pilot' },
    ] },
    { h:'Company', items:[
      { label:'About', page:'company' },
      { label:'Careers', page:'company', hash:'careers' },
    ] },
  ];
  return (
    <footer style={{background:PALETTE.paper,color:PALETTE.ink,padding:'56px 48px 32px',borderTop:`1px solid ${PALETTE.line}`}}>
      <div style={{display:'grid',gridTemplateColumns:'2fr 1fr 1fr 1fr',gap:32,maxWidth:1200,margin:'0 auto'}}>
        <div>
          <div style={{display:'flex',gap:10,alignItems:'center'}}>
            <img src="./assets/logo-coral.svg" alt="" style={{width:32,height:28}}/>
            <span style={{fontFamily:FONT_D,fontWeight:600,fontSize:22,color:PALETTE.navy}}>Seymoura</span>
          </div>
          <p style={{fontFamily:FONT_T,fontSize:14,lineHeight:1.6,color:PALETTE.ink2,marginTop:12,maxWidth:300}}>Closing the reading gap.</p>
        </div>
        {groups.map(col => (
          <div key={col.h}>
            <div style={{fontFamily:FONT_T,fontWeight:700,fontSize:12,letterSpacing:'0.14em',textTransform:'uppercase',color:PALETTE.coral,marginBottom:12}}>{col.h}</div>
            {col.items.map(item => {
              if (item.action === 'pilot') {
                return <div key={item.label} onClick={onPilot} style={{fontFamily:FONT_T,fontSize:14,color:PALETTE.ink2,margin:'6px 0',cursor:'pointer'}}>{item.label}</div>;
              }
              if (item.href) {
                return <a key={item.label} href={item.href} style={{display:'block',fontFamily:FONT_T,fontSize:14,color:PALETTE.ink2,margin:'6px 0',cursor:'pointer',textDecoration:'none'}}>{item.label}</a>;
              }
              return <div key={item.label} onClick={() => onNav(item.page, item.hash)} style={{fontFamily:FONT_T,fontSize:14,color:PALETTE.ink2,margin:'6px 0',cursor:'pointer'}}>{item.label}</div>;
            })}
          </div>
        ))}
      </div>
      <div style={{borderTop:`1px solid ${PALETTE.line}`,paddingTop:20,fontFamily:FONT_T,fontSize:13,color:PALETTE.ink3,display:'flex',justifyContent:'space-between',maxWidth:1200,margin:'40px auto 0'}}>
        <span>© Seymoura 2026  ·  <a href="mailto:hello@seymoura.com" style={{color:'inherit'}}>hello@seymoura.com</a></span>
        <span>Built in the real world.</span>
      </div>
    </footer>
  );
}

const PILOT_FORM = {
  action: 'https://docs.google.com/forms/d/e/1FAIpQLSeuf9YqL_H9Us40xjR60opb-Mb3aLw5r2vZ_sLKsG5Z_8fG5A/formResponse',
  fields: {
    name: 'entry.1542095427',
    email: 'entry.1086655985',
    role: 'entry.439520398',
    schoolDistrict: 'entry.424099939',
    location: 'entry.160718988',
    gradeLevels: 'entry.1736870876',
    studentsCount: 'entry.2110895786',
    challenge: 'entry.1185209233',
  },
  roleOptions: ['District administrator','Principal / assistant principal','Reading specialist / interventionist','Teacher','Other'],
  gradeOptions: ['Pre-K','Kindergarten','1st','2nd','3rd','4th','5th','Other / mixed'],
};

function PilotFormModal({ open, onClose }) {
  const [form, setForm] = useState({ name:'', email:'', role:'', schoolDistrict:'', location:'', gradeLevels:[], studentsCount:'', challenge:'' });
  const [status, setStatus] = useState('idle');

  useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', onKey);
    const prevOverflow = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => { document.removeEventListener('keydown', onKey); document.body.style.overflow = prevOverflow; };
  }, [open]);

  useEffect(() => {
    if (open) {
      setForm({ name:'', email:'', role:'', schoolDistrict:'', location:'', gradeLevels:[], studentsCount:'', challenge:'' });
      setStatus('idle');
    }
  }, [open]);

  if (!open) return null;

  const update = (k) => (e) => setForm(f => ({ ...f, [k]: e.target.value }));
  const toggleGrade = (g) => setForm(f => ({ ...f, gradeLevels: f.gradeLevels.includes(g) ? f.gradeLevels.filter(x => x !== g) : [...f.gradeLevels, g] }));

  const submit = async (e) => {
    e.preventDefault();
    if (status === 'submitting') return;
    setStatus('submitting');
    const body = new FormData();
    body.append(PILOT_FORM.fields.name, form.name);
    body.append(PILOT_FORM.fields.email, form.email);
    body.append(PILOT_FORM.fields.role, form.role);
    body.append(PILOT_FORM.fields.schoolDistrict, form.schoolDistrict);
    body.append(PILOT_FORM.fields.location, form.location);
    for (const g of form.gradeLevels) body.append(PILOT_FORM.fields.gradeLevels, g);
    body.append(PILOT_FORM.fields.studentsCount, form.studentsCount);
    body.append(PILOT_FORM.fields.challenge, form.challenge);
    try {
      await fetch(PILOT_FORM.action, { method:'POST', body, mode:'no-cors' });
      setStatus('success');
    } catch (err) {
      setStatus('error');
    }
  };

  const labelStyle = { fontFamily:FONT_T, fontWeight:600, fontSize:13, color:PALETTE.ink, display:'block', marginBottom:6 };
  const inputStyle = { fontFamily:FONT_T, fontSize:15, padding:'10px 12px', borderRadius:10, border:`1px solid ${PALETTE.line}`, background:'#fff', color:PALETTE.ink, width:'100%', boxSizing:'border-box', outline:'none' };
  const fieldGap = { marginBottom:16 };

  return (
    <div role="dialog" aria-modal="true" onClick={onClose}
      style={{position:'fixed',inset:0,background:'rgba(14,26,43,0.6)',backdropFilter:'blur(6px)',display:'flex',alignItems:'flex-start',justifyContent:'center',padding:'40px 20px',zIndex:100,overflowY:'auto'}}>
      <div onClick={(e) => e.stopPropagation()}
        style={{background:PALETTE.paper,borderRadius:20,boxShadow:'0 40px 80px rgba(14,26,43,0.35)',maxWidth:560,width:'100%',padding:'32px 32px 28px',position:'relative'}}>
        <button onClick={onClose} aria-label="Close"
          style={{position:'absolute',top:16,right:16,width:32,height:32,borderRadius:999,border:0,background:PALETTE.paper2,color:PALETTE.ink2,cursor:'pointer',display:'flex',alignItems:'center',justifyContent:'center',fontSize:18,lineHeight:1}}>×</button>

        {status === 'success' ? (
          <div style={{padding:'8px 0 4px'}}>
            <div style={{fontFamily:FONT_T,fontWeight:700,fontSize:12,letterSpacing:'0.14em',textTransform:'uppercase',color:PALETTE.coral,marginBottom:10}}>Thank you</div>
            <h2 style={{fontFamily:FONT_D,fontWeight:600,fontSize:28,lineHeight:1.15,color:PALETTE.navy,margin:'0 0 12px',letterSpacing:'-0.01em'}}>We'll be in touch soon.</h2>
            <p style={{fontFamily:FONT_T,fontSize:15,lineHeight:1.55,color:PALETTE.ink2,margin:'0 0 20px'}}>Thanks for reaching out. We read every message personally and will follow up from hello@seymoura.com.</p>
            <CtaPrimary onClick={onClose}>Close</CtaPrimary>
          </div>
        ) : (
          <form onSubmit={submit}>
            <div style={{fontFamily:FONT_T,fontWeight:700,fontSize:12,letterSpacing:'0.14em',textTransform:'uppercase',color:PALETTE.coral,marginBottom:10}}>Request a pilot</div>
            <h2 style={{fontFamily:FONT_D,fontWeight:600,fontSize:26,lineHeight:1.15,color:PALETTE.navy,margin:'0 0 8px',letterSpacing:'-0.01em'}}>Tell us about your classroom.</h2>
            <p style={{fontFamily:FONT_T,fontSize:14,lineHeight:1.55,color:PALETTE.ink2,margin:'0 0 22px'}}>A few quick questions — we'll follow up within two business days.</p>

            <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:14,marginBottom:16}}>
              <div>
                <label style={labelStyle}>Your name</label>
                <input required value={form.name} onChange={update('name')} style={inputStyle}/>
              </div>
              <div>
                <label style={labelStyle}>Work email</label>
                <input required type="email" value={form.email} onChange={update('email')} style={inputStyle}/>
              </div>
            </div>

            <div style={fieldGap}>
              <label style={labelStyle}>Your role</label>
              <select required value={form.role} onChange={update('role')} style={{...inputStyle,appearance:'none',backgroundImage:`url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='12' height='8' viewBox='0 0 12 8'><path fill='none' stroke='%230E1A2B' stroke-width='1.6' d='M1 1l5 5 5-5'/></svg>")`,backgroundRepeat:'no-repeat',backgroundPosition:'right 14px center',paddingRight:36}}>
                <option value="" disabled>Choose one</option>
                {PILOT_FORM.roleOptions.map(o => <option key={o} value={o}>{o}</option>)}
              </select>
            </div>

            <div style={fieldGap}>
              <label style={labelStyle}>School or district name</label>
              <input required value={form.schoolDistrict} onChange={update('schoolDistrict')} style={inputStyle}/>
            </div>

            <div style={fieldGap}>
              <label style={labelStyle}>Location</label>
              <input required placeholder="City, State (or country if outside the U.S.)" value={form.location} onChange={update('location')} style={inputStyle}/>
            </div>

            <div style={fieldGap}>
              <label style={labelStyle}>Grade level(s) you'd pilot with</label>
              <div style={{display:'flex',gap:8,flexWrap:'wrap'}}>
                {PILOT_FORM.gradeOptions.map(g => {
                  const active = form.gradeLevels.includes(g);
                  return (
                    <button type="button" key={g} onClick={() => toggleGrade(g)}
                      style={{
                        fontFamily:FONT_T,fontSize:13,fontWeight:600,
                        padding:'8px 14px',borderRadius:999,cursor:'pointer',
                        border:`1px solid ${active?PALETTE.coral:PALETTE.line}`,
                        background: active ? PALETTE.coral : '#fff',
                        color: active ? '#fff' : PALETTE.ink2,
                        transition:'all 150ms',
                      }}>{g}</button>
                  );
                })}
              </div>
            </div>

            <div style={fieldGap}>
              <label style={labelStyle}>Approximate number of students in the pilot</label>
              <input required placeholder="e.g., 20, or 2 classes of 24" value={form.studentsCount} onChange={update('studentsCount')} style={inputStyle}/>
            </div>

            <div style={{...fieldGap,marginBottom:20}}>
              <label style={labelStyle}>What reading challenge are you trying to solve?</label>
              <textarea required rows={3} placeholder={'A sentence or two is enough.'} value={form.challenge} onChange={update('challenge')} style={{...inputStyle,resize:'vertical',fontFamily:FONT_T,lineHeight:1.5}}/>
            </div>

            {status === 'error' && (
              <div style={{fontFamily:FONT_T,fontSize:13,color:PALETTE.coral,marginBottom:12}}>Something went wrong — please try again, or email hello@seymoura.com.</div>
            )}

            <div style={{display:'flex',gap:12,alignItems:'center'}}>
              <CtaPrimary onClick={submit} disabled={status==='submitting'}>
                {status === 'submitting' ? 'Sending…' : 'Send request'}
              </CtaPrimary>
              <button type="button" onClick={onClose} style={{fontFamily:FONT_T,fontSize:14,color:PALETTE.ink3,background:'none',border:0,cursor:'pointer'}}>Cancel</button>
            </div>
          </form>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { PALETTE, FONT_D, FONT_T, Eyebrow, CtaPrimary, CtaSecondary, Chip, Nav, Footer, PilotFormModal });
