// Shared public chrome — nav, footer, utilities. Pairs with styles/public.css.
const { useState, useEffect, useRef, useMemo } = React;

const NAV = [
  { href:'/product/reservations', label:'Product', key:'product',
    submenu: [
      { href:'/product/reservations', label:'Reservations',  hint:'Books · waitlist · guest CRM' },
      { href:'/product/service',      label:'Service floor', hint:'Floor plan · pacing · host stand' },
      { href:'/product/finance',      label:'Finance & menu',hint:'Invoices · GP · menu engineering' },
      { href:'/product/mise',         label:'Mise · the agent', hint:'Drafts for approval, never autopilot' },
    ]
  },
  { href:'/pricing',     label:'Pricing',    key:'pricing'   },
  { href:'/customers',   label:'Customers',  key:'customers' },
  { href:'/about',       label:'Philosophy', key:'about'     },
  { href:'/changelog',   label:'Changelog',  key:'changelog' },
  { href:'/security',    label:'Security',   key:'security'  },
];

function Brand({ size=22, sub=false }) {
  return (
    <a href="/" className="nav-brand" style={{ fontSize:size }} aria-label="Bord — by Mise en Place">
      <span className="dot"/>
      <span>Bord{sub && <span style={{ color:'var(--site-ink-dim)', fontStyle:'italic', marginLeft:6, fontSize:'0.7em' }}> by Mise en Place</span>}</span>
    </a>
  );
}

function PublicNav({ current }) {
  const [open, setOpen] = useState(null);
  return (
    <header className="nav">
      <div className="wrap nav-inner">
        <Brand sub/>
        <div className="nav-links">
          {NAV.map(item => {
            const active = current === item.key;
            return (
              <div key={item.label}
                   onMouseEnter={() => item.submenu && setOpen(item.label)}
                   onMouseLeave={() => setOpen(null)}
                   style={{ position:'relative', padding:'14px 0' }}>
                <a href={item.href} className={'nav-link' + (active ? ' active' : '')}>
                  {item.label}
                  {item.submenu && <span style={{ opacity:0.5, marginLeft:4, fontSize:9 }}>▾</span>}
                </a>
                {item.submenu && open === item.label && (
                  <div style={{
                    position:'absolute', top:'100%', left:-14, paddingTop:0, minWidth:280, zIndex:50,
                    background:'var(--site-bg-tint)',
                    border:'1px solid var(--site-hair)', borderRadius:6, padding:6,
                    boxShadow:'0 18px 40px rgba(0,0,0,0.4)',
                  }}>
                    {item.submenu.map(s => (
                      <a key={s.label} href={s.href} style={{
                        display:'block', padding:'10px 12px', borderRadius:4,
                      }}
                      onMouseEnter={e => e.currentTarget.style.background='rgba(255,255,255,0.03)'}
                      onMouseLeave={e => e.currentTarget.style.background='transparent'}>
                        <div style={{ fontSize:13.5, color:'var(--site-ink)', fontWeight:500 }}>{s.label}</div>
                        <div style={{ fontSize:11.5, color:'var(--site-ink-dim)', marginTop:2 }}>{s.hint}</div>
                      </a>
                    ))}
                  </div>
                )}
              </div>
            );
          })}
        </div>
        <div style={{ display:'flex', gap:12, alignItems:'center' }}>
          <a href="/login" className="nav-link">Sign in</a>
          <a href="/demo" className="btn btn-primary" style={{ padding:'9px 14px', fontSize:13 }}>Request a demo</a>
        </div>
      </div>
    </header>
  );
}

function PublicFooter() {
  return (
    <footer className="footer">
      <div className="wrap">
        <div className="footer-grid">
          <div>
            <Brand sub/>
            <p className="copy" style={{ marginTop:18, fontSize:14, maxWidth:360 }}>
              The calm operating system for independent fine-dining — reservations, service, and finance on one table.
            </p>
            <div style={{ display:'flex', gap:8, marginTop:18 }}>
              <span className="tag">Stockholm</span>
              <span className="tag">Est. 2023</span>
              <span className="tag tag-gold">Nordics</span>
            </div>
          </div>
          <FooterCol title="Product" links={[
            ['Reservations',  '/product/reservations'],
            ['Service floor', '/product/service'],
            ['Finance & menu','/product/finance'],
            ['Mise · agent',  '/product/mise'],
            ['Pricing',       '/pricing'],
          ]}/>
          <FooterCol title="Company" links={[
            ['Philosophy',  '/about'],
            ['Customers',   '/customers'],
            ['Changelog',   '/changelog'],
            ['Journal',     '#'],
            ['Careers',     '#'],
          ]}/>
          <FooterCol title="Trust" links={[
            ['Security',    '/security'],
            ['Privacy',     '#'],
            ['GDPR & DPA',  '#'],
            ['Status',      '#'],
            ['Subprocessors','#'],
          ]}/>
          <FooterCol title="Operator" links={[
            ['Sign in',         '/login'],
            ['Request a demo',  '/demo'],
            ['Restaurant guide','#'],
            ['Help center',     '#'],
            ['Contact',         '#'],
          ]}/>
        </div>
        <div className="footer-bottom">
          <span>© 2026 Mise en Place AB · Skeppargatan 12, 114 52 Stockholm · Org 559387-2104</span>
          <span style={{ display:'inline-flex', alignItems:'center', gap:6 }}>
            <span style={{ width:6, height:6, borderRadius:999, background:'var(--success)' }}/> All systems operational
          </span>
        </div>
      </div>
    </footer>
  );
}

function FooterCol({ title, links }) {
  return (
    <div className="footer-col">
      <div className="footer-col-title">{title}</div>
      {links.map(([label, href]) => <a key={label} href={href}>{label}</a>)}
    </div>
  );
}

// ===========================================================================
// Section primitives
// ===========================================================================
function Eyebrow({ children, plain, mute }) {
  return <div className={'eyebrow' + (plain?' eyebrow-plain':'') + (mute?' eyebrow-mute':'')}>{children}</div>;
}

function SectionHead({ eyebrow, title, lede, children, align='split' }) {
  if (align === 'center') {
    return (
      <div style={{ textAlign:'center', maxWidth:780, margin:'0 auto 64px' }}>
        {eyebrow && <Eyebrow>{eyebrow}</Eyebrow>}
        <h2 className="display display-lg" style={{ marginTop:24 }}>{title}</h2>
        {lede && <p className="lede" style={{ marginTop:24, marginInline:'auto' }}>{lede}</p>}
        {children}
      </div>
    );
  }
  return (
    <div className="section-head">
      <div>
        {eyebrow && <Eyebrow>{eyebrow}</Eyebrow>}
        <h2 className="display display-lg" style={{ marginTop:24 }}>{title}</h2>
      </div>
      <div>
        {lede && <p className="lede" style={{ marginBottom:24 }}>{lede}</p>}
        {children}
      </div>
    </div>
  );
}

// ===========================================================================
// Logo strip — invented Nordic fine-dining names
// ===========================================================================
const DEFAULT_LOGOS = [
  { name: 'Björk & Hagel', sub: 'Stockholm · 2★' },
  { name: 'Nocturne',      sub: 'Malmö · 1★' },
  { name: 'Salt & Ember',  sub: 'Göteborg' },
  { name: 'Fyra Vindar',   sub: 'Copenhagen · 2★' },
  { name: 'Råmtida',       sub: 'Uppsala · 1★' },
  { name: 'Ateljé Nord',   sub: 'Stockholm' },
  { name: 'Vänd',          sub: 'Åre' },
  { name: 'Glimma',        sub: 'Oslo · 1★' },
];
function LogoStrip({ items=DEFAULT_LOGOS, marquee=false }) {
  const renderRow = (k='') => (
    <div style={{ display:'flex', gap:64, alignItems:'center', flexShrink:0 }} key={k}>
      {items.map((l,i) => (
        <div key={i+k} style={{
          display:'flex', flexDirection:'column', alignItems:'center', whiteSpace:'nowrap',
          fontFamily:'var(--font-display)', color:'var(--site-ink-mute)',
        }}>
          <div style={{ fontSize:22, letterSpacing:'0.01em', fontStyle: i%2 ? 'italic':'normal', fontWeight: i%3===0 ? 500 : 400 }}>{l.name}</div>
          <div style={{ fontSize:9.5, letterSpacing:'0.22em', textTransform:'uppercase',
            color:'var(--site-ink-dim)', fontFamily:'var(--font-ui)', fontWeight:600, marginTop:4 }}>{l.sub}</div>
        </div>
      ))}
    </div>
  );
  if (!marquee) return <div style={{ display:'flex', justifyContent:'center', flexWrap:'wrap', gap:64, rowGap:32 }}>
    {items.map((l,i) => (
      <div key={i} style={{ display:'flex', flexDirection:'column', alignItems:'center', whiteSpace:'nowrap',
        fontFamily:'var(--font-display)', color:'var(--site-ink-mute)' }}>
        <div style={{ fontSize:22, letterSpacing:'0.01em', fontStyle: i%2 ? 'italic':'normal', fontWeight: i%3===0 ? 500 : 400 }}>{l.name}</div>
        <div style={{ fontSize:9.5, letterSpacing:'0.22em', textTransform:'uppercase',
          color:'var(--site-ink-dim)', fontFamily:'var(--font-ui)', fontWeight:600, marginTop:4 }}>{l.sub}</div>
      </div>
    ))}
  </div>;
  return (
    <div style={{ overflow:'hidden', maskImage:'linear-gradient(90deg, transparent, #000 10%, #000 90%, transparent)' }}>
      <div style={{ display:'flex', gap:64, animation:'ticker 60s linear infinite' }}>
        {renderRow('a')}{renderRow('b')}
      </div>
    </div>
  );
}

// ===========================================================================
// Product-shot frame + mini operator chrome
// ===========================================================================
function ProductShot({ path='bord.app/overview', children, chromeless, style }) {
  return (
    <div className="shot" style={style}>
      {!chromeless && <div className="shot-chrome">
        <div className="dots"><span/><span/><span/></div>
        <div style={{ flex:1, textAlign:'center' }}><span className="shot-path">{path}</span></div>
        <div style={{ width:40 }}/>
      </div>}
      {children}
    </div>
  );
}

function ShotSidebar({ active='overview', compact=false }) {
  const items = [
    { id:'overview',     icon:<Icon.home size={13}/>,     label:'Overview' },
    { id:'reservations', icon:<Icon.book size={13}/>,     label:'Reservations' },
    { id:'floor',        icon:<Icon.grid size={13}/>,     label:'Floor plan' },
    { id:'menu',         icon:<Icon.plate size={13}/>,    label:'Menu' },
    { id:'engineering',  icon:<Icon.matrix size={13}/>,   label:'Engineering' },
    { id:'wine',         icon:<Icon.wine size={13}/>,     label:'Wine list' },
    { id:'inventory',    icon:<Icon.box size={13}/>,      label:'Inventory' },
    { id:'invoices',     icon:<Icon.receipt size={13}/>,  label:'Invoices' },
    { id:'schedule',     icon:<Icon.calendar size={13}/>, label:'Schedule' },
    { id:'mise',         icon:<Icon.sparkle size={13}/>,  label:'Mise' },
  ];
  return (
    <aside style={{
      width: compact ? 56 : 184, flexShrink:0,
      background:'var(--bg-primary)', borderRight:'1px solid var(--border-subtle)',
      padding:'14px 8px', display:'flex', flexDirection:'column', gap:2,
    }}>
      <div style={{ display:'flex', alignItems:'center', gap:8, padding: compact?'8px 6px':'8px 10px', marginBottom:12 }}>
        <span style={{ width:8, height:8, background:'var(--accent-gold)', borderRadius:2, transform:'rotate(45deg)' }}/>
        {!compact && <span style={{ fontFamily:'var(--font-display)', fontSize:16 }}>Bord</span>}
      </div>
      {items.map(it => (
        <div key={it.id} style={{
          display:'flex', alignItems:'center', gap:10,
          padding: compact?'9px':'8px 10px', borderRadius:4, fontSize:12,
          background: it.id===active ? 'var(--bg-elevated)' : 'transparent',
          color: it.id===active ? 'var(--text-primary)' : 'var(--text-tertiary)',
          borderLeft: it.id===active ? '2px solid var(--accent-gold)' : '2px solid transparent',
          justifyContent: compact ? 'center' : undefined,
          fontWeight: 500,
        }}>{it.icon}{!compact && it.label}</div>
      ))}
    </aside>
  );
}

function ShotTopbar({ title, subtitle, crumbs=['Bord'], actions }) {
  return (
    <div style={{ display:'flex', alignItems:'center', gap:16, padding:'12px 18px',
      borderBottom:'1px solid var(--border-subtle)', background:'var(--bg-primary)' }}>
      <div style={{ flex:1, minWidth:0 }}>
        <div style={{ fontSize:10, color:'var(--text-tertiary)', letterSpacing:'0.08em', textTransform:'uppercase', marginBottom:2 }}>
          {crumbs.join(' · ')}
        </div>
        <div style={{ display:'flex', alignItems:'baseline', gap:10 }}>
          <div style={{ fontSize:16, fontWeight:700, color:'var(--text-primary)', letterSpacing:'-0.01em' }}>{title}</div>
          {subtitle && <div style={{ fontSize:12, color:'var(--text-tertiary)' }}>{subtitle}</div>}
        </div>
      </div>
      {actions}
    </div>
  );
}

function ShotApp({ active, title, subtitle, crumbs, actions, children, compactSidebar }) {
  return (
    <div style={{ display:'flex', height:'100%', background:'var(--bg-primary)', fontFamily:'var(--font-ui)' }}>
      <ShotSidebar active={active} compact={compactSidebar}/>
      <div style={{ flex:1, display:'flex', flexDirection:'column', minWidth:0 }}>
        <ShotTopbar title={title} subtitle={subtitle} crumbs={crumbs} actions={actions}/>
        <div style={{ flex:1, overflow:'hidden', padding:16 }}>{children}</div>
      </div>
    </div>
  );
}

// ===========================================================================
// CTA block, proof bar, pull-quote, reveal hook
// ===========================================================================
function CtaBlock({
  eyebrow='Bring Bord to your floor',
  title=<>Calm service. <em className="display-italic ink-gold">Sharper margin.</em></>,
  sub='Book a 30-minute demo. We tailor it to your covers, your floor plan, and your dishes — no slides, just your data.',
}) {
  return (
    <section className="section">
      <div className="wrap">
        <div className="keyline" style={{ padding:'56px 56px', textAlign:'center', position:'relative' }}>
          <span className="keyline-label">{eyebrow}</span>
          <h2 className="display display-lg" style={{ maxWidth:760, margin:'0 auto' }}>{title}</h2>
          <p className="lede" style={{ marginTop:24, maxWidth:560, marginInline:'auto' }}>{sub}</p>
          <div style={{ display:'flex', gap:12, justifyContent:'center', marginTop:32 }}>
            <a href="/demo" className="btn btn-primary">Request a demo</a>
            <a href="/pricing" className="btn btn-ghost">See pricing</a>
          </div>
        </div>
      </div>
    </section>
  );
}

function ProofBar({ items }) {
  return (
    <div style={{ display:'grid', gridTemplateColumns:`repeat(${items.length}, 1fr)`, gap:0,
      borderTop:'1px solid var(--site-hair)', borderBottom:'1px solid var(--site-hair)' }}>
      {items.map((it, i) => (
        <div key={i} style={{
          display:'flex', flexDirection:'column', gap:6, padding:'28px 32px',
          borderRight: i < items.length-1 ? '1px solid var(--site-hair)' : 'none',
        }}>
          <div style={{ fontFamily:'var(--font-display)', fontSize:42, lineHeight:1, letterSpacing:'-0.02em', color:'var(--site-ink)' }}>
            {it.value}
          </div>
          <div style={{ fontSize:11, letterSpacing:'0.18em', textTransform:'uppercase', color:'var(--site-ink-dim)', fontWeight:600 }}>
            {it.label}
          </div>
          {it.note && <div style={{ fontSize:12, color:'var(--site-ink-mute)', fontStyle:'italic', fontFamily:'var(--font-display)' }}>{it.note}</div>}
        </div>
      ))}
    </div>
  );
}

function Pullquote({ children, attrib }) {
  return (
    <blockquote style={{ margin:0 }}>
      <p className="pullquote">{children}</p>
      {attrib && <footer style={{
        marginTop:24, fontSize:12, letterSpacing:'0.14em', textTransform:'uppercase',
        color:'var(--site-ink-dim)', fontWeight:600,
      }}>— {attrib}</footer>}
    </blockquote>
  );
}

function CookieBanner() {
  const [open, setOpen] = useState(() => {
    try { return localStorage.getItem('bord_cookie_ack') !== '1'; } catch { return true; }
  });
  if (!open) return null;
  const dismiss = () => {
    try { localStorage.setItem('bord_cookie_ack', '1'); } catch {}
    setOpen(false);
  };
  return (
    <div role="dialog" aria-label="Cookie preferences" style={{
      position:'fixed', bottom:20, left:20, right:20, maxWidth:520,
      background:'var(--site-bg-tint)', border:'1px solid var(--site-hair-strong)',
      borderRadius:6, padding:'16px 18px', display:'flex', gap:14, alignItems:'flex-start',
      zIndex:80, boxShadow:'0 18px 40px rgba(0,0,0,0.4)', fontSize:12.5, color:'var(--site-ink-mute)',
    }}>
      <div style={{ flex:1, lineHeight:1.5 }}>
        Strictly-necessary cookies for auth and a single first-party analytics cookie.
        No third-party trackers on this site.
      </div>
      <button className="btn btn-ghost" style={{ padding:'7px 12px', fontSize:12 }} onClick={dismiss}>OK</button>
    </div>
  );
}

function useReveal() {
  useEffect(() => {
    const els = document.querySelectorAll('.reveal');
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => { if (e.isIntersecting) { e.target.classList.add('in'); io.unobserve(e.target); } });
    }, { threshold: 0.08 });
    els.forEach(el => io.observe(el));
    return () => io.disconnect();
  }, []);
}

Object.assign(window, {
  Brand, PublicNav, PublicFooter, FooterCol,
  Eyebrow, SectionHead, LogoStrip,
  ProductShot, ShotSidebar, ShotTopbar, ShotApp,
  CtaBlock, ProofBar, Pullquote, CookieBanner, useReveal,
});
