// Shared components: Nav, Footer, Logo, Pill, Marquee, etc.
const { useState, useEffect, useRef, useMemo, useCallback } = React;

/* -------------- routing helpers -------------- */
const ROUTES = {
  '': 'landing',
  'home': 'landing',
  'product': 'landing',
  'dashboard': 'dashboard',
  'pricing': 'pricing',
  'about': 'about',
  'login': 'auth',
  'signup': 'auth',
  '404': 'notfound',
};

function useRoute() {
  const parse = () => {
    const h = (window.location.hash || '#').replace(/^#\/?/, '').split('?')[0];
    return ROUTES[h] !== undefined ? { name: ROUTES[h], slug: h } : { name: 'notfound', slug: h };
  };
  const [route, setRoute] = useState(parse);
  useEffect(() => {
    const onHash = () => {
      setRoute(parse());
      window.scrollTo({ top: 0, behavior: 'instant' });
    };
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);
  return route;
}

function go(slug) {
  if (window.location.hash !== '#/' + slug) {
    window.location.hash = '#/' + slug;
  } else {
    window.scrollTo({ top: 0, behavior: 'smooth' });
  }
}

/* -------------- logo -------------- */
function Logo({ size = 22 }) {
  return (
    <span className="brand">
      <span className="brand-mark" style={{ width: size, height: size }} aria-hidden></span>
      <span>Lot Copilot</span>
    </span>
  );
}

/* -------------- theme toggle (sun / moon) -------------- */
function ThemeToggle({ theme, onToggle }) {
  const isDark = theme === 'dark';
  const label = isDark ? 'Switch to day theme' : 'Switch to night theme';
  return (
    <button
      type="button"
      className="theme-toggle"
      aria-label={label}
      title={label}
      onClick={onToggle}
    >
      {isDark ? (
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
          <circle cx="12" cy="12" r="4" />
          <path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41" />
        </svg>
      ) : (
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
          <path d="M21 12.79A9 9 0 1 1 11.21 3a7 7 0 0 0 9.79 9.79z" />
        </svg>
      )}
    </button>
  );
}

/* -------------- nav -------------- */
function Nav({ active, theme, onToggleTheme }) {
  const items = [
    { slug: 'product', label: 'Product', match: 'landing' },
    { slug: 'dashboard', label: 'Dashboard', match: 'dashboard' },
    { slug: 'pricing', label: 'Pricing', match: 'pricing' },
    { slug: 'about', label: 'About', match: 'about' },
  ];
  return (
    <nav className="nav">
      <div className="container nav-inner">
        <a href="#/" onClick={(e) => { e.preventDefault(); go(''); }}><Logo /></a>
        <div className="nav-links">
          {items.map(it => (
            <a key={it.slug}
               href={'#/' + it.slug}
               className={active === it.match ? 'is-active' : ''}
               onClick={(e) => { e.preventDefault(); go(it.slug); }}>
              {it.label}
            </a>
          ))}
        </div>
        <div className="nav-actions">
          <ThemeToggle theme={theme} onToggle={onToggleTheme} />
          <button className="btn btn--ghost btn--sm" onClick={() => go('login')}>Sign in</button>
          <button className="btn btn--sm" onClick={() => go('signup')}>Start trial</button>
        </div>
      </div>
    </nav>
  );
}

/* -------------- footer -------------- */
function Footer() {
  const todayISO = new Date().toISOString().slice(0, 10);
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer-grid">
          <div>
            <Logo />
            <p style={{ fontSize: 13, color: 'var(--ink-2)', maxWidth: 320, marginTop: 16 }}>
              All-in-one compliance for independent used-car dealerships.
              Five minutes to set up, every regulator handled.
            </p>
            <div style={{ display: 'flex', gap: 8, marginTop: 18 }}>
              <button className="btn btn--sm" onClick={() => go('signup')}>Start 14-day trial</button>
            </div>
          </div>
          <div>
            <h5>Product</h5>
            <ul>
              <li><a href="#/product" onClick={(e)=>{e.preventDefault();go('product');}}>Overview</a></li>
              <li><a href="#/dashboard" onClick={(e)=>{e.preventDefault();go('dashboard');}}>Dashboard</a></li>
              <li><a href="#/pricing" onClick={(e)=>{e.preventDefault();go('pricing');}}>Pricing</a></li>
              <li><a href="#/404" onClick={(e)=>{e.preventDefault();go('changelog');}}>Changelog</a></li>
            </ul>
          </div>
          <div>
            <h5>Compliance</h5>
            <ul>
              <li><a href="#/404" onClick={(e)=>{e.preventDefault();go('ftc');}}>FTC Safeguards</a></li>
              <li><a href="#/404" onClick={(e)=>{e.preventDefault();go('cars-act');}}>California CARS Act</a></li>
              <li><a href="#/404" onClick={(e)=>{e.preventDefault();go('google');}}>Google VLA Policy</a></li>
              <li><a href="#/404" onClick={(e)=>{e.preventDefault();go('wisp');}}>WISP template</a></li>
            </ul>
          </div>
          <div>
            <h5>Company</h5>
            <ul>
              <li><a href="#/about" onClick={(e)=>{e.preventDefault();go('about');}}>About</a></li>
              <li><a href="#/404" onClick={(e)=>{e.preventDefault();go('careers');}}>Careers</a></li>
              <li><a href="#/404" onClick={(e)=>{e.preventDefault();go('press');}}>Press kit</a></li>
              <li><a href="mailto:hello@lotcopilot.com">hello@lotcopilot.com</a></li>
            </ul>
          </div>
        </div>
        <div className="footer-bottom">
          <span>© 2026 LOT COPILOT, INC. — DEL.</span>
          <span>NOT LEGAL ADVICE. CONSULT YOUR ATTORNEY.</span>
          <span>BUILD 2026.05.06 · {todayISO}</span>
        </div>
      </div>
    </footer>
  );
}

/* -------------- status pill -------------- */
function StatusPill({ kind = 'ok', children }) {
  const dotCls = kind === 'ok' ? 'dot--ok' : kind === 'warn' ? 'dot--warn' : kind === 'alert' ? 'dot--alert' : '';
  return (
    <span className="pill">
      <span className={'dot ' + dotCls}></span>
      {children}
    </span>
  );
}

/* -------------- marquee ticker -------------- */
function Marquee({ items, speed = 60 }) {
  // duplicate for seamless loop
  const dur = `${items.length * speed / 4}s`;
  return (
    <div style={{ overflow: 'hidden', borderTop: '1px solid var(--rule)', borderBottom: '1px solid var(--rule)', background: 'var(--paper-2)' }}>
      <div style={{
        display: 'flex',
        gap: 56,
        padding: '12px 0',
        whiteSpace: 'nowrap',
        animation: `scrollX ${dur} linear infinite`,
        width: 'max-content',
      }}>
        {[...items, ...items, ...items].map((it, i) => (
          <span key={i} className="mono" style={{ fontSize: 12, color: 'var(--ink-2)', letterSpacing: '0.04em' }}>
            {it}
          </span>
        ))}
      </div>
    </div>
  );
}

/* -------------- section header used across pages -------------- */
function SectionLabel({ kana, title, sub, no }) {
  return (
    <div className="m-section-label" style={{
      display: 'grid',
      gridTemplateColumns: '120px 1fr',
      gap: 32,
      borderTop: '1px solid var(--rule-strong)',
      paddingTop: 14,
      marginBottom: 36,
    }}>
      <div className="mono" style={{ fontSize: 11, letterSpacing: '0.08em', color: 'var(--ink-3)', textTransform: 'uppercase' }}>
        {no || '§'}
      </div>
      <div>
        <div className="label" style={{ marginBottom: 14 }}>{kana}</div>
        <h2 className="h-section" style={{ maxWidth: 900 }}>{title}</h2>
        {sub && <p className="lede" style={{ marginTop: 18, maxWidth: 760 }}>{sub}</p>}
      </div>
    </div>
  );
}

/* -------------- regulator block (re-used) -------------- */
function RegulatorRow({ no, abbr, name, deadline, fine, status, lede, items }) {
  return (
    <div className="m-regulator-row" style={{
      display: 'grid',
      gridTemplateColumns: '60px 1.2fr 2fr 1fr',
      gap: 24,
      padding: '28px 0',
      borderTop: '1px solid var(--rule)',
      alignItems: 'start',
    }}>
      <div className="mono" style={{ fontSize: 11, color: 'var(--ink-3)' }}>{no}</div>
      <div>
        <div className="display" style={{ fontSize: 36, lineHeight: 1, letterSpacing: '-0.03em' }}>{abbr}</div>
        <div style={{ fontSize: 13, color: 'var(--ink-2)', marginTop: 6 }}>{name}</div>
      </div>
      <div>
        <p style={{ margin: 0, fontSize: 14, color: 'var(--ink-2)', maxWidth: 540 }}>{lede}</p>
        {items && (
          <ul className="mono" style={{ margin: '12px 0 0', padding: 0, listStyle: 'none', fontSize: 11, color: 'var(--ink-3)', display: 'grid', gap: 4, letterSpacing: '0.02em' }}>
            {items.map((it, i) => <li key={i}>— {it}</li>)}
          </ul>
        )}
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8, alignItems: 'flex-start' }}>
        <StatusPill kind={status === 'live' ? 'alert' : status === 'soon' ? 'warn' : 'ok'}>
          {status === 'live' ? 'In effect' : status === 'soon' ? 'Imminent' : 'Watching'}
        </StatusPill>
        <div className="mono" style={{ fontSize: 11, color: 'var(--ink-3)' }}>{deadline}</div>
        {fine && <div className="display tnum" style={{ fontSize: 22, color: 'var(--ink)' }}>{fine}</div>}
      </div>
    </div>
  );
}

/* expose globally for other Babel scripts */
Object.assign(window, {
  useRoute, go,
  Logo, Nav, Footer,
  StatusPill, Marquee, SectionLabel, RegulatorRow,
});
