// CHROME - shared across pages.
// Tokens · Context · Primitives (EdLogo / EdTag / EdBtn / EdSectionHead)
// EdNav (with active-page highlight) · EdFooter · EdChrome wrapper.
// Pages import these by reading window.* after this script loads.

const ED_BASE = {
  bg: '#FFFFFF',
  bgWarm: '#F8F7F3',
  bgAlt: '#ECE9E1',
  ink: '#37474F',       // brand Deep Grey
  ink2: '#5C6770',
  ink3: '#8A949B',
  rule: '#D9DCE0',
  ruleSoft: '#E6E8EB',
  red: '#EE4B46',     // brand Red - fixed (independent of `accent` tweak)
  accent: '#EE4B46',    // brand Red
  teal: '#00A4B4',
  yellow: '#F9AB00',
  green: '#69CD64',
  inverse: '#FFFFFF',
};

const EdCtx = React.createContext(null);

const FONT_STACKS = {
  sans: {
    display: '"Sofia Pro", "Mulish", -apple-system, BlinkMacSystemFont, sans-serif',
    body:    '"Sofia Pro", "Mulish", -apple-system, BlinkMacSystemFont, sans-serif',
  },
  serif: {
    display: '"Instrument Serif", "Newsreader", Georgia, serif',
    body:    '"Geist", "Sofia Pro", -apple-system, BlinkMacSystemFont, sans-serif',
  },
};

function makeEdText(fontMode) {
  const f = FONT_STACKS[fontMode] || FONT_STACKS.sans;
  const isSerif = fontMode === 'serif';
  return {
    display:     { fontFamily: f.display, fontWeight: isSerif ? 400 : 300, letterSpacing: '-0.035em' },
    displayBold: { fontFamily: f.display, fontWeight: isSerif ? 400 : 700, letterSpacing: '-0.035em', fontStyle: 'italic' },
    sans:        { fontFamily: f.body, fontWeight: 400 },
    med:         { fontFamily: f.body, fontWeight: 500 },
    bold:        { fontFamily: f.body, fontWeight: 700 },
    tag:         { fontFamily: f.body, fontWeight: 500, letterSpacing: '0.18em', textTransform: 'uppercase', fontSize: 18 },
  };
}

// ─── responsive ─────────────────────────────────────────────────
// Single mobile breakpoint at 768px. Components opt in via useIsMobile().
// Optional override: setMobilePreview(width) lets you simulate a phone
// viewport on desktop. useIsMobile() returns true whenever the override
// is set, regardless of real viewport width.

const MOBILE_PREVIEW_DEFAULT = 390;

if (typeof window !== 'undefined' && !window.__OutrunPreview) {
  const listeners = new Set();
  window.__OutrunPreview = {
    width: 0, // 0 means off
    subscribe(fn) { listeners.add(fn); return () => listeners.delete(fn); },
    set(w) {
      const next = w ? (typeof w === 'number' ? w : MOBILE_PREVIEW_DEFAULT) : 0;
      if (next === this.width) return;
      this.width = next;
      listeners.forEach(fn => fn(next));
    },
  };
}

function useMobilePreview() {
  const [w, setW] = React.useState(() => (typeof window !== 'undefined' ? window.__OutrunPreview.width : 0));
  React.useEffect(() => {
    if (typeof window === 'undefined') return;
    return window.__OutrunPreview.subscribe(setW);
  }, []);
  return w; // 0 = off, otherwise pixel width
}

function useIsMobile(breakpoint = 768) {
  const query = `(max-width: ${breakpoint - 1}px)`;
  const previewWidth = useMobilePreview();
  const [isMobile, setIsMobile] = React.useState(() => {
    if (typeof window === 'undefined' || !window.matchMedia) return false;
    return window.matchMedia(query).matches;
  });
  React.useEffect(() => {
    if (!window.matchMedia) return;
    const mq = window.matchMedia(query);
    const handler = (e) => setIsMobile(e.matches);
    mq.addEventListener ? mq.addEventListener('change', handler) : mq.addListener(handler);
    return () => {
      mq.removeEventListener ? mq.removeEventListener('change', handler) : mq.removeListener(handler);
    };
  }, [query]);
  return previewWidth > 0 ? previewWidth < breakpoint : isMobile;
}

// ─── primitives ─────────────────────────────────────────────────

function EdLogo({ size = 22, variant = 'positive' }) {
  // Logo aspect ratio is ~3.57:1 (2400×672). `size` is the rendered HEIGHT in px.
  // variant: 'positive' (dark wordmark, on light bg)
  //        | 'negative' (white wordmark + brand-coloured mark, on dark bg)
  //        | 'white'    (all white, for use over imagery / when restraint matters)
  const R = (typeof window !== 'undefined' && window.__resources) || {};
  const src = variant === 'negative'
    ? (R.logoNegative || 'assets/outrun-logo-negative.png')
    : variant === 'white'
      ? (R.logoWhite || 'assets/outrun-logo-white.png')
      : (R.logoPositive || 'assets/outrun-logo.png');
  return (
    <img
      src={src}
      alt="Outrun"
      style={{ height: size, width: 'auto', display: 'block' }}
    />
  );
}

function EdTag({ children, num, color, dot }) {
  const ED = React.useContext(EdCtx);
  const edText = ED.text;
  return (
    <div style={{ display: 'inline-flex', alignItems: 'center', gap: 12, ...edText.tag, color: color || ED.ink2, whiteSpace: 'nowrap' }}>
      {dot && <span style={{ width: 6, height: 6, borderRadius: 999, background: ED.accent, display: 'inline-block' }} />}
      {num && <span style={{ color: ED.accent }}>§ {num}</span>}
      {num && <span style={{ width: 20, height: 1, background: 'currentColor', opacity: 0.4 }} />}
      <span>{children}</span>
    </div>
  );
}

function EdBtn({ children, kind = 'primary', href, target, arrow = true }) {
  const ED = React.useContext(EdCtx);
  const edText = ED.text;
  const isMobile = useIsMobile();
  const [hover, setHover] = React.useState(false);
  const variants = {
    primary:  { bg: ED.ink, fg: ED.inverse, border: ED.ink, hoverBg: '#1a1813', hoverFg: ED.inverse },
    accent:   { bg: ED.accent, fg: ED.inverse, border: ED.accent, hoverBg: ED.ink, hoverFg: ED.inverse },
    ghost:    { bg: 'transparent', fg: ED.ink, border: ED.ink, hoverBg: ED.ink, hoverFg: ED.inverse },
    ghostInv: { bg: 'transparent', fg: ED.inverse, border: 'rgba(255,255,255,0.5)', hoverBg: ED.inverse, hoverFg: ED.ink },
  };
  const v = variants[kind];
  return (
    <a
      href={href}
      target={target}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        ...edText.med,
        fontSize: isMobile ? 14 : 15,
        letterSpacing: '-0.005em',
        padding: isMobile ? '12px 18px' : '14px 22px',
        borderRadius: 2,
        textDecoration: 'none',
        display: 'inline-flex',
        alignItems: 'center',
        gap: 10,
        whiteSpace: 'nowrap',
        cursor: 'pointer',
        background: hover ? v.hoverBg : v.bg,
        color: hover ? v.hoverFg : v.fg,
        border: `1px solid ${v.border}`,
        transition: 'background 160ms ease, color 160ms ease, border-color 160ms ease',
      }}
    >
      <span>{children}</span>
      {arrow && (
        <span style={{
          display: 'inline-block',
          transform: hover ? 'translateX(3px)' : 'translateX(0)',
          transition: 'transform 220ms cubic-bezier(0.4, 0, 0.2, 1)',
          fontSize: 15,
          lineHeight: 1,
        }}>→</span>
      )}
    </a>
  );
}

function EdSectionHead({ num, kicker, title, subtitle, inverse }) {
  const ED = React.useContext(EdCtx);
  const edText = ED.text;
  const isMobile = useIsMobile();
  const ink = inverse ? ED.inverse : ED.ink;
  const ink2 = inverse ? 'rgba(255,255,255,0.7)' : ED.ink2;
  return (
    <div style={{ marginBottom: isMobile ? 36 : 56 }}>
      {(num || kicker) && <EdTag num={num} color={ink2}>{kicker}</EdTag>}
      <h2 style={{ ...edText.display, fontSize: isMobile ? 'clamp(34px, 9.5vw, 38px)' : 88, lineHeight: isMobile ? 1.02 : 0.95, margin: (num || kicker) ? (isMobile ? '16px 0 0' : '24px 0 0') : 0, color: ink, letterSpacing: '-0.035em', maxWidth: 1100 }}>{title}</h2>
      {subtitle && <p style={{ ...edText.sans, fontSize: isMobile ? 18 : 18, color: ink2, lineHeight: 1.55, marginTop: isMobile ? 18 : 24, maxWidth: 740 }}>{subtitle}</p>}
    </div>
  );
}

// ─── nav ────────────────────────────────────────────────────────

// NAV_ITEMS - top-level. Each item routes to its primary destination.
// Children appear in the hover dropdown.
// `href` of '' means stub (not yet built) - these render as cursor: default
// and don't navigate, so we don't surface dead links.
const NAV_ITEMS = [
  { label: 'For MGAs',    href: '/da-platform',
    match: ['/da-platform', '/mga-pas-plus'],
    children: [
      { label: 'DA Platform', href: '/da-platform' },
      { label: 'MGA PAS+',    href: '/mga-pas-plus' },
    ],
  },
  { label: 'For Brokers', href: '/schemes-platform',
    match: ['/schemes-platform', '/broker-pas-plus'],
    children: [
      { label: 'Schemes Platform', href: '/schemes-platform' },
      { label: 'Broker PAS+',      href: '/broker-pas-plus' },
    ],
  },
  { label: 'Company',     href: '/about',
    match: ['/about', '/team'],
    children: [
      { label: 'About Us',      href: '/about' },
      { label: 'Meet The Team', href: '/team' },
    ],
  },
];

function EdNavChild({ child, ED, edText }) {
  const [hovered, setHovered] = React.useState(false);
  const interactive = !!child.href;
  return (
    <a href={child.href || undefined}
       onMouseEnter={() => setHovered(true)}
       onMouseLeave={() => setHovered(false)}
       style={{
         ...edText.sans,
         display: 'block',
         position: 'relative',
         padding: '10px 24px 10px 28px',
         fontSize: 15,
         color: interactive && hovered ? ED.accent : (interactive ? ED.ink : ED.ink3),
         textDecoration: 'none',
         letterSpacing: '-0.005em',
         cursor: interactive ? 'pointer' : 'default',
         transition: 'color 120ms ease',
       }}>
      {interactive && hovered && (
        <span aria-hidden="true" style={{ position: 'absolute', left: 12, top: 8, bottom: 8, width: 3, background: ED.accent }} />
      )}
      {child.label}
    </a>
  );
}

function EdNav({ current }) {
  const ED = React.useContext(EdCtx);
  const edText = ED.text;
  const isMobile = useIsMobile();
  const [openIdx, setOpenIdx] = React.useState(null);
  const [hoverIdx, setHoverIdx] = React.useState(null);
  const [mobileOpen, setMobileOpen] = React.useState(false);

  // ── Mobile nav: hamburger + drawer ──
  if (isMobile) {
    return (
      <>
        <nav style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '12px 20px', borderBottom: `1px solid ${ED.rule}`, background: ED.bg, position: 'sticky', top: 0, zIndex: 30 }}>
          <a href="/" style={{ display: 'block', textDecoration: 'none' }}>
            <EdLogo size={44} />
          </a>
          <button
            aria-label={mobileOpen ? 'Close menu' : 'Open menu'}
            onClick={() => setMobileOpen(o => !o)}
            style={{
              background: 'transparent', border: 'none', cursor: 'pointer',
              padding: 8, display: 'flex', flexDirection: 'column', gap: 5,
            }}
          >
            <span style={{ width: 24, height: 1.5, background: ED.ink, transition: 'transform 200ms ease, opacity 200ms ease', transform: mobileOpen ? 'translateY(6.5px) rotate(45deg)' : 'none' }} />
            <span style={{ width: 24, height: 1.5, background: ED.ink, transition: 'opacity 150ms ease', opacity: mobileOpen ? 0 : 1 }} />
            <span style={{ width: 24, height: 1.5, background: ED.ink, transition: 'transform 200ms ease', transform: mobileOpen ? 'translateY(-6.5px) rotate(-45deg)' : 'none' }} />
          </button>
        </nav>
        {mobileOpen && (
          <div style={{
            position: 'fixed', top: 68, left: 0, right: 0, bottom: 0,
            background: ED.bg, zIndex: 25, overflowY: 'auto',
            padding: '24px 20px 40px',
            borderTop: `1px solid ${ED.rule}`,
          }}>
            <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column' }}>
              {NAV_ITEMS.map((it) => {
                const isActive = (it.match || (it.href ? [it.href] : [])).includes(current);
                return (
                  <li key={it.label} style={{ borderBottom: `1px solid ${ED.ruleSoft}`, padding: '14px 0' }}>
                    <a href={it.href || undefined}
                       onClick={() => setMobileOpen(false)}
                       style={{ ...edText.display, fontSize: 28, color: isActive ? ED.accent : ED.ink, textDecoration: 'none', display: 'block', letterSpacing: '-0.02em' }}>
                      {it.label}
                    </a>
                    {it.children && (
                      <ul style={{ listStyle: 'none', padding: '8px 0 4px 16px', margin: 0, display: 'flex', flexDirection: 'column', gap: 8 }}>
                        {it.children.map(c => (
                          <li key={c.label}>
                            <a href={c.href || undefined}
                               onClick={() => setMobileOpen(false)}
                               style={{ ...edText.sans, fontSize: 15, color: ED.ink2, textDecoration: 'none', display: 'block', letterSpacing: '-0.005em' }}>
                              {c.label}
                            </a>
                          </li>
                        ))}
                      </ul>
                    )}
                  </li>
                );
              })}
            </ul>
            <a href="/demo" onClick={() => setMobileOpen(false)} style={{ ...edText.med, fontSize: 16, background: ED.ink, color: ED.inverse, padding: '14px 22px', borderRadius: 2, textDecoration: 'none', display: 'inline-flex', alignItems: 'center', gap: 8, marginTop: 28 }}>
              Book a demo
              <span>→</span>
            </a>
          </div>
        )}
      </>
    );
  }

  const link = { ...edText.sans, fontSize: 14, textDecoration: 'none', display: 'inline-flex', alignItems: 'center', gap: 6, padding: '8px 0', transition: 'color 120ms ease' };
  const caret = { fontSize: 9, color: ED.ink3, transition: 'transform 120ms ease', marginTop: 1 };

  return (
    <nav style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '14px 144px', borderBottom: `1px solid ${ED.rule}`, background: ED.bg, position: 'sticky', top: 0, zIndex: 10 }}>
      <a href="/" style={{ display: 'block', textDecoration: 'none' }}>
        <EdLogo size={68} />
      </a>
      <div style={{ display: 'flex', alignItems: 'center', gap: 36 }}>
        {NAV_ITEMS.map((it, i) => {
          const hasChildren = !!it.children;
          const isOpen = openIdx === i;
          const isStub = !it.href;
          const isActive = (it.match || (it.href ? [it.href] : [])).includes(current);
          const baseColor = isActive ? ED.accent : (isStub ? ED.ink3 : ED.ink);
          return (
            <div key={it.label}
                 style={{ position: 'relative' }}
                 onMouseEnter={() => { setHoverIdx(i); if (hasChildren) setOpenIdx(i); }}
                 onMouseLeave={() => {
                   setHoverIdx(prev => prev === i ? null : prev);
                   setOpenIdx(prev => prev === i ? null : prev);
                 }}>
              <a href={it.href || undefined}
                 style={{ ...link, color: (isOpen || hoverIdx === i || isActive) && !isStub ? ED.accent : baseColor, cursor: isStub && !hasChildren ? 'default' : 'pointer' }}>
                {it.label}
                {hasChildren && (
                  <span style={{ ...caret, transform: isOpen ? 'rotate(180deg)' : 'rotate(0deg)' }}>▾</span>
                )}
              </a>
              {hasChildren && isOpen && (
                <div style={{
                  position: 'absolute',
                  top: '100%',
                  left: -24,
                  minWidth: 240,
                  background: ED.bg,
                  border: `1px solid ${ED.rule}`,
                  borderTop: `2px solid ${ED.accent}`,
                  padding: '14px 0 16px',
                  boxShadow: '0 12px 32px rgba(55, 71, 79, 0.08)',
                  zIndex: 20,
                }}>
                  <div style={{ ...edText.tag, color: ED.ink3, fontSize: 10, padding: '0 24px 12px', borderBottom: `1px solid ${ED.ruleSoft}`, marginBottom: 8 }}>
                    {it.label}
                  </div>
                  {it.children.map(child => (
                    <EdNavChild key={child.label} child={child} ED={ED} edText={edText} />
                  ))}
                </div>
              )}
            </div>
          );
        })}
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
        <a href="/demo" style={{ ...edText.med, fontSize: 14, background: ED.ink, color: ED.inverse, padding: '10px 18px', borderRadius: 2, textDecoration: 'none', display: 'inline-flex', alignItems: 'center', gap: 6, whiteSpace: 'nowrap' }}>
          Book a demo
          <span>→</span>
        </a>
      </div>
    </nav>
  );
}

// ─── footer ────────────────────────────────────────────────────

function EdFooter() {
  const ED = React.useContext(EdCtx);
  const edText = ED.text;
  const isMobile = useIsMobile();
  const inv = '#FFFFFF';
  const cols = [
    ['For MGAs',    [{ label: 'DA Platform', href: '/da-platform' }, { label: 'MGA PAS+', href: '/mga-pas-plus' }]],
    ['For Brokers', [{ label: 'Schemes Platform', href: '/schemes-platform' }, { label: 'Broker PAS+', href: '/broker-pas-plus' }]],
    ['Company',     [{ label: 'About Us', href: '/about' }, { label: 'Meet The Team', href: '/team' }]],
    ['Contact',     [{ label: 'Get in touch', href: '/contact' }, { label: 'Book a demo', href: '/demo' }]],
  ];
  return (
    <footer style={{ padding: isMobile ? '48px 24px 32px' : '64px 144px 40px', background: ED.ink, color: inv }}>
      <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1.6fr 1fr 1fr 1fr 1fr', gap: isMobile ? 36 : 48 }}>
        <div>
          <a href="/" style={{ display: 'block', textDecoration: 'none' }}>
            <EdLogo size={28} variant="negative" />
          </a>
          <p style={{ ...edText.sans, fontSize: isMobile ? 17 : 16, color: 'rgba(255,255,255,0.7)', marginTop: 18, lineHeight: 1.5, maxWidth: 320 }}>
            The DA &amp; Schemes Platform for UK MGAs and Schemes Brokers.
          </p>
        </div>
        {cols.map(([t, items]) => (
          <div key={t}>
            <div style={{ ...edText.tag, color: 'rgba(255,255,255,0.5)', marginBottom: 14, fontSize: 10 }}>{t.toUpperCase()}</div>
            <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 10 }}>
              {items.map(i => (
                <li key={i.label}>
                  <a href={i.href || undefined}
                     style={{ ...edText.sans, fontSize: 15, color: 'rgba(255,255,255,0.85)', textDecoration: 'none', cursor: i.href ? 'pointer' : 'default' }}>
                    {i.label}
                  </a>
                </li>
              ))}
            </ul>
          </div>
        ))}
      </div>
      <div style={{ marginTop: isMobile ? 40 : 56, paddingTop: 22, borderTop: '1px solid rgba(255,255,255,0.15)', display: 'flex', justifyContent: 'space-between', ...edText.tag, color: 'rgba(255,255,255,0.5)', fontSize: 11 }}>
        <span style={{ textTransform: 'none', letterSpacing: '0.04em' }}>© 2026 Exponential Systems Ltd, trading as Outrun</span>
      </div>
    </footer>
  );
}

// ─── chrome wrapper ────────────────────────────────────────────

function EdChrome({ accent, fontMode = 'serif', current, children }) {
  const tokens = React.useMemo(() => ({
    ...ED_BASE,
    accent: accent || ED_BASE.accent,
    text: makeEdText(fontMode),
    fontMode,
  }), [accent, fontMode]);
  const isMobile = useIsMobile();
  const previewWidth = useMobilePreview();
  const inner = (
    <EdCtx.Provider value={tokens}>
      <div style={{ background: tokens.bg, color: tokens.ink, fontFamily: FONT_STACKS[fontMode].body, width: '100%', minHeight: '100%', minWidth: (isMobile || previewWidth) ? undefined : 1280 }}>
        <EdNav current={current} />
        <div style={(isMobile || previewWidth) ? undefined : { zoom: 0.9 }}>
          {children}
        </div>
        <EdFooter />
      </div>
    </EdCtx.Provider>
  );
  if (!previewWidth) return inner;
  // Mobile preview frame - constrains width so isMobile branches render.
  return (
    <div style={{ minHeight: '100vh', background: '#1a1813', padding: '24px 16px 48px', display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
      <div style={{ ...edText_preview(), color: 'rgba(255,255,255,0.7)', marginBottom: 14, fontSize: 12, letterSpacing: '0.14em', textTransform: 'uppercase' }}>
        Mobile preview · {previewWidth}px
      </div>
      <div style={{ width: previewWidth, maxWidth: '100%', background: tokens.bg, boxShadow: '0 24px 64px rgba(0,0,0,0.4)', borderRadius: 22, overflow: 'hidden' }}>
        {inner}
      </div>
    </div>
  );
}

function edText_preview() {
  return { fontFamily: '"Geist", -apple-system, sans-serif', fontWeight: 500 };
}

Object.assign(window, {
  ED_BASE, EdCtx, FONT_STACKS, makeEdText,
  useIsMobile, useMobilePreview,
  EdLogo, EdTag, EdBtn, EdSectionHead,
  EdNav, EdFooter, EdChrome,
});

// ─── dev-preview link shim ─────────────────────────────────────
// Clean URLs (/about, /da-platform) work in production because the Azure
// Static Web Apps config rewrites them to /*.html. Dev/preview servers
// don't apply that config, so links 404. This shim only activates off-host
// and rewrites clean internal hrefs to their .html equivalents at click time.

if (typeof window !== 'undefined' && !window.__outrunLinkShimInstalled) {
  const host = window.location.hostname;
  const isProd = host.endsWith('azurestaticapps.net') ||
                 host.endsWith('outrun.insure') ||
                 host === 'outrun.insure';
  if (!isProd) {
    window.__outrunLinkShimInstalled = true;
    document.addEventListener('click', (e) => {
      const a = e.target.closest && e.target.closest('a[href]');
      if (!a) return;
      const href = a.getAttribute('href');
      if (!href || !href.startsWith('/')) return;
      // skip if already has an extension, hash, or query string
      if (/\.[a-z0-9]+(\?|#|$)/i.test(href) || href.includes('#') || href.includes('?')) return;
      e.preventDefault();
      window.location.href = href === '/' ? '/index.html' : href.replace(/\/$/, '') + '.html';
    }, true);
  }
}
