/* global React */
const { useState, useEffect, useRef, useMemo } = React;

// ─────────────────────────────────────────────────────────────
// Primitives
// ─────────────────────────────────────────────────────────────

const Eyebrow = ({ children, color, style }) => (
  <span className="cs-eyebrow" style={{ color: color || 'inherit', ...style }}>{children}</span>
);

const Slash = ({ color, size }) => (
  <span style={{
    display: 'inline-block',
    transform: 'skewX(-12deg)',
    color: color || 'var(--mid-soft)',
    fontWeight: 900,
    margin: '0 0.4em',
    fontFamily: 'var(--font-display)',
    fontSize: size || 'inherit',
  }}>/</span>
);

const Hairline = ({ color, style }) => (
  <div style={{ height: 1, background: color || 'var(--hairline)', width: '100%', ...style }} />
);

const Button = ({ children, variant = 'primary', href = '#', onClick, style, type }) => {
  const cls = variant === 'secondary' ? 'cs-btn cs-btn--secondary'
            : variant === 'ghost'     ? 'cs-btn cs-btn--ghost'
            : variant === 'on-ink'    ? 'cs-btn'
            : 'cs-btn';
  const onInk = variant === 'on-ink' ? { background: 'var(--paper)', color: 'var(--ink)', border: '1px solid var(--paper)' } : {};
  if (type) {
    return (
      <button type={type} className={cls} onClick={onClick} style={{ ...onInk, ...style }}>
        {children}
        {variant === 'ghost' ? null : <span style={{ marginLeft: 8 }}>→</span>}
      </button>
    );
  }
  return (
    <a className={cls} href={href} onClick={onClick} style={{ ...onInk, ...style }}>
      {children}
      {variant === 'ghost' ? null : <span style={{ marginLeft: 8 }}>→</span>}
    </a>
  );
};

const SectionHeader = ({ index, count, eyebrow, action }) => (
  <div style={{ display: 'flex', alignItems: 'center', gap: 16, marginBottom: 56 }}>
    {(index || count) && (
      <span className="cs-mono" style={{ color: 'var(--mid)' }}>
        {index ? String(index).padStart(2, '0') : ''}{count ? ` / ${String(count).padStart(2, '0')}` : ''}
      </span>
    )}
    <Eyebrow style={{ color: 'var(--mid)' }}>{eyebrow}</Eyebrow>
    <div style={{ flex: 1, height: 1, background: 'var(--hairline)' }} />
    {action}
  </div>
);

// ─────────────────────────────────────────────────────────────
// Editorial Portrait — real photograph, treated for monochrome
// CentreStage aesthetic. Drop-in replacement API for Silhouette.
// ─────────────────────────────────────────────────────────────

const Portrait = ({ src, ratio = '3 / 4', label, code, hoverScale = true, treatment = 'mono', overlay = true, style }) => {
  const [hover, setHover] = useState(false);
  const filters = {
    mono:  'grayscale(100%) contrast(1.06) brightness(0.94)',
    warm:  'grayscale(70%) sepia(0.18) contrast(1.05) brightness(0.93) saturate(0.9)',
    cool:  'grayscale(85%) contrast(1.08) brightness(0.9)',
    color: 'contrast(1.06) brightness(0.96) saturate(0.85)',
    deep:  'grayscale(100%) contrast(1.15) brightness(0.78)',
  };
  return (
    <div
      data-reveal-img=""
      style={{
        position: 'relative', overflow: 'hidden',
        aspectRatio: ratio,
        background: 'var(--ink)',
        ...style,
      }}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
    >
      <img
        src={src} alt={label || ''}
        loading="lazy"
        style={{
          width: '100%', height: '100%', objectFit: 'cover', display: 'block',
          filter: filters[treatment] || filters.mono,
          transition: 'transform 600ms var(--ease-stage)',
          transform: hover && hoverScale ? 'scale(1.02)' : 'scale(1)',
        }}
      />
      {overlay && (
        <div style={{
          position: 'absolute', inset: 0, pointerEvents: 'none',
          background: 'radial-gradient(ellipse at center, transparent 45%, rgba(10,10,10,0.28) 100%)',
        }} />
      )}
      {label && (
        <div style={{
          position: 'absolute', bottom: 12, left: 14,
          fontFamily: 'var(--font-mono)', fontSize: 11,
          color: 'rgba(244,241,234,0.85)', letterSpacing: '0.06em',
          textShadow: '0 1px 2px rgba(0,0,0,0.5)',
        }}>{label}</div>
      )}
      {code && (
        <div style={{
          position: 'absolute', top: 12, right: 14,
          fontFamily: 'var(--font-mono)', fontSize: 10,
          color: 'rgba(244,241,234,0.7)', letterSpacing: '0.08em',
          textShadow: '0 1px 2px rgba(0,0,0,0.5)',
        }}>{code}</div>
      )}
    </div>
  );
};

// ─────────────────────────────────────────────────────────────
// Editorial Silhouette — abstract figure, no faces
// ─────────────────────────────────────────────────────────────

const SILHOUETTE_VARIANTS = {
  // Tight portrait, head + shoulders
  portrait: (color) => (
    <svg viewBox="0 0 300 400" preserveAspectRatio="xMidYMid slice" style={{ width: '100%', height: '100%', display: 'block' }}>
      <defs>
        <radialGradient id="cs-sil-portrait" cx="50%" cy="30%" r="80%">
          <stop offset="0%" stopColor={color.lite} />
          <stop offset="100%" stopColor={color.dark} />
        </radialGradient>
      </defs>
      <rect width="300" height="400" fill="url(#cs-sil-portrait)" />
      {/* Figure */}
      <path d="M150 90 C 178 90 200 112 200 142 C 200 168 188 188 175 200 C 215 215 245 245 260 295 L 260 400 L 40 400 L 40 295 C 55 245 85 215 125 200 C 112 188 100 168 100 142 C 100 112 122 90 150 90 Z"
            fill="var(--ink)" opacity="0.92" />
    </svg>
  ),
  // Wider, environmental — figure off-center
  environmental: (color) => (
    <svg viewBox="0 0 300 400" preserveAspectRatio="xMidYMid slice" style={{ width: '100%', height: '100%', display: 'block' }}>
      <defs>
        <linearGradient id="cs-sil-env" x1="0" y1="0" x2="1" y2="1">
          <stop offset="0%" stopColor={color.lite} />
          <stop offset="100%" stopColor={color.dark} />
        </linearGradient>
      </defs>
      <rect width="300" height="400" fill="url(#cs-sil-env)" />
      {/* Horizon line */}
      <rect x="0" y="320" width="300" height="1" fill="var(--ink)" opacity="0.4" />
      {/* Standing figure */}
      <path d="M195 160 C 208 160 218 170 218 184 C 218 196 213 204 207 210 C 220 215 230 226 230 240 L 230 320 C 230 322 228 324 226 324 L 220 324 L 220 380 C 220 384 217 386 213 386 L 208 386 C 204 386 202 384 202 380 L 202 324 L 198 324 L 198 380 C 198 384 195 386 191 386 L 186 386 C 182 386 180 384 180 380 L 180 324 L 174 324 C 172 324 170 322 170 320 L 170 240 C 170 226 180 215 193 210 C 187 204 182 196 182 184 C 182 170 192 160 195 160 Z"
            fill="var(--ink)" opacity="0.92" />
    </svg>
  ),
  // Three-quarter, head tilted
  threequarter: (color) => (
    <svg viewBox="0 0 300 400" preserveAspectRatio="xMidYMid slice" style={{ width: '100%', height: '100%', display: 'block' }}>
      <defs>
        <linearGradient id="cs-sil-tq" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor={color.lite} />
          <stop offset="100%" stopColor={color.dark} />
        </linearGradient>
      </defs>
      <rect width="300" height="400" fill="url(#cs-sil-tq)" />
      {/* Tilted head + shoulder */}
      <g transform="translate(150 200) rotate(-8) translate(-150 -200)">
        <path d="M170 100 C 200 100 222 124 222 154 C 222 182 208 202 192 213 C 240 226 270 258 285 308 L 285 400 L 30 400 L 30 320 C 50 268 90 232 138 215 C 122 204 110 184 110 154 C 110 124 138 100 170 100 Z"
              fill="var(--ink)" opacity="0.92" />
      </g>
    </svg>
  ),
  // Group — two overlapping figures
  group: (color) => (
    <svg viewBox="0 0 300 400" preserveAspectRatio="xMidYMid slice" style={{ width: '100%', height: '100%', display: 'block' }}>
      <defs>
        <linearGradient id="cs-sil-group" x1="0" y1="0" x2="1" y2="1">
          <stop offset="0%" stopColor={color.lite} />
          <stop offset="100%" stopColor={color.dark} />
        </linearGradient>
      </defs>
      <rect width="300" height="400" fill="url(#cs-sil-group)" />
      <path d="M90 140 C 112 140 130 158 130 180 C 130 198 122 212 112 220 C 142 230 168 254 180 290 L 180 400 L 0 400 L 0 290 C 12 254 38 230 68 220 C 58 212 50 198 50 180 C 50 158 68 140 90 140 Z"
            fill="var(--ink)" opacity="0.95" />
      <path d="M205 110 C 230 110 250 130 250 156 C 250 176 240 192 228 200 C 262 212 290 240 300 282 L 300 400 L 140 400 L 140 290 C 152 246 182 218 218 208 C 208 198 200 180 200 156 C 200 130 200 110 205 110 Z"
            fill="var(--ink-90)" opacity="0.85" />
    </svg>
  ),
  // Wide, full-bleed pose
  full: (color) => (
    <svg viewBox="0 0 400 300" preserveAspectRatio="xMidYMid slice" style={{ width: '100%', height: '100%', display: 'block' }}>
      <defs>
        <linearGradient id="cs-sil-full" x1="0" y1="0" x2="1" y2="0">
          <stop offset="0%" stopColor={color.lite} />
          <stop offset="100%" stopColor={color.dark} />
        </linearGradient>
      </defs>
      <rect width="400" height="300" fill="url(#cs-sil-full)" />
      <path d="M250 70 C 268 70 282 84 282 102 C 282 116 276 126 268 132 C 290 138 308 156 316 180 L 316 300 L 184 300 L 184 200 C 192 168 218 144 244 138 C 232 132 218 116 218 102 C 218 84 232 70 250 70 Z"
            fill="var(--ink)" opacity="0.92" />
    </svg>
  ),
};

const Silhouette = ({ variant = 'portrait', tone = 'warm', label, code, ratio, style, hoverScale = true }) => {
  const palettes = {
    warm:    { lite: '#A8987F', dark: '#3A2E25' },   // sepia
    cool:    { lite: '#7A8693', dark: '#252A33' },   // slate
    paper:   { lite: '#DAD3C2', dark: '#4A4438' },   // bone on dark
    deep:    { lite: '#3A332B', dark: '#0E0E0C' },   // very dark ink
    spotlight: { lite: '#F2D65A', dark: '#3A2E25' }, // accent warm
  };
  const c = palettes[tone] || palettes.warm;
  const render = SILHOUETTE_VARIANTS[variant] || SILHOUETTE_VARIANTS.portrait;
  const [hover, setHover] = useState(false);
  return (
    <div
      style={{
        position: 'relative', overflow: 'hidden',
        aspectRatio: ratio || (variant === 'full' ? '4 / 3' : '3 / 4'),
        background: 'var(--ink)',
        ...style,
      }}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
    >
      <div style={{
        position: 'absolute', inset: 0,
        transition: 'transform 600ms var(--ease-stage)',
        transform: hover && hoverScale ? 'scale(1.02)' : 'scale(1)',
      }}>
        {render(c)}
      </div>
      {/* Soft grain overlay */}
      <div style={{
        position: 'absolute', inset: 0,
        background: 'radial-gradient(ellipse at center, transparent 40%, rgba(10,10,10,0.18) 100%)',
        pointerEvents: 'none',
      }} />
      {label && (
        <div style={{
          position: 'absolute', bottom: 12, left: 14,
          fontFamily: 'var(--font-mono)', fontSize: 11,
          color: 'rgba(244,241,234,0.7)', letterSpacing: '0.06em',
        }}>{label}</div>
      )}
      {code && (
        <div style={{
          position: 'absolute', top: 12, right: 14,
          fontFamily: 'var(--font-mono)', fontSize: 10,
          color: 'rgba(244,241,234,0.5)', letterSpacing: '0.08em',
        }}>{code}</div>
      )}
    </div>
  );
};

// ─────────────────────────────────────────────────────────────
// Navigation
// ─────────────────────────────────────────────────────────────

const NAV_ITEMS = [
  { id: 'home',    label: 'Home' },
  { id: 'about',   label: 'Who we are' },
  { id: 'youth',   label: 'Youth (4–16)' },
  { id: 'pro',     label: 'Professional (17+)' },
  { id: 'faq',     label: 'FAQ' },
  { id: 'contact', label: 'Contact' },
];

const Nav = ({ route, navigate }) => {
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 12);
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  // Close drawer when route changes
  useEffect(() => { setOpen(false); }, [route]);
  // Lock scroll when drawer open
  useEffect(() => {
    if (open) {
      const prev = document.body.style.overflow;
      document.body.style.overflow = 'hidden';
      return () => { document.body.style.overflow = prev; };
    }
  }, [open]);
  return (
    <header className="cs-nav" style={{
      position: 'sticky', top: 0, zIndex: 50,
      background: scrolled ? 'rgba(244,241,234,0.78)' : 'var(--paper)',
      backdropFilter: scrolled ? 'blur(12px)' : 'none',
      WebkitBackdropFilter: scrolled ? 'blur(12px)' : 'none',
      borderBottom: '1px solid var(--hairline)',
      transition: 'background 240ms var(--ease-stage)',
    }}>
      <div className="cs-nav-inner" style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '20px 48px', height: 72,
        maxWidth: 1600, margin: '0 auto',
      }}>
        <a href="#home" onClick={(e) => { e.preventDefault(); navigate('home'); }}
           className="cs-logo-link"
           style={{ display: 'flex', alignItems: 'center', gap: 14, textDecoration: 'none' }}
           aria-label="CentreStage Agency home">
          <img src={(window.__resources && window.__resources.logoBlack) || "assets/logo/CentreStage-Solid-Black.png"} alt="CentreStage" style={{ height: 20 }} />
          <span className="cs-logo-divider" style={{
            display: 'inline-block', width: 1, height: 18, background: 'var(--hairline)',
          }} />
          <span className="cs-mono cs-logo-tagline" style={{ color: 'var(--mid)', fontSize: 11, letterSpacing: '0.08em', textTransform: 'uppercase' }}>
            Geelong <Slash color="var(--hairline)" /> National
          </span>
        </a>
        <nav style={{ display: 'flex', gap: 28 }} className="cs-nav-desktop">
          {NAV_ITEMS.map(it => {
            const active = route === it.id;
            return (
              <a key={it.id} href={`#${it.id}`} onClick={(e) => { e.preventDefault(); navigate(it.id); }}
                 style={{
                   fontFamily: 'var(--font-sans)', fontSize: 12, fontWeight: 700,
                   letterSpacing: '0.08em', textTransform: 'uppercase',
                   color: active ? 'var(--ink)' : 'var(--mid)',
                   textDecoration: 'none', paddingBottom: 4,
                   borderBottom: active ? '2px solid var(--ink)' : '2px solid transparent',
                   transition: 'color 200ms var(--ease-stage)',
                 }}>
                {it.label}
              </a>
            );
          })}
        </nav>

        {/* Hamburger — mobile only via CSS */}
        <button
          type="button"
          className="cs-nav-burger"
          onClick={() => setOpen(o => !o)}
          aria-label={open ? 'Close menu' : 'Open menu'}
          aria-expanded={open}
          style={{
            display: 'none',
            width: 44, height: 44, border: 0, background: 'transparent',
            cursor: 'pointer', padding: 0, position: 'relative',
          }}
        >
          <span style={{
            position: 'absolute', left: 10, right: 10, top: '50%',
            height: 1.5, background: 'var(--ink)',
            transform: open ? 'translateY(0) rotate(45deg)' : 'translateY(-6px)',
            transition: 'transform 240ms var(--ease-stage), opacity 240ms var(--ease-stage)',
          }} />
          <span style={{
            position: 'absolute', left: 10, right: 10, top: '50%',
            height: 1.5, background: 'var(--ink)',
            opacity: open ? 0 : 1,
            transform: 'translateY(0)',
            transition: 'opacity 160ms var(--ease-stage)',
          }} />
          <span style={{
            position: 'absolute', left: 10, right: 10, top: '50%',
            height: 1.5, background: 'var(--ink)',
            transform: open ? 'translateY(0) rotate(-45deg)' : 'translateY(6px)',
            transition: 'transform 240ms var(--ease-stage)',
          }} />
        </button>
      </div>

      {/* Mobile inline expansion — expands below the nav row when open */}
      <div
        className="cs-nav-expand"
        aria-hidden={!open}
        style={{
          display: 'none', // toggled to block via media query
          overflow: 'hidden',
          maxHeight: open ? '70vh' : '0px',
          opacity: open ? 1 : 0,
          transition: 'max-height 360ms var(--ease-stage), opacity 240ms var(--ease-stage)',
          background: 'var(--paper)',
          borderBottom: open ? '1px solid var(--hairline)' : 'none',
        }}
      >
        <nav style={{ padding: '4px 20px 20px' }}>
          {NAV_ITEMS.map((it, i) => {
            const active = route === it.id;
            return (
              <a key={it.id} href={`#${it.id}`}
                 onClick={(e) => { e.preventDefault(); navigate(it.id); setOpen(false); }}
                 style={{
                   padding: '16px 0',
                   borderTop: i === 0 ? '0' : '1px solid var(--hairline)',
                   display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                   textDecoration: 'none',
                   color: active ? 'var(--ink)' : 'var(--mid)',
                   fontFamily: 'var(--font-sans)', fontWeight: 700,
                   fontSize: 17, letterSpacing: '-0.01em',
                 }}>
                <span style={{ display: 'inline-flex', alignItems: 'center', gap: 12 }}>
                  <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--mid)', letterSpacing: '0.08em', minWidth: 20 }}>
                    {String(i + 1).padStart(2, '0')}
                  </span>
                  {it.label}
                </span>
                {active ? (
                  <span style={{ display: 'inline-block', transform: 'skewX(-12deg)', fontFamily: 'var(--font-display)', fontWeight: 900, fontSize: 16, color: 'var(--ink)' }}>/</span>
                ) : (
                  <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--mid-soft)' }}>→</span>
                )}
              </a>
            );
          })}
          <div style={{ marginTop: 18, paddingTop: 16, borderTop: '1px solid var(--hairline)', display: 'flex', gap: 24, fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--mid)', letterSpacing: '0.06em', lineHeight: 1.5 }}>
            <a href="mailto:agency@centrestage.org.au" style={{ color: 'var(--mid)', textDecoration: 'none' }}>
              agency@centrestage.org.au
            </a>
            <span style={{ color: 'var(--mid-soft)' }}>Fyansford VIC</span>
          </div>
        </nav>
      </div>
    </header>
  );
};

// ─────────────────────────────────────────────────────────────
// Footer
// ─────────────────────────────────────────────────────────────

const Footer = ({ navigate }) => {
  const a = window.CS_DATA.agency;
  return (
    <footer style={{ background: 'var(--ink)', color: 'var(--paper)', marginTop: 144 }}>
      <div style={{ maxWidth: 1600, margin: '0 auto', padding: '88px 48px 36px' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1.6fr 1fr 1fr 1fr', gap: 48, alignItems: 'flex-start' }}>
          <div>
            <img src={(window.__resources && window.__resources.logoWhite) || "assets/logo/CentreStage-Solid-White.png"} alt="CentreStage" style={{ height: 28, marginBottom: 28 }} />
            <p style={{ fontSize: 15, lineHeight: 1.6, color: 'var(--fg-on-ink-2)', maxWidth: '34ch', margin: 0 }}>
              An Australian casting and talent management agency representing children, young people, and working professionals.
            </p>
            <div style={{ marginTop: 28, display: 'flex', gap: 20 }}>
              <a href={a.facebook} target="_blank" rel="noopener" style={{ color: 'var(--paper)', fontFamily: 'var(--font-sans)', fontSize: 11, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', textDecoration: 'none' }}>Facebook ↗</a>
              <a href={a.instagram} target="_blank" rel="noopener" style={{ color: 'var(--paper)', fontFamily: 'var(--font-sans)', fontSize: 11, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', textDecoration: 'none' }}>Instagram ↗</a>
            </div>

            {/* Parent brand */}
            {a.parentBrand && (
              <div style={{ marginTop: 36, paddingTop: 28, borderTop: '1px solid var(--hairline-ink)' }}>
                <div style={{ fontFamily: 'var(--font-sans)', fontSize: 10, fontWeight: 700, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--fg-on-ink-2)', marginBottom: 8 }}>
                  Part of
                </div>
                <a href={a.parentBrand.url} target="_blank" rel="noopener"
                   style={{
                     color: 'var(--paper)', textDecoration: 'none',
                     fontFamily: 'var(--font-display)', fontWeight: 900,
                     fontSize: 26, letterSpacing: '-0.02em',
                     display: 'inline-flex', alignItems: 'baseline', gap: 8,
                   }}
                   onMouseEnter={e => { e.currentTarget.style.textDecoration = 'underline'; e.currentTarget.style.textUnderlineOffset = '4px'; }}
                   onMouseLeave={e => { e.currentTarget.style.textDecoration = 'none'; }}
                >
                  {a.parentBrand.name}
                  <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, fontWeight: 400, color: 'var(--fg-on-ink-2)', letterSpacing: '0.04em' }}>↗</span>
                </a>
              </div>
            )}
          </div>
          {[
            { h: 'Agency',          links: [['Who we are','about'],['FAQ','faq'],['Contact','contact']] },
            { h: 'Sign up',         links: [['Youth (4–16)','youth'],['Professional (17+)','pro']] },
            { h: 'Studio',          links: [['Head Office, Geelong','contact'],['National touchpoints','contact']] },
          ].map(col => (
            <div key={col.h}>
              <div style={{ fontFamily: 'var(--font-sans)', fontSize: 11, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--fg-on-ink-2)', marginBottom: 18 }}>{col.h}</div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                {col.links.map(([label, route], i) => (
                  <a key={i} href={`#${route}`} onClick={(e) => { e.preventDefault(); navigate(route); }}
                     style={{ color: 'var(--paper)', fontSize: 14, textDecoration: 'none', lineHeight: 1.4 }}
                     onMouseEnter={e => { e.currentTarget.style.textDecoration = 'underline'; e.currentTarget.style.textUnderlineOffset = '4px'; }}
                     onMouseLeave={e => { e.currentTarget.style.textDecoration = 'none'; }}
                  >{label}</a>
                ))}
              </div>
            </div>
          ))}
        </div>
        <div style={{ height: 1, background: 'var(--hairline-ink)', margin: '64px 0 22px' }} />
        <div style={{ display: 'flex', justifyContent: 'space-between', flexWrap: 'wrap', gap: 12, fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--fg-on-ink-2)', letterSpacing: '0.04em' }}>
          <span>© 2026 CENTRESTAGE AGENCY</span>
          <span>{a.email.toUpperCase()}</span>
          <span>GEELONG <Slash color="var(--mid)" /> MELBOURNE <Slash color="var(--mid)" /> SYDNEY <Slash color="var(--mid)" /> NATIONAL</span>
        </div>
      </div>
    </footer>
  );
};

// ─────────────────────────────────────────────────────────────
// Form primitives
// ─────────────────────────────────────────────────────────────

const FieldLabel = ({ children, required, hint }) => (
  <div style={{ marginBottom: 8, display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 8 }}>
    <span style={{
      fontFamily: 'var(--font-sans)', fontSize: 11, fontWeight: 700,
      letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--mid)',
    }}>
      {children}{required ? <span style={{ color: 'var(--ink)' }}> *</span> : null}
    </span>
    {hint && (
      <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--mid-soft)', letterSpacing: '0.04em' }}>
        {hint}
      </span>
    )}
  </div>
);

const TextField = ({ label, name, type = 'text', placeholder, required, hint, value, onChange, autoComplete }) => (
  <div>
    <FieldLabel required={required} hint={hint}>{label}</FieldLabel>
    <input
      className="cs-input"
      type={type} name={name} placeholder={placeholder} value={value}
      onChange={e => onChange && onChange(e.target.value)}
      autoComplete={autoComplete}
      style={{
        padding: '0 0 10px 0', height: 44, fontSize: 17,
        borderBottom: '1px solid var(--ink)',
      }}
    />
  </div>
);

const SelectField = ({ label, name, options, required, hint, value, onChange }) => (
  <div>
    <FieldLabel required={required} hint={hint}>{label}</FieldLabel>
    <select
      name={name} value={value || ''} onChange={e => onChange && onChange(e.target.value)}
      style={{
        width: '100%', height: 44, padding: '0 0 10px 0',
        background: 'transparent', border: 0, borderBottom: '1px solid var(--ink)',
        fontFamily: 'var(--font-sans)', fontSize: 17, color: 'var(--ink)',
        borderRadius: 0, outline: 'none', cursor: 'pointer',
        appearance: 'none', WebkitAppearance: 'none', MozAppearance: 'none',
        backgroundImage: 'url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\' width=\'12\' height=\'8\' viewBox=\'0 0 12 8\'><path d=\'M1 1l5 5 5-5\' stroke=\'%230A0A0A\' stroke-width=\'1.5\' fill=\'none\' stroke-linecap=\'square\'/></svg>")',
        backgroundRepeat: 'no-repeat', backgroundPosition: 'right 4px center', paddingRight: 24,
      }}
    >
      <option value="" disabled>Select…</option>
      {options.map(o => <option key={o} value={o}>{o}</option>)}
    </select>
  </div>
);

const TextArea = ({ label, name, placeholder, required, hint, rows = 4, value, onChange }) => (
  <div>
    <FieldLabel required={required} hint={hint}>{label}</FieldLabel>
    <textarea
      className="cs-textarea"
      name={name} placeholder={placeholder} rows={rows} value={value}
      onChange={e => onChange && onChange(e.target.value)}
      style={{
        width: '100%', padding: 16,
        fontFamily: 'var(--font-sans)', fontSize: 17, color: 'var(--ink)',
        background: 'transparent', border: '1px solid var(--ink)',
        borderRadius: 0, resize: 'vertical', outline: 'none',
        lineHeight: 1.5,
      }}
    />
  </div>
);

const DOBField = ({ label, name, required, hint, value, onChange }) => {
  // value is "YYYY-MM-DD" or empty
  const parts = (value || '').split('-');
  const [d, m, y] = [parts[2] || '', parts[1] || '', parts[0] || ''];
  const update = (day, mon, year) => {
    if (!day && !mon && !year) { onChange && onChange(''); return; }
    onChange && onChange(`${year || ''}-${(mon || '').padStart(2,'0')}-${(day || '').padStart(2,'0')}`);
  };
  const ipStyle = {
    height: 44, padding: '0 0 10px 0', background: 'transparent', border: 0,
    borderBottom: '1px solid var(--ink)', fontFamily: 'var(--font-mono)', fontSize: 17,
    color: 'var(--ink)', borderRadius: 0, outline: 'none', textAlign: 'center', width: '100%',
  };
  return (
    <div>
      <FieldLabel required={required} hint={hint}>{label}</FieldLabel>
      <div style={{ display: 'grid', gridTemplateColumns: '60px 60px 1fr', gap: 12 }}>
        <input style={ipStyle} placeholder="DD" maxLength={2} inputMode="numeric"
          value={d} onChange={e => update(e.target.value, m, y)} />
        <input style={ipStyle} placeholder="MM" maxLength={2} inputMode="numeric"
          value={m} onChange={e => update(d, e.target.value, y)} />
        <input style={ipStyle} placeholder="YYYY" maxLength={4} inputMode="numeric"
          value={y} onChange={e => update(d, m, e.target.value)} />
      </div>
    </div>
  );
};

const CheckboxGroup = ({ label, name, options, required, value, onChange, columns = 2 }) => {
  const arr = value || [];
  const toggle = (o) => {
    const next = arr.includes(o) ? arr.filter(x => x !== o) : [...arr, o];
    onChange && onChange(next);
  };
  return (
    <div>
      <FieldLabel required={required}>{label}</FieldLabel>
      <div style={{ display: 'grid', gridTemplateColumns: `repeat(${columns}, 1fr)`, gap: 8, marginTop: 4 }}>
        {options.map(o => {
          const on = arr.includes(o);
          return (
            <button type="button" key={o} onClick={() => toggle(o)}
              style={{
                display: 'flex', alignItems: 'center', gap: 12,
                padding: '12px 14px', textAlign: 'left',
                border: '1px solid ' + (on ? 'var(--ink)' : 'var(--hairline)'),
                background: on ? 'var(--ink)' : 'transparent',
                color: on ? 'var(--paper)' : 'var(--ink)',
                fontFamily: 'var(--font-sans)', fontSize: 13, fontWeight: 700,
                letterSpacing: '0.04em', textTransform: 'uppercase',
                cursor: 'pointer', borderRadius: 0,
                transition: 'background 200ms var(--ease-stage), color 200ms var(--ease-stage), border-color 200ms var(--ease-stage)',
              }}>
              <span style={{
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                width: 14, height: 14, border: '1px solid ' + (on ? 'var(--paper)' : 'var(--ink)'),
                flexShrink: 0,
              }}>
                {on ? <span style={{ fontSize: 12, lineHeight: 1, color: 'var(--paper)' }}>×</span> : null}
              </span>
              {o}
            </button>
          );
        })}
      </div>
    </div>
  );
};

const FileUpload = ({ label, name, accept, required, hint, value, onChange }) => {
  const inputRef = useRef(null);
  const filename = value ? (value.name || (value.file && value.file.name)) : null;
  const filesize = value ? (value.size || (value.file && value.file.size)) : null;
  return (
    <div>
      <FieldLabel required={required} hint={hint}>{label}</FieldLabel>
      <div
        onClick={() => inputRef.current && inputRef.current.click()}
        style={{
          border: '1px dashed var(--ink)',
          padding: '20px 18px',
          cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16,
          background: filename ? 'var(--ink)' : 'transparent',
          color: filename ? 'var(--paper)' : 'var(--ink)',
          transition: 'background 200ms var(--ease-stage), color 200ms var(--ease-stage)',
        }}
      >
        <div style={{ display: 'flex', alignItems: 'center', gap: 14, minWidth: 0 }}>
          <span style={{
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
            width: 36, height: 36, border: '1px solid currentColor', flexShrink: 0,
          }}>
            <span style={{ fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 900, lineHeight: 1, transform: 'translateY(-1px)' }}>+</span>
          </span>
          <div style={{ minWidth: 0 }}>
            <div style={{ fontFamily: 'var(--font-sans)', fontSize: 14, fontWeight: 700, letterSpacing: '-0.01em', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
              {filename || 'Click to upload'}
            </div>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, opacity: 0.7, letterSpacing: '0.04em' }}>
              {filename ? (filesize ? `${(filesize/1024).toFixed(0)} KB` : '') : (accept || 'PDF, JPG, PNG')}
            </div>
          </div>
        </div>
        <span style={{ fontFamily: 'var(--font-sans)', fontSize: 11, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase' }}>
          {filename ? 'Replace ↗' : 'Browse →'}
        </span>
        <input
          ref={inputRef} className="cs-file-hidden" type="file" name={name} accept={accept}
          onChange={(e) => {
            const f = e.target.files && e.target.files[0];
            onChange && onChange(f ? { name: f.name, size: f.size, file: f } : null);
          }}
        />
      </div>
    </div>
  );
};

const ConsentCheckbox = ({ label, value, onChange }) => (
  <label style={{ display: 'flex', alignItems: 'flex-start', gap: 14, cursor: 'pointer' }}>
    <span
      onClick={(e) => { e.preventDefault(); onChange && onChange(!value); }}
      style={{
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        width: 22, height: 22, border: '1px solid var(--ink)',
        background: value ? 'var(--ink)' : 'transparent',
        flexShrink: 0, marginTop: 2,
        transition: 'background 200ms var(--ease-stage)',
      }}>
      {value ? <span style={{ color: 'var(--paper)', fontSize: 16, lineHeight: 1, fontFamily: 'var(--font-display)' }}>/</span> : null}
    </span>
    <span style={{ fontSize: 14, lineHeight: 1.5, color: 'var(--ink)' }}>{label}</span>
    <input type="checkbox" checked={value || false} onChange={e => onChange && onChange(e.target.checked)} style={{ display: 'none' }} />
  </label>
);

// ─────────────────────────────────────────────────────────────
// Form section header
// ─────────────────────────────────────────────────────────────

const FormSection = ({ index, title, intro, children }) => (
  <section style={{ display: 'grid', gridTemplateColumns: '1fr 2fr', gap: 64, alignItems: 'flex-start' }}>
    <div>
      <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--mid)', letterSpacing: '0.08em', marginBottom: 12 }}>
        STEP {String(index).padStart(2, '0')}
      </div>
      <h3 style={{ fontFamily: 'var(--font-display)', fontWeight: 900, fontSize: 36, letterSpacing: '-0.02em', lineHeight: 1, margin: '0 0 16px' }}>
        {title}
      </h3>
      {intro && <p style={{ fontSize: 15, lineHeight: 1.6, color: 'var(--mid)', maxWidth: '32ch', margin: 0 }}>{intro}</p>}
    </div>
    <div style={{ display: 'flex', flexDirection: 'column', gap: 28 }}>
      {children}
    </div>
  </section>
);

// Export to window
Object.assign(window, {
  Eyebrow, Slash, Hairline, Button, SectionHeader,
  Silhouette, Portrait, Nav, Footer,
  TextField, SelectField, TextArea, DOBField, CheckboxGroup, FileUpload, ConsentCheckbox,
  FieldLabel, FormSection,
  NAV_ITEMS,
});
