// Shared components — nav, footer, primitives, tweaks panel, defect card
const { useState, useEffect, useRef, createContext, useContext } = React;

// ---------- Router context (simple hash-based) ----------
const RouterCtx = createContext({ path: '/', go: () => {} });
const useRouter = () => useContext(RouterCtx);

function RouterProvider({ children }) {
  const [path, setPath] = useState(() => {
    const h = window.location.hash.replace(/^#/, '');
    return h || '/';
  });
  useEffect(() => {
    const onHash = () => {
      const h = window.location.hash.replace(/^#/, '') || '/';
      setPath(h);
      window.scrollTo({ top: 0, behavior: 'instant' });
    };
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);
  const go = (p) => { window.location.hash = p; };
  return <RouterCtx.Provider value={{ path, go }}>{children}</RouterCtx.Provider>;
}

function Link({ to, children, className, style, onClick }) {
  const { go, path } = useRouter();
  const active = path === to;
  return (
    <a
      href={`#${to}`}
      className={className}
      data-active={active}
      style={style}
      onClick={(e) => {
        e.preventDefault();
        go(to);
        onClick && onClick(e);
      }}
    >{children}</a>
  );
}

// ---------- Nav ----------
function TopNav() {
  const { path } = useRouter();
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const on = () => setScrolled(window.scrollY > 8);
    window.addEventListener('scroll', on, { passive: true });
    on();
    return () => window.removeEventListener('scroll', on);
  }, []);
  return (
    <header style={{
      position: 'sticky', top: 0, zIndex: 40,
      borderBottom: '1px solid var(--rule)',
      background: scrolled ? 'color-mix(in oklab, var(--paper) 88%, transparent)' : 'var(--paper)',
      backdropFilter: scrolled ? 'saturate(1.4) blur(10px)' : 'none',
      transition: 'background .2s',
    }}>
      <div style={{
        maxWidth: 1240, margin: '0 auto',
        padding: '14px 28px',
        display: 'grid', gridTemplateColumns: '1fr auto 1fr', alignItems: 'center', gap: 24,
      }}>
        <Link to="/" style={{ display: 'inline-flex', alignItems: 'center', gap: 10 }}>
          <LogoMark />
          <span style={{ fontFamily: 'var(--font-sans)', fontWeight: 600, letterSpacing: '-0.01em', fontSize: 17 }}>
            IssuesId
          </span>
          <span style={{
            fontFamily: 'var(--font-mono)', fontSize: 10, padding: '2px 6px',
            border: '1px solid var(--rule)', borderRadius: 3, color: 'var(--ink-3)',
            textTransform: 'uppercase', letterSpacing: '0.08em'
          }}>v4.2</span>
        </Link>
        <nav style={{ display: 'flex', gap: 4, justifyContent: 'center' }}>
          {[
            { to: '/', label: 'Product' },
            { to: '/pricing', label: 'Pricing' },
            { to: '/about', label: 'About' },
            { to: '/contact', label: 'Contact' },
          ].map(l => (
            <Link key={l.to} to={l.to} style={{
              padding: '8px 14px', fontSize: 14, fontWeight: 500,
              borderRadius: 6,
              color: path === l.to ? 'var(--ink)' : 'var(--ink-2)',
              background: path === l.to ? 'var(--paper-2)' : 'transparent',
              transition: 'background .15s, color .15s',
            }}
            onMouseEnter={e => { if (path !== l.to) e.currentTarget.style.background = 'var(--paper-2)'; }}
            onMouseLeave={e => { if (path !== l.to) e.currentTarget.style.background = 'transparent'; }}
            >{l.label}</Link>
          ))}
        </nav>
        <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', alignItems: 'center' }}>
          <a href="#/contact" onClick={e => { e.preventDefault(); window.location.hash = '/contact'; }}
             style={{ fontSize: 14, padding: '8px 14px', color: 'var(--ink-2)', fontWeight: 500 }}>Login</a>
          <Btn to="/contact" variant="primary" size="sm">Request demo →</Btn>
        </div>
      </div>
    </header>
  );
}

function LogoMark({ size = 22, invert = false }) {
  const bg = invert ? 'var(--paper)' : 'var(--ink)';
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" aria-hidden>
      <rect x="1" y="1" width="22" height="22" rx="4" fill={bg} />
      <path d="M6 6h12v2H6zM6 10h12v2H6zM6 14h8v2H6z" fill="var(--accent)"/>
      <circle cx="17" cy="15" r="1.6" fill="var(--accent)" />
    </svg>
  );
}

// ---------- Buttons ----------
function Btn({ to, href, children, variant = 'secondary', size = 'md', onClick, style, as }) {
  const sizes = {
    sm: { padding: '8px 14px', fontSize: 13 },
    md: { padding: '12px 18px', fontSize: 14 },
    lg: { padding: '14px 22px', fontSize: 15 },
  };
  const variants = {
    primary: { background: 'var(--ink)', color: 'var(--paper)', border: '1px solid var(--ink)' },
    accent: { background: 'var(--accent)', color: 'oklch(0.18 0.04 55)', border: '1px solid var(--accent)' },
    secondary: { background: 'transparent', color: 'var(--ink)', border: '1px solid var(--rule)' },
    ghost: { background: 'transparent', color: 'var(--ink)', border: '1px solid transparent' },
    ghostLight: { background: 'color-mix(in oklab, white 10%, transparent)', color: 'var(--paper)', border: '1px solid color-mix(in oklab, white 25%, transparent)' },
  };
  const common = {
    fontFamily: 'var(--font-sans)', fontWeight: 500,
    borderRadius: 6, cursor: 'pointer',
    display: 'inline-flex', alignItems: 'center', gap: 8,
    transition: 'transform .12s, filter .15s, background .15s',
    textDecoration: 'none', whiteSpace: 'nowrap',
    ...sizes[size], ...variants[variant], ...style,
  };
  const hover = {
    onMouseEnter: e => { e.currentTarget.style.filter = 'brightness(0.92)'; },
    onMouseLeave: e => { e.currentTarget.style.filter = 'brightness(1)'; },
    onMouseDown: e => { e.currentTarget.style.transform = 'translateY(1px)'; },
    onMouseUp: e => { e.currentTarget.style.transform = 'translateY(0)'; },
  };
  if (to) {
    return <Link to={to}><button style={common} {...hover}>{children}</button></Link>;
  }
  if (href) {
    return <a href={href} style={common} {...hover}>{children}</a>;
  }
  return <button onClick={onClick} style={common} {...hover}>{children}</button>;
}

// ---------- Section wrappers ----------
function Section({ children, style, label, labelColor }) {
  return (
    <section style={{ padding: '96px 28px', borderTop: '1px solid var(--rule)', ...style }}>
      <div style={{ maxWidth: 1240, margin: '0 auto' }}>
        {label && <EyebrowLabel color={labelColor}>{label}</EyebrowLabel>}
        {children}
      </div>
    </section>
  );
}

function EyebrowLabel({ children, color }) {
  return (
    <div style={{
      display: 'inline-flex', alignItems: 'center', gap: 8,
      fontFamily: 'var(--font-mono)', fontSize: 11, fontWeight: 500,
      color: color || 'var(--ink-3)',
      letterSpacing: '0.12em', textTransform: 'uppercase',
      marginBottom: 28,
    }}>
      <span style={{ width: 6, height: 6, background: 'var(--accent)', borderRadius: 1 }} />
      {children}
    </div>
  );
}

// ---------- Defect card (the hero star) ----------
function DefectCard({ compact = false }) {
  const [status, setStatus] = useState('open');
  const statuses = {
    open: { label: 'Open', color: 'var(--danger)', bg: 'color-mix(in oklab, var(--danger) 14%, transparent)' },
    assigned: { label: 'Assigned', color: 'var(--warn)', bg: 'color-mix(in oklab, var(--warn) 20%, transparent)' },
    resolved: { label: 'Resolved', color: 'var(--ok)', bg: 'color-mix(in oklab, var(--ok) 16%, transparent)' },
  };
  const s = statuses[status];
  return (
    <div style={{
      background: 'var(--card)',
      border: '1px solid var(--rule)',
      borderRadius: 10,
      overflow: 'hidden',
      boxShadow: '0 1px 0 rgba(0,0,0,0.02), 0 24px 60px -30px rgba(0,0,0,0.18)',
      fontFamily: 'var(--font-sans)',
      width: '100%',
    }}>
      {/* Header */}
      <div style={{
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        padding: '12px 16px', borderBottom: '1px solid var(--rule)',
        background: 'var(--paper-2)',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <span style={{
            fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--ink-3)',
            letterSpacing: '0.05em',
          }}>DEF-0421</span>
          <span style={{
            fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--ink-3)',
            padding: '2px 6px', border: '1px solid var(--rule)', borderRadius: 3,
          }}>LVL 04 · BATH 2B</span>
        </div>
        <button onClick={() => {
          setStatus(status === 'open' ? 'assigned' : status === 'assigned' ? 'resolved' : 'open');
        }}
          style={{
            display: 'inline-flex', alignItems: 'center', gap: 6,
            padding: '3px 8px', fontSize: 11, fontFamily: 'var(--font-mono)',
            color: s.color, background: s.bg, border: 'none',
            borderRadius: 4, cursor: 'pointer', fontWeight: 500,
            letterSpacing: '0.04em', textTransform: 'uppercase',
          }}>
          <span style={{ width: 6, height: 6, background: s.color, borderRadius: '50%' }} />
          {s.label}
        </button>
      </div>
      {/* Photo area */}
      <div style={{
        position: 'relative', aspectRatio: '16/9',
        background: `repeating-linear-gradient(45deg, var(--paper-2), var(--paper-2) 8px, var(--rule-2) 8px, var(--rule-2) 9px)`,
        borderBottom: '1px solid var(--rule)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        {/* annotation pin */}
        <div style={{
          position: 'absolute', top: '34%', left: '58%',
          width: 28, height: 28, borderRadius: '50%',
          background: 'var(--accent)',
          border: '3px solid var(--card)',
          boxShadow: '0 2px 10px rgba(0,0,0,0.18)',
          display: 'grid', placeItems: 'center',
          color: 'oklch(0.18 0.04 55)', fontWeight: 700, fontSize: 13,
          fontFamily: 'var(--font-mono)',
        }}>1</div>
        <div style={{
          position: 'absolute', top: '34%', left: '58%',
          width: 28, height: 28, borderRadius: '50%',
          background: 'var(--accent)', opacity: 0.35,
          animation: 'ping 1.8s ease-out infinite',
        }} />
        <span style={{
          fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--ink-3)',
          background: 'var(--card)', padding: '4px 8px', borderRadius: 3,
          border: '1px solid var(--rule)',
        }}>photo · silicone seal, bathroom basin</span>
      </div>
      {/* Body */}
      <div style={{ padding: '16px' }}>
        <div style={{ fontSize: 15, fontWeight: 500, marginBottom: 6, letterSpacing: '-0.01em' }}>
          Silicone seal discontinuous at basin edge
        </div>
        <div style={{ fontSize: 13, color: 'var(--ink-2)', lineHeight: 1.5, marginBottom: 14 }}>
          ~40 mm gap between basin rim and tiled splashback. Water ingress risk. Reseal required before PC sign-off.
        </div>
        <div style={{
          display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10,
          paddingTop: 14, borderTop: '1px dashed var(--rule)',
          fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--ink-3)',
        }}>
          <div><div style={{ color: 'var(--ink-3)' }}>TRADE</div><div style={{ color: 'var(--ink)', fontSize: 12, marginTop: 2 }}>Wet Seal Co.</div></div>
          <div><div style={{ color: 'var(--ink-3)' }}>DUE</div><div style={{ color: 'var(--ink)', fontSize: 12, marginTop: 2 }}>Fri 24 Apr</div></div>
          <div><div style={{ color: 'var(--ink-3)' }}>CAPTURED</div><div style={{ color: 'var(--ink)', fontSize: 12, marginTop: 2 }}>Offline · synced 09:41</div></div>
          <div><div style={{ color: 'var(--ink-3)' }}>INSPECTOR</div><div style={{ color: 'var(--ink)', fontSize: 12, marginTop: 2 }}>K. Hartley</div></div>
        </div>
      </div>
    </div>
  );
}

// ---------- Footer ----------
function Footer() {
  return (
    <footer style={{
      borderTop: '1px solid var(--rule)',
      padding: '64px 28px 32px',
      background: 'var(--paper-2)',
    }}>
      <div style={{ maxWidth: 1240, margin: '0 auto' }}>
        <div style={{
          display: 'grid', gridTemplateColumns: '2fr 1fr 1fr 1fr',
          gap: 40, marginBottom: 48,
        }}>
          <div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14 }}>
              <LogoMark size={20} />
              <span style={{ fontWeight: 600, fontSize: 16 }}>IssuesId</span>
            </div>
            <div style={{ fontSize: 14, color: 'var(--ink-2)', lineHeight: 1.55, maxWidth: 320 }}>
              Construction defect management for builders, inspectors, and sub-contractors.
            </div>
            <div style={{
              marginTop: 20, display: 'inline-flex', alignItems: 'center', gap: 8,
              fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--ink-3)',
              padding: '5px 10px', border: '1px solid var(--rule)', borderRadius: 4,
            }}>
              <span style={{ width: 6, height: 6, background: 'var(--ok)', borderRadius: '50%' }} />
              ALL SYSTEMS OPERATIONAL
            </div>
          </div>
          {[
            { title: 'Product', links: [['Features', '/features'], ['Solutions', '/solutions'], ['Pricing', '/pricing'], ['Customers', '/customers'], ['Changelog', '/changelog'], ['Status', '/status']] },
            { title: 'Company', links: [['About', '/about'], ['Contact', '/contact'], ['Careers', '/careers'], ['Blog', '/blog']] },
            { title: 'Legal', links: [['Privacy', '/privacy'], ['Terms', '/terms'], ['Security', '/security'], ['DPA', '/contact']] },
          ].map(col => (
            <div key={col.title}>
              <div style={{
                fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--ink-3)',
                letterSpacing: '0.12em', textTransform: 'uppercase', marginBottom: 14,
              }}>{col.title}</div>
              <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'grid', gap: 10 }}>
                {col.links.map(([l, to]) => (
                  <li key={l}><Link to={to} style={{ fontSize: 14, color: 'var(--ink-2)' }}>{l}</Link></li>
                ))}
              </ul>
            </div>
          ))}
        </div>
        <div style={{
          paddingTop: 24, borderTop: '1px solid var(--rule)',
          display: 'flex', justifyContent: 'space-between', alignItems: 'center',
          fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--ink-3)',
        }}>
          <div>© 2026 ISSUESID PTY LTD · ABN 00 000 000 000</div>
          <div>BUILT ON-SITE · SYDNEY · AEST</div>
        </div>
      </div>
    </footer>
  );
}

// ---------- Tweaks panel ----------
function TweaksPanel({ visible, accent, setAccent, font, setFont, theme, setTheme }) {
  if (!visible) return null;
  const accents = [
    { name: 'Safety Orange', v: '#f27a2a' },
    { name: 'Hi-Vis Yellow', v: '#e5b800' },
    { name: 'Concrete Blue', v: '#2f6ff0' },
    { name: 'Rebar Red', v: '#d94a3a' },
    { name: 'Forest', v: '#2d8a5f' },
    { name: 'Graphite', v: '#1f1f1f' },
  ];
  const fonts = [
    { k: 'geist', name: 'Geist + Instrument Serif' },
    { k: 'inter', name: 'Inter + Mono' },
    { k: 'fraunces', name: 'Inter + Fraunces' },
  ];
  return (
    <div style={{
      position: 'fixed', right: 20, bottom: 20, zIndex: 100,
      width: 280,
      background: 'var(--card)',
      border: '1px solid var(--rule)',
      borderRadius: 10,
      boxShadow: '0 24px 60px -20px rgba(0,0,0,0.25)',
      fontFamily: 'var(--font-sans)',
      overflow: 'hidden',
    }}>
      <div style={{
        padding: '10px 14px', borderBottom: '1px solid var(--rule)',
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        background: 'var(--paper-2)',
      }}>
        <span style={{
          fontFamily: 'var(--font-mono)', fontSize: 11,
          letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--ink-3)',
        }}>Tweaks</span>
        <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--ink-3)' }}>LIVE</span>
      </div>
      <div style={{ padding: 14, display: 'grid', gap: 16 }}>
        <div>
          <div style={{ fontSize: 11, color: 'var(--ink-3)', marginBottom: 8, fontFamily: 'var(--font-mono)', letterSpacing: '0.06em', textTransform: 'uppercase' }}>Accent</div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: 6 }}>
            {accents.map(a => (
              <button key={a.v} onClick={() => setAccent(a.v)} title={a.name}
                style={{
                  aspectRatio: '1', background: a.v, border: accent === a.v ? '2px solid var(--ink)' : '1px solid var(--rule)',
                  borderRadius: 4, cursor: 'pointer', padding: 0,
                }} />
            ))}
          </div>
        </div>
        <div>
          <div style={{ fontSize: 11, color: 'var(--ink-3)', marginBottom: 8, fontFamily: 'var(--font-mono)', letterSpacing: '0.06em', textTransform: 'uppercase' }}>Typography</div>
          <div style={{ display: 'grid', gap: 4 }}>
            {fonts.map(f => (
              <button key={f.k} onClick={() => setFont(f.k)}
                style={{
                  textAlign: 'left', padding: '8px 10px', fontSize: 13,
                  background: font === f.k ? 'var(--paper-2)' : 'transparent',
                  border: '1px solid ' + (font === f.k ? 'var(--ink)' : 'var(--rule)'),
                  borderRadius: 4, cursor: 'pointer', color: 'var(--ink)',
                  fontFamily: 'var(--font-sans)',
                }}>{f.name}</button>
            ))}
          </div>
        </div>
        <div>
          <div style={{ fontSize: 11, color: 'var(--ink-3)', marginBottom: 8, fontFamily: 'var(--font-mono)', letterSpacing: '0.06em', textTransform: 'uppercase' }}>Theme</div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 6 }}>
            {['light', 'dark'].map(t => (
              <button key={t} onClick={() => setTheme(t)}
                style={{
                  padding: '8px 10px', fontSize: 13, textTransform: 'capitalize',
                  background: theme === t ? 'var(--paper-2)' : 'transparent',
                  border: '1px solid ' + (theme === t ? 'var(--ink)' : 'var(--rule)'),
                  borderRadius: 4, cursor: 'pointer', color: 'var(--ink)',
                  fontFamily: 'var(--font-sans)',
                }}>{t}</button>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

// Global exports for other Babel files
Object.assign(window, {
  RouterProvider, useRouter, Link,
  TopNav, Footer, Btn, Section, EyebrowLabel,
  DefectCard, LogoMark, TweaksPanel,
});
