/* ============================================================
   Autobrew marketing — shared primitives
   Exported to window at bottom for cross-file use.
   ============================================================ */

/* Responsive: true when the viewport is below `bp` px. Drives the mobile
   layout branches in the sections. At >= bp the desktop layout is untouched. */
function useIsMobile(bp = 768) {
  const [m, setM] = React.useState(() => typeof window !== 'undefined' && window.innerWidth < bp);
  React.useEffect(() => {
    const mq = window.matchMedia(`(max-width: ${bp - 1}px)`);
    const f = () => setM(mq.matches);
    f();
    mq.addEventListener('change', f);
    return () => mq.removeEventListener('change', f);
  }, [bp]);
  return m;
}

/* Robust Lucide icon: React owns the wrapper <span>; the SVG inside is
   injected via ref so React never conflicts with Lucide's DOM swap. */
function Icon({ name, size = 20, stroke = 1.75, color = 'currentColor', style = {} }) {
  const ref = React.useRef(null);
  React.useLayoutEffect(() => {
    const L = window.lucide;
    if (!L || !ref.current) return;
    const key = name.replace(/(^|-)([a-z])/g, (_, __, c) => c.toUpperCase());
    const node = L.icons && (L.icons[name] || L.icons[key]);
    if (!node) { ref.current.textContent = ''; return; }
    const el = L.createElement(node);
    el.setAttribute('width', size);
    el.setAttribute('height', size);
    el.setAttribute('stroke-width', stroke);
    ref.current.replaceChildren(el);
  });
  return <span ref={ref} aria-hidden="true" style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: size, height: size, color, flex: 'none', ...style }} />;
}

function Button({ variant = 'primary', children, icon, iconRight, ...rest }) {
  return (
    <button className={`mk-btn mk-btn-${variant}`} {...rest}>
      {icon && <Icon name={icon} size={17} />}
      {children}
      {iconRight && <Icon name={iconRight} size={17} />}
    </button>
  );
}

/* The brand node-graph, rendered live. Variants tune color for light/dark. */
function NodeGraph({ width = 64, height = 68, onDark = false, glow = false }) {
  const edge = onDark ? '#F9F6EF' : '#252F3B';
  const nodes = [[290, 62], [62, 125], [62, 276], [290, 311]];
  const lines = [[0, 1], [0, 2], [0, 3], [1, 2], [1, 3], [2, 3]];
  return (
    <svg width={width} height={height} viewBox="0 0 351.8 372.8" fill="none" role="img" aria-label="autobrew">
      <g stroke={edge} strokeWidth="11" strokeLinecap="round" opacity={onDark ? 0.92 : 1}>
        {lines.map(([a, b], i) => (
          <line key={i} x1={nodes[a][0]} y1={nodes[a][1]} x2={nodes[b][0]} y2={nodes[b][1]} />
        ))}
      </g>
      <g fill="#BA5C43">
        {nodes.map(([x, y], i) => (
          <circle key={i} cx={x} cy={y} r="38" style={glow ? { filter: 'drop-shadow(0 0 10px rgba(186,92,67,.55))' } : null} />
        ))}
      </g>
    </svg>
  );
}

function Logo({ onDark = false, size = 30 }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 11 }}>
      <NodeGraph width={size} height={size * 1.06} onDark={onDark} />
      <span style={{ fontWeight: 500, fontSize: size * 0.78, letterSpacing: '-0.01em', color: onDark ? '#F4F1E9' : '#252F3B' }}>autobrew</span>
    </div>
  );
}

/* Faint decorative node-graph backdrop for dark sections. */
function GraphField({ opacity = 0.16 }) {
  const pts = [[80, 60], [240, 130], [410, 70], [560, 150], [700, 80], [860, 160], [1010, 90], [1120, 200], [160, 230], [380, 250], [620, 280], [900, 300]];
  const links = [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [0, 8], [8, 1], [1, 9], [9, 3], [3, 10], [10, 5], [6, 7], [5, 11], [2, 9]];
  return (
    <svg width="100%" height="100%" viewBox="0 0 1180 360" preserveAspectRatio="xMidYMid slice" style={{ position: 'absolute', inset: 0, pointerEvents: 'none' }}>
      <g stroke={`rgba(244,241,233,${opacity})`} strokeWidth="1.3">
        {links.map(([a, b], i) => <line key={i} x1={pts[a][0]} y1={pts[a][1]} x2={pts[b][0]} y2={pts[b][1]} />)}
      </g>
      {pts.map(([x, y], i) => (
        <circle key={i} cx={x} cy={y} r={i % 4 === 0 ? 6 : 4} fill={i % 3 === 0 ? '#BA5C43' : `rgba(244,241,233,${opacity + 0.18})`} />
      ))}
    </svg>
  );
}

function Nav() {
  const [scrolled, setScrolled] = React.useState(false);
  const [open, setOpen] = React.useState(false);
  const isMobile = useIsMobile();
  React.useEffect(() => {
    const f = () => setScrolled(window.scrollY > 10);
    window.addEventListener('scroll', f); return () => window.removeEventListener('scroll', f);
  }, []);
  React.useEffect(() => { if (!isMobile) setOpen(false); }, [isMobile]);
  const links = ['Product', 'How it works', 'Docs']; // 'Pricing' hidden until pricing section is re-enabled
  const solid = scrolled || open;
  return (
    <header style={{ position: 'sticky', top: 0, zIndex: 50, background: solid ? 'rgba(249,246,239,.92)' : 'transparent', backdropFilter: solid ? 'saturate(140%) blur(10px)' : 'none', borderBottom: solid ? '1px solid var(--ab-border)' : '1px solid transparent', transition: 'all .25s var(--ab-ease)' }}>
      <div className="mk-wrap" style={{ height: 68, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <Logo size={isMobile ? 26 : 28} />
        {isMobile ? (
          <button aria-label="Menu" aria-expanded={open} onClick={() => setOpen(o => !o)} style={{ width: 42, height: 42, borderRadius: 10, border: '1px solid var(--ab-border-strong)', background: 'var(--ab-surface)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', boxShadow: 'var(--ab-shadow-xs)' }}>
            <Icon name={open ? 'x' : 'menu'} size={20} color="var(--ab-ink-800)" />
          </button>
        ) : (
          <React.Fragment>
            <nav style={{ display: 'flex', gap: 28 }}>
              {links.map(l => (
                <a key={l} href="#" style={{ fontSize: 14.5, color: 'var(--ab-fg-2)', fontWeight: 450 }}
                  onMouseEnter={e => e.currentTarget.style.color = 'var(--ab-ink-800)'}
                  onMouseLeave={e => e.currentTarget.style.color = 'var(--ab-fg-2)'}>{l}</a>
              ))}
            </nav>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              <a href="#" style={{ fontSize: 14.5, color: 'var(--ab-fg-2)', fontWeight: 450 }}>Sign in</a>
              <Button variant="primary" iconRight="arrow-right" style={{ padding: '9px 16px', fontSize: 14 }}>Connect a repo</Button>
            </div>
          </React.Fragment>
        )}
      </div>
      {isMobile && open && (
        <div style={{ borderTop: '1px solid var(--ab-border)', background: 'rgba(249,246,239,.98)', backdropFilter: 'blur(10px)', padding: '14px 20px 22px', animation: 'mk-menu-in .18s var(--ab-ease)' }}>
          <nav style={{ display: 'flex', flexDirection: 'column' }}>
            {links.map(l => (
              <a key={l} href="#" onClick={() => setOpen(false)} style={{ fontSize: 16, color: 'var(--ab-ink-800)', fontWeight: 500, padding: '13px 4px', borderBottom: '1px solid var(--ab-border)' }}>{l}</a>
            ))}
          </nav>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginTop: 16 }}>
            <Button variant="primary" iconRight="arrow-right" style={{ width: '100%', justifyContent: 'center', padding: '12px 16px' }}>Connect a repo</Button>
            <Button variant="secondary" style={{ width: '100%', justifyContent: 'center', padding: '12px 16px' }}>Sign in</Button>
          </div>
        </div>
      )}
    </header>
  );
}

function Footer() {
  const cols = [
    ['Product', ['Knowledge Graph', 'Readiness Report', 'Coordinated Changes', 'Component Catalog']],
    ['Company', ['About', 'Careers', 'Security', 'Status']],
    ['Resources', ['Docs', 'Changelog', 'Contact']], // 'Pricing' hidden until pricing section is re-enabled
  ];
  return (
    <footer style={{ background: 'var(--ab-ink-panel)', color: 'var(--ab-fg-on-dark-2)', position: 'relative', overflow: 'hidden' }}>
      <div style={{ position: 'absolute', inset: 0, opacity: .5 }}><GraphField opacity={0.08} /></div>
      <div className="mk-wrap mk-footer" style={{ padding: '72px 32px 40px', position: 'relative' }}>
        <div className="mk-footer-grid" style={{ display: 'grid', gridTemplateColumns: '1.6fr 1fr 1fr 1fr', gap: 40 }}>
          <div>
            <Logo onDark size={28} />
            <p style={{ maxWidth: 280, marginTop: 18, fontSize: 14, lineHeight: 1.6 }}>The production backbone for the AI era of software. Bring us any codebase — we make it production-ready and keep it that way.</p>
          </div>
          {cols.map(([h, items]) => (
            <div key={h}>
              <div style={{ fontFamily: 'var(--ab-font-mono)', fontSize: 11, letterSpacing: '.14em', textTransform: 'uppercase', color: 'var(--ab-fg-on-dark)', opacity: .55, marginBottom: 14 }}>{h}</div>
              <ul style={{ listStyle: 'none', margin: 0, padding: 0, display: 'flex', flexDirection: 'column', gap: 11 }}>
                {items.map(i => <li key={i}><a href="#" style={{ fontSize: 14 }}>{i}</a></li>)}
              </ul>
            </div>
          ))}
        </div>
        <div className="mk-footer-legal" style={{ marginTop: 56, paddingTop: 22, borderTop: '1px solid var(--ab-border-dark)', display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 16, flexWrap: 'wrap', fontSize: 13 }}>
          <span style={{ fontFamily: 'var(--ab-font-mono)' }}>© 2026 autobrew</span>
          <span style={{ display: 'flex', gap: 22 }}><a href="#">Privacy</a><a href="#">Terms</a><a href="#">SOC 2</a></span>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { Icon, Button, NodeGraph, Logo, GraphField, Nav, Footer, useIsMobile });
