/* ============================================================
   BrainTrail · Marketing — shared components
   Nav, footer, brand lockup, trust row, product mockups built
   from the real BrainTrail UI vocabulary, and small atoms.
   Depends on shared.jsx (Icon, MountainArt) + mascot.jsx (BearCub).
   ============================================================ */
const { useState: useMS, useEffect: useME, useRef: useMR } = React;

/* ---------------- Brand lockup ---------------- */
function MkBrand({ onClick }) {
  return (
    <div className="mk-brand" onClick={onClick}>
      <div className="mk-brand-mark">
        <Icon.Mountain stroke="currentColor"/>
      </div>
      <div className="mk-brand-name">Brain<span>Trail</span></div>
    </div>
  );
}

/* ---------------- Sticky nav ---------------- */
function MkNav({ accent, onCta }) {
  const [stuck, setStuck] = useMS(false);
  useME(() => {
    const el = document.querySelector('.mk');
    if (!el) return;
    const onScroll = () => setStuck(el.scrollTop > 8 || window.scrollY > 8);
    el.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => { el.removeEventListener('scroll', onScroll); window.removeEventListener('scroll', onScroll); };
  }, []);
  const links = ['For Families', 'For Teachers', 'For Schools', 'Pricing'];
  return (
    <nav className={`mk-nav ${stuck ? 'is-stuck' : ''}`}>
      <div className="mk-nav-inner">
        <MkBrand/>
        <div className="mk-nav-links">
          {links.map(l => <a key={l} className="mk-nav-link">{l}</a>)}
        </div>
        <div className="mk-nav-spacer"/>
        <div className="mk-nav-cta">
          <a className="mk-nav-link" href="/login">Sign in</a>
          <button className="mk-btn mk-btn-primary" onClick={onCta}>
            Start free<Icon.Arrow stroke="#fff" fill="none"/>
          </button>
        </div>
      </div>
    </nav>
  );
}

/* ---------------- Small atoms ---------------- */
function Eyebrow({ children }) {
  return <p className="mk-eyebrow">{children}</p>;
}

function Stat({ num, label, sub, accent }) {
  return (
    <div>
      <div className="mk-stat-num" style={{ color: accent || 'var(--mk-accent)' }}>{num}</div>
      <div style={{ fontFamily: 'Fredoka', fontWeight: 600, fontSize: 17, marginTop: 8 }}>{label}</div>
      {sub && <p className="mk-muted" style={{ fontSize: 14.5, marginTop: 4 }}>{sub}</p>}
    </div>
  );
}

/* ---------------- Trust / logo row ---------------- */
function TrustRow({ note = 'Trusted in classrooms across 1,200+ schools' }) {
  const orgs = ['Maplewood ISD', 'Crestline Academy', 'Riverbend K–8', 'Northgate Public', 'Summit Charter'];
  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 22 }}>
      <p className="mk-muted" style={{ fontFamily: 'Fredoka', fontWeight: 500, fontSize: 14.5, letterSpacing: '0.04em' }}>
        {note}
      </p>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 'clamp(20px,4vw,52px)', justifyContent: 'center', alignItems: 'center' }}>
        {orgs.map(o => (
          <div key={o} style={{
            display: 'flex', alignItems: 'center', gap: 9,
            fontFamily: 'Fredoka', fontWeight: 600, fontSize: 17,
            color: 'var(--ink)', opacity: 0.42,
          }}>
            <span style={{
              width: 22, height: 22, borderRadius: 7, background: 'var(--ink)',
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center', transform: 'rotate(-4deg)',
            }}>
              <Icon.Mountain width="13" height="13" stroke="var(--cream)" strokeWidth="2.4" fill="none"/>
            </span>
            {o}
          </div>
        ))}
      </div>
    </div>
  );
}

/* ---------------- Image placeholder ---------------- */
function Photo({ label, height = 320, style }) {
  return (
    <div className="mk-ph" style={{ height, ...style }}>
      <span>{label}</span>
    </div>
  );
}

/* ============================================================
   PRODUCT MOCKUPS — built from the BrainTrail UI vocabulary
   ============================================================ */

/* ---- Student tablet: simplified dashboard ---- */
function TabletMockup({ accent = 'var(--teal-700)' }) {
  return (
    <div style={{
      width: 300, background: 'var(--cream)', borderRadius: 30,
      border: '8px solid #20322d', boxShadow: '0 30px 60px -28px rgba(20,58,51,0.5)',
      overflow: 'hidden', flexShrink: 0,
    }}>
      {/* hero band */}
      <div style={{ position: 'relative', height: 118 }}>
        <MountainArt width={284} height={118} palette="sunrise"/>
        <div style={{ position: 'absolute', top: 14, left: 16, display: 'flex', alignItems: 'center', gap: 7 }}>
          <span style={{ width: 22, height: 22, borderRadius: 7, background: 'var(--ink)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>
            <Icon.Mountain width="13" height="13" stroke="var(--cream)" strokeWidth="2.4" fill="none"/>
          </span>
          <span style={{ fontFamily: 'Fredoka', fontWeight: 600, fontSize: 14, color: 'var(--ink)' }}>Hi, Maya!</span>
        </div>
      </div>
      <div style={{ padding: '14px 16px 20px', marginTop: -18, position: 'relative' }}>
        {/* streak + xp card */}
        <div className="mk-card" style={{ padding: 13, borderRadius: 18, marginBottom: 12 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 9 }}>
            <span style={{ fontFamily: 'Fredoka', fontWeight: 600, fontSize: 13 }}>Daily streak</span>
            <span className="bt-chip medium" style={{ fontSize: 11, padding: '3px 9px' }}>🔥 6 days</span>
          </div>
          <div className="bt-progress" style={{ height: 9 }}>
            <div className="bt-progress-fill" style={{ width: '72%' }}/>
          </div>
          <div style={{ fontSize: 11, color: 'var(--ink-mute)', marginTop: 6, fontWeight: 700 }}>180 / 250 XP today</div>
        </div>
        {/* today's trail */}
        <div style={{ fontFamily: 'Fredoka', fontWeight: 600, fontSize: 13, color: 'var(--ink-soft)', marginBottom: 8 }}>Today's trail</div>
        <div className="mk-card" style={{ padding: 12, borderRadius: 18, display: 'flex', gap: 11, alignItems: 'center' }}>
          <div style={{ width: 42, height: 42, borderRadius: 13, background: 'var(--plum-100)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 22 }}>🧮</div>
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: 'Fredoka', fontWeight: 600, fontSize: 14 }}>Fractions Peak</div>
            <div style={{ fontSize: 11.5, color: 'var(--ink-mute)' }}>Stage 3 of 5</div>
          </div>
          <span style={{ width: 30, height: 30, borderRadius: '50%', background: accent, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Icon.Arrow width="15" height="15" stroke="#fff" strokeWidth="2.6" fill="none"/>
          </span>
        </div>
      </div>
    </div>
  );
}

/* ---- Teacher/parent web dashboard mockup ---- */
function DashMockup({ accent = 'var(--teal-700)', wide = false }) {
  const rows = [
    { n: 'Aisha K.', a: 'owl', p: 94, s: 'On track' },
    { n: 'Mateo R.', a: 'fox', p: 71, s: 'On track' },
    { n: 'Priya S.', a: 'rabbit', p: 48, s: 'Needs nudge' },
    { n: 'Jonas W.', a: 'bear', p: 88, s: 'On track' },
  ];
  return (
    <div className="mk-card" style={{ padding: 0, overflow: 'hidden', borderRadius: 22 }}>
      {/* window chrome */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 7, padding: '12px 16px', borderBottom: '1.5px solid #efe6d2', background: '#fff' }}>
        <span style={{ width: 11, height: 11, borderRadius: '50%', background: '#f0b8a8' }}/>
        <span style={{ width: 11, height: 11, borderRadius: '50%', background: '#f3d9a6' }}/>
        <span style={{ width: 11, height: 11, borderRadius: '50%', background: '#aedcc8' }}/>
        <span style={{ marginLeft: 10, fontFamily: 'Fredoka', fontSize: 13, color: 'var(--ink-mute)' }}>app.braintrail.com/classroom</span>
      </div>
      <div style={{ display: 'flex' }}>
        {/* sidebar */}
        <div style={{ width: 58, background: 'var(--teal-900)', padding: '16px 0', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 16 }}>
          <span style={{ width: 30, height: 30, borderRadius: 10, background: 'rgba(255,255,255,0.12)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Icon.Mountain width="17" height="17" stroke="var(--cream)" strokeWidth="2.2" fill="none"/>
          </span>
          {[Icon.Home, Icon.Map, Icon.Clipboard, Icon.Person].map((Ico, i) => (
            <span key={i} style={{ width: 34, height: 34, borderRadius: 11, display: 'flex', alignItems: 'center', justifyContent: 'center', background: i === 1 ? 'rgba(255,255,255,0.14)' : 'transparent' }}>
              <Ico width="19" height="19" stroke={i === 1 ? '#fff' : 'rgba(255,255,255,0.5)'} strokeWidth="2" fill="none"/>
            </span>
          ))}
        </div>
        {/* content */}
        <div style={{ flex: 1, padding: '18px 20px', background: 'var(--cream)' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 14 }}>
            <div>
              <div style={{ fontFamily: 'Fredoka', fontWeight: 600, fontSize: 17, whiteSpace: 'nowrap' }}>Room 4B · Math</div>
              <div style={{ fontSize: 12.5, color: 'var(--ink-mute)' }}>26 trailblazers</div>
            </div>
            <span className="mk-chip" style={{ fontSize: 12, padding: '5px 12px' }}>This week</span>
          </div>
          {/* mini stats */}
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 10, marginBottom: 16 }}>
            {[['Mastery', '78%'], ['Active', '24/26'], ['Time', '4.2h']].map(([l, v]) => (
              <div key={l} className="mk-card" style={{ padding: '11px 13px', borderRadius: 14, boxShadow: 'none' }}>
                <div style={{ fontSize: 11.5, color: 'var(--ink-mute)', fontWeight: 700 }}>{l}</div>
                <div style={{ fontFamily: 'Fredoka', fontWeight: 600, fontSize: 21, color: accent }}>{v}</div>
              </div>
            ))}
          </div>
          {/* roster rows */}
          <div className="mk-card" style={{ padding: 6, borderRadius: 16, boxShadow: 'none' }}>
            {rows.map((r, i) => (
              <div key={r.n} style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '9px 10px', borderBottom: i < rows.length - 1 ? '1px solid #f1e9d6' : 'none' }}>
                <Avatar id={r.a} size={30}/>
                <span style={{ fontFamily: 'Fredoka', fontWeight: 600, fontSize: 13.5, width: 78 }}>{r.n}</span>
                <div className="bt-progress" style={{ flex: 1, height: 8 }}>
                  <div className="bt-progress-fill" style={{ width: `${r.p}%` }}/>
                </div>
                <span style={{
                  fontSize: 11, fontWeight: 700, fontFamily: 'Fredoka',
                  color: r.s === 'On track' ? 'var(--teal-700)' : 'var(--orange-700)',
                  width: 76, textAlign: 'right',
                }}>{r.s}</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

/* ---------------- Demo modal ---------------- */
function DemoModal({ onClose }) {
  const [form, setForm] = useMS({ name: '', email: '', org: '', phone: '', role: 'Teacher' });
  const [status, setStatus] = useMS('idle'); // idle | sending | done | error

  const set = (k) => (e) => setForm(f => ({ ...f, [k]: e.target.value }));

  const submit = async () => {
    if (!form.name || !form.email) return;
    setStatus('sending');
    try {
      const res = await fetch('/api/leads', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(form),
      });
      setStatus(res.ok ? 'done' : 'error');
    } catch {
      setStatus('error');
    }
  };

  const overlay = {
    position: 'fixed', inset: 0, background: 'rgba(10,30,26,0.6)', zIndex: 9000,
    display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20,
  };
  const box = {
    background: 'var(--cream, #fbf5e9)', borderRadius: 28, padding: 'clamp(28px,4vw,44px)',
    width: '100%', maxWidth: 480, position: 'relative',
    boxShadow: '0 32px 64px -20px rgba(10,30,26,0.45)',
    fontFamily: 'Nunito, sans-serif',
  };
  const inp = {
    width: '100%', padding: '11px 14px', borderRadius: 12,
    border: '1.5px solid #ded4bc', fontFamily: 'Nunito, sans-serif',
    fontSize: 15, background: '#fff', outline: 'none', boxSizing: 'border-box',
  };
  const label = { fontWeight: 700, fontSize: 13.5, color: '#4a3f2f', display: 'block', marginBottom: 5 };

  if (status === 'done') {
    return (
      <div style={overlay} onClick={onClose}>
        <div style={{ ...box, textAlign: 'center', display: 'flex', flexDirection: 'column', gap: 16, alignItems: 'center' }}>
          <span style={{ fontSize: 52 }}>🎉</span>
          <h2 style={{ fontFamily: 'Fredoka, sans-serif', fontWeight: 600, fontSize: 26, margin: 0 }}>We'll be in touch!</h2>
          <p style={{ color: '#7a6a55', fontSize: 16, margin: 0 }}>Thanks! A member of our team will reach out within one business day.</p>
          <button className="mk-btn mk-btn-primary" onClick={onClose} style={{ marginTop: 8 }}>Done</button>
        </div>
      </div>
    );
  }

  return (
    <div style={overlay} onClick={(e) => e.target === e.currentTarget && onClose()}>
      <div style={box}>
        <button onClick={onClose} style={{ position: 'absolute', top: 16, right: 18, background: 'none', border: 'none', fontSize: 22, cursor: 'pointer', color: '#9a8a74', lineHeight: 1 }}>✕</button>
        <h2 style={{ fontFamily: 'Fredoka, sans-serif', fontWeight: 600, fontSize: 26, margin: '0 0 6px' }}>Book a demo</h2>
        <p style={{ color: '#7a6a55', fontSize: 15, margin: '0 0 24px' }}>Tell us a bit about yourself and we'll reach out to schedule a walkthrough.</p>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div>
            <label style={label}>Your name *</label>
            <input style={inp} placeholder="Jane Smith" value={form.name} onChange={set('name')}/>
          </div>
          <div>
            <label style={label}>Work email *</label>
            <input style={inp} type="email" placeholder="jane@school.org" value={form.email} onChange={set('email')}/>
          </div>
          <div>
            <label style={label}>Organization</label>
            <input style={inp} placeholder="School or district name" value={form.org} onChange={set('org')}/>
          </div>
          <div>
            <label style={label}>Phone</label>
            <input style={inp} type="tel" placeholder="+1 (555) 000-0000" value={form.phone} onChange={set('phone')}/>
          </div>
          <div>
            <label style={label}>I am a…</label>
            <select style={{ ...inp }} value={form.role} onChange={set('role')}>
              {['Teacher', 'Principal / Admin', 'District Leader', 'Parent', 'Other'].map(r => <option key={r}>{r}</option>)}
            </select>
          </div>
          {status === 'error' && <p style={{ color: '#c0392b', fontSize: 14, margin: 0 }}>Something went wrong — please try again.</p>}
          <button
            className="mk-btn mk-btn-primary"
            style={{ width: '100%', marginTop: 4, opacity: status === 'sending' ? 0.7 : 1 }}
            onClick={submit}
            disabled={status === 'sending'}
          >
            {status === 'sending' ? 'Sending…' : 'Request a demo'}<Icon.Arrow stroke="#fff" fill="none"/>
          </button>
          <p style={{ fontSize: 12.5, color: '#9a8a74', textAlign: 'center', margin: 0 }}>
            We respect your privacy. No spam — ever.
          </p>
        </div>
      </div>
    </div>
  );
}

/* ---------------- Final CTA band ---------------- */
function CtaBand({ onCta, onDemo }) {
  return (
    <section className="mk-section" style={{ position: 'relative', overflow: 'hidden', background: 'var(--teal-900)' }}>
      <div className="mk-topo" style={{ opacity: 0.16 }}>
        <svg viewBox="0 0 1200 500" preserveAspectRatio="xMidYMid slice">
          {[0,1,2,3,4,5,6].map(i => (
            <ellipse key={i} cx="600" cy="320" rx={180 + i*120} ry={120 + i*86}
              fill="none" stroke="#7cd6c4" strokeWidth="1.6"/>
          ))}
        </svg>
      </div>
      <div className="mk-wrap" style={{ position: 'relative', textAlign: 'center', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 22 }}>
        <h2 className="mk-h2" style={{ color: 'var(--cream)', maxWidth: 640 }}>
          Every learner has a summit. Help them reach it.
        </h2>
        <p style={{ color: 'rgba(255,255,255,0.8)', fontSize: 19, maxWidth: 520 }}>
          Start a free family trail in minutes — no card required.
        </p>
        <div style={{ display: 'flex', gap: 14, flexWrap: 'wrap', justifyContent: 'center', marginTop: 4 }}>
          <button className="mk-btn mk-btn-primary mk-btn-lg" onClick={onCta} style={{ background: 'var(--orange-500)', boxShadow: '0 4px 0 var(--orange-700)' }}>
            Start free<Icon.Arrow stroke="#fff" fill="none"/>
          </button>
          <button className="mk-btn mk-btn-lg" onClick={onDemo} style={{ background: 'rgba(255,255,255,0.1)', color: '#fff', boxShadow: 'inset 0 0 0 1.5px rgba(255,255,255,0.3)' }}>
            Book a demo
          </button>
        </div>
      </div>
    </section>
  );
}

/* ---------------- Footer ---------------- */
function MkFooter() {
  const cols = [
    ['Product', ['For Families', 'For Teachers', 'For Schools', 'Trail library', 'Pricing']],
    ['Company', ['About', 'Careers', 'Blog', 'Press']],
    ['Support', ['Help center', 'Contact', 'Status', 'Accessibility']],
    ['Legal', ['Privacy', 'Terms', 'COPPA & FERPA', 'Cookies']],
  ];
  return (
    <footer className="mk-footer">
      <div className="mk-wrap" style={{ paddingBlock: '64px 40px', display: 'grid', gridTemplateColumns: '1.4fr repeat(4, 1fr)', gap: 40 }}>
        <div>
          <div className="mk-brand" style={{ cursor: 'default' }}>
            <div className="mk-brand-mark" style={{ background: 'var(--cream)', color: 'var(--ink)' }}>
              <Icon.Mountain stroke="currentColor"/>
            </div>
            <div className="mk-brand-name" style={{ color: '#fff' }}>Brain<span>Trail</span></div>
          </div>
          <p style={{ fontSize: 14.5, marginTop: 16, maxWidth: 240, color: 'rgba(255,255,255,0.6)' }}>
            Where every problem is an adventure. Standards-aligned practice, K–8.
          </p>
        </div>
        {cols.map(([h, items]) => (
          <div key={h} className="mk-foot-col">
            <h4>{h}</h4>
            {items.map(it => <a key={it}>{it}</a>)}
          </div>
        ))}
      </div>
      <div className="mk-wrap" style={{ paddingBlock: '20px 40px', borderTop: '1px solid rgba(255,255,255,0.12)', display: 'flex', justifyContent: 'space-between', flexWrap: 'wrap', gap: 12, fontSize: 13.5, color: 'rgba(255,255,255,0.5)' }}>
        <span>© 2026 BrainTrail Learning, Inc.</span>
        <span style={{ display: 'inline-flex', gap: 8, alignItems: 'center' }}>
          <Icon.Lock width="13" height="13" stroke="currentColor" strokeWidth="2.2" fill="none"/>
          Student data stays private — always.
        </span>
      </div>
    </footer>
  );
}

/* footer responsive */
(function injectFootResp() {
  if (document.getElementById('mk-foot-resp')) return;
  const s = document.createElement('style');
  s.id = 'mk-foot-resp';
  s.textContent = `@media (max-width: 820px){ .mk-footer .mk-wrap:first-child{ grid-template-columns: 1fr 1fr !important; } }
  @media (max-width: 480px){ .mk-footer .mk-wrap:first-child{ grid-template-columns: 1fr !important; } }`;
  document.head.appendChild(s);
})();

Object.assign(window, {
  MkBrand, MkNav, Eyebrow, Stat, TrustRow, Photo,
  TabletMockup, DashMockup, CtaBand, MkFooter, DemoModal,
});
