/* global React */
// Header + footer + shared chrome

/* DeltaStrat — symbol
   Equilateral, open delta.
   - Two white edges run from base corners up to a sharp apex (closed apex).
   - The bottom side is BROKEN: a small cut/gap divides white left segment
     from a short cyan segment on the right.
   - The bottom-right of the triangle has a small DIAGONAL CUT — the right
     edge does not meet the base; it terminates above the baseline and the
     cyan segment sits on the cut.
   - Sharp corners, consistent stroke, no glow, no gradient. */
function DeltaMark({ size = 22, strokeWidth }) {
  /*  Geometry — reference-exact
   *  ViewBox 0 0 34 30 (≈1.13:1, slightly wider than tall)
   *
   *  Apex    : (17, 2)
   *  BL      : ( 2, 29)
   *  BR      : (32, 29)
   *
   *  Segments
   *  --------
   *  White left edge   : apex → BL   (full diagonal)
   *  White right edge  : apex → BR   (full diagonal — reaches baseline)
   *  White left base   : BL → (13, 29)   short horizontal
   *  GAP               : 13 → 19   (6 units, clearly visible)
   *  Cyan right base   : (19, 29) → BR   horizontal, same baseline
   */
  const sw = strokeWidth ?? Math.max(1.4, size / 14);
  const h  = Math.round(size * 0.88);
  return (
    <svg width={size} height={h} viewBox="0 0 34 30"
      fill="none" aria-hidden="true" shapeRendering="geometricPrecision"
      style={{ display: 'block', flexShrink: 0 }}>
      <path d="M17 2 L2 29"
        stroke="#FFFFFF" strokeWidth={sw} strokeLinecap="square" strokeLinejoin="miter"/>
      <path d="M17 2 L32 29"
        stroke="#FFFFFF" strokeWidth={sw} strokeLinecap="square" strokeLinejoin="miter"/>
      <path d="M2 29 L13 29"
        stroke="#FFFFFF" strokeWidth={sw} strokeLinecap="square"/>
      <path d="M19 29 L32 29"
        stroke="#19B5E8" strokeWidth={sw} strokeLinecap="square"/>
    </svg>
  );
}

/* Wordmark — custom engineered letterforms
   Modifications applied via SVG mask (runtime measurement):
   · E: middle bar removed → open, segmented look
   · A: crossbar removed → sharp apex, open feel
   Tracking: +12%. DELTA white, STRAT cyan. Extra word gap.
*/
function Wordmark({ scale = 1, withSubtitle = false, subtitle, align = 'left' }) {
  const svgRef  = React.useRef(null);
  const [cuts, setCuts] = React.useState([]);
  const [svgW, setSvgW]   = React.useState(null);

  const fontSize = Math.round(18 * scale);
  const wordGap  = Math.round(fontSize * 0.55);
  const subSize  = Math.round(fontSize * 0.66);

  React.useEffect(() => {
    const svg = svgRef.current;
    if (!svg) return;

    const measure = () => {
      const textEl = svg.querySelector('#wm-main');
      if (!textEl || typeof textEl.getExtentOfChar !== 'function') return;
      try {
        const c = [];
        // E (charnum 1 in "DELTASTRAT"): erase middle bar
        const e = textEl.getExtentOfChar(1);
        c.push({ x: e.x + e.width*0.14, y: e.y + e.height*0.34, w: e.width*0.86, h: e.height*0.30 });
        // A in DELTA (charnum 4): erase crossbar
        const a1 = textEl.getExtentOfChar(4);
        c.push({ x: a1.x + a1.width*0.14, y: a1.y + a1.height*0.43, w: a1.width*0.72, h: a1.height*0.19 });
        // A in STRAT (charnum 8): erase crossbar
        const a2 = textEl.getExtentOfChar(8);
        c.push({ x: a2.x + a2.width*0.14, y: a2.y + a2.height*0.43, w: a2.width*0.72, h: a2.height*0.19 });
        setCuts(c);
        // Set explicit SVG width so text doesn't overflow into nav
        const totalW = textEl.getComputedTextLength();
        const measured = Math.ceil(totalW) + 4;
        setSvgW(measured);
        // Also set directly on the DOM element to avoid React re-render delay
        if (svg) svg.setAttribute('width', String(measured));
      } catch (_) { /* font metrics unavailable — fallback to unmodified */ }
    };

    if (document.fonts) {
      document.fonts.ready.then(() => requestAnimationFrame(measure));
    } else {
      setTimeout(measure, 500);
    }
  }, [fontSize]);

  const svgH  = fontSize + 4;
  const mId   = 'wm-mask';

  return (
    <div style={{
      display: 'flex', flexDirection: 'column',
      alignItems: align === 'center' ? 'center' : 'flex-start',
      lineHeight: 1,
    }}>
      <svg ref={svgRef} height={svgH} width={svgW || fontSize * 12}
           style={{ display: 'block', overflow: 'visible', maxWidth: 'none', flexShrink: 0 }}>
        <defs>
          <mask id={mId}>
            {/* White = show, Black = erase */}
            <rect x="-500" y="-50" width="4000" height="400" fill="white"/>
            {cuts.map((c, i) => (
              <rect key={i} x={c.x} y={c.y}
                width={Math.max(c.w, 0)} height={Math.max(c.h, 0)}
                fill="black"/>
            ))}
          </mask>
        </defs>
        <text id="wm-main" x={0} y={fontSize}
          fontFamily="'Inter Tight','Helvetica Neue',Helvetica,sans-serif"
          fontSize={fontSize} fontWeight={600}
          letterSpacing="0.14em"
          mask={`url(#${mId})`}>
          <tspan fill="#FFFFFF">DELTA</tspan>
          <tspan fill="#19B5E8" dx={wordGap}>STRAT</tspan>
        </text>
      </svg>

      {withSubtitle && subtitle && (
        <div style={{
          marginTop: Math.max(4, fontSize * 0.28),
          fontFamily: "'Inter Tight','Helvetica Neue',sans-serif",
          fontSize: subSize, fontWeight: 400,
          letterSpacing: '0.20em',
          color: '#8A939B',
          textTransform: 'uppercase',
          whiteSpace: 'nowrap',
        }}>{subtitle}</div>
      )}
    </div>
  );
}


function Logo({ onClick, size = 'sm', withSubtitle = false, subtitle }) {
  const cfg = {
    sm: { mark: 24, scale: 0.82, gap: 0, divH: 36 }, // header
    md: { mark: 32, scale: 1.15, gap: 0, divH: 48 }, // footer
    lg: { mark: 64, scale: 2.40, gap: 0, divH: 0  }, // hero
  }[size] || { mark: 24, scale: 0.82, gap: 0, divH: 36 };

  return (
    <button onClick={onClick} aria-label="DeltaStrat home"
      style={{
        display: 'flex', alignItems: 'center', gap: 0,
        padding: 0, background: 'transparent', border: 'none',
        cursor: onClick ? 'pointer' : 'default',
        flexShrink: 0,
      }}>
      {/* Delta symbol */}
      <DeltaMark size={cfg.mark} strokeWidth={size === 'lg' ? 2.2 : 1.6}/>

      {/* Vertical divider — between symbol and wordmark */}
      {cfg.divH > 0 && (
        <div style={{
          width: 1,
          height: cfg.divH,
          background: '#2A2F36',
          flexShrink: 0,
          margin: '0 18px',
          alignSelf: 'center',
        }}/>
      )}

      {/* Wordmark + subtitle */}
      <Wordmark scale={cfg.scale} withSubtitle={withSubtitle} subtitle={subtitle}/>
    </button>
  );
}

function Header({ lang, setLang, route, navigate, t }) {
  const [scrolled, setScrolled] = useState(false);
  const [mobileOpen, setMobileOpen] = useState(false);

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 8);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  useEffect(() => { setMobileOpen(false); }, [route.page, route.slug]);
  useEffect(() => {
    document.body.style.overflow = mobileOpen ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [mobileOpen]);

  const navItems = [
    { key: 'home', label: t.nav.home },
    { key: 'services', label: t.nav.services },
    { key: 'about', label: t.nav.about },
    { key: 'certifications', label: t.nav.certifications },
    { key: 'contact', label: t.nav.contact },
  ];

  const isActive = (k) => route.page === k;

  return (
    <>
      <header style={{
        position: 'fixed', top: 0, left: 0, right: 0, zIndex: 80,
        borderBottom: scrolled ? '1px solid var(--line)' : '1px solid transparent',
        background: scrolled ? 'oklch(0.14 0.006 250 / 0.78)' : 'transparent',
        backdropFilter: scrolled ? 'blur(14px) saturate(140%)' : 'none',
        transition: 'all 260ms var(--ease)',
      }}>
        <div className="container" style={{
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          height: 92,
        }}>
          <Logo onClick={() => navigate('home')} withSubtitle subtitle="OFFENSIVE SECURITY · APPLICATION SECURITY"/>

          {/* Desktop nav */}
          <nav className="desktop-nav" style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
            {navItems.map((item) => (
              <button key={item.key}
                onClick={() => navigate(item.key)}
                style={{
                  padding: '8px 14px',
                  fontFamily: 'var(--ff-mono)',
                  fontSize: 12,
                  letterSpacing: '0.06em',
                  textTransform: 'uppercase',
                  color: isActive(item.key) ? 'var(--fg-0)' : 'var(--fg-2)',
                  position: 'relative',
                  transition: 'color var(--t-fast)',
                }}
                onMouseEnter={(e) => e.currentTarget.style.color = 'var(--fg-0)'}
                onMouseLeave={(e) => e.currentTarget.style.color = isActive(item.key) ? 'var(--fg-0)' : 'var(--fg-2)'}
              >
                {item.label}
                {isActive(item.key) && (
                  <span style={{
                    position: 'absolute', left: 14, right: 14, bottom: 2,
                    height: 1, background: 'var(--accent)',
                  }}/>
                )}
              </button>
            ))}
          </nav>

          <div className="header-right" style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
            <LangSwitch lang={lang} setLang={setLang} />
            <button className="btn btn-primary desktop-cta" onClick={() => navigate('contact')}>
              {t.nav.cta}
              <span className="arrow">→</span>
            </button>
            <button className="mobile-toggle" aria-label="Menu"
              onClick={() => setMobileOpen((v) => !v)}
              style={{
                display: 'none',
                width: 40, height: 40,
                border: '1px solid var(--line)',
                borderRadius: 4,
                alignItems: 'center', justifyContent: 'center',
              }}>
              <svg width="16" height="12" viewBox="0 0 16 12" fill="none">
                <line x1="0" y1={mobileOpen ? 6 : 1} x2="16" y2={mobileOpen ? 6 : 1} stroke="currentColor" strokeWidth="1.5"
                  style={{ transform: mobileOpen ? 'rotate(45deg)' : 'none', transformOrigin: 'center', transition: '280ms var(--ease)' }}/>
                <line x1="0" y1="6" x2="16" y2="6" stroke="currentColor" strokeWidth="1.5"
                  style={{ opacity: mobileOpen ? 0 : 1, transition: '160ms' }}/>
                <line x1="0" y1={mobileOpen ? 6 : 11} x2="16" y2={mobileOpen ? 6 : 11} stroke="currentColor" strokeWidth="1.5"
                  style={{ transform: mobileOpen ? 'rotate(-45deg)' : 'none', transformOrigin: 'center', transition: '280ms var(--ease)' }}/>
              </svg>
            </button>
          </div>
        </div>
      </header>

      {/* Mobile panel */}
      <div className="mobile-panel" style={{
        position: 'fixed', top: 92, left: 0, right: 0, bottom: 0,
        zIndex: 70,
        background: 'var(--bg-0)',
        borderTop: '1px solid var(--line)',
        transform: mobileOpen ? 'translateY(0)' : 'translateY(-20px)',
        opacity: mobileOpen ? 1 : 0,
        pointerEvents: mobileOpen ? 'auto' : 'none',
        transition: 'all 320ms var(--ease)',
        padding: '32px 24px',
        display: 'flex', flexDirection: 'column', gap: 4,
      }}>
        {navItems.map((item, i) => (
          <button key={item.key}
            onClick={() => navigate(item.key)}
            style={{
              textAlign: 'left',
              padding: '18px 0',
              borderBottom: '1px solid var(--line)',
              fontFamily: 'var(--ff-display)',
              fontSize: 28, letterSpacing: '-0.02em',
              color: isActive(item.key) ? 'var(--accent)' : 'var(--fg-0)',
              display: 'flex', alignItems: 'center', gap: 16,
            }}>
            <span className="mono-sm" style={{ color: 'var(--fg-3)', minWidth: 24 }}>
              0{i + 1}
            </span>
            {item.label}
          </button>
        ))}
        <div style={{ marginTop: 32 }}>
          <button className="btn btn-primary" style={{ width: '100%', height: 56 }}
            onClick={() => navigate('contact')}>
            {t.nav.cta} <span className="arrow">→</span>
          </button>
        </div>
      </div>
    </>
  );
}

function LangSwitch({ lang, setLang }) {
  return (
    <div style={{
      display: 'flex',
      border: '1px solid var(--line)',
      borderRadius: 4,
      overflow: 'hidden',
      height: 32,
    }}>
      {LANGS.map((code) => {
        const isActive = lang === code;
        const label = code === 'pt-BR' ? 'PT' : 'EN';
        return (
          <button key={code}
            onClick={() => setLang(code)}
            style={{
              padding: '0 10px',
              fontFamily: 'var(--ff-mono)',
              fontSize: 11,
              letterSpacing: '0.08em',
              background: isActive ? 'var(--fg-0)' : 'transparent',
              color: isActive ? 'var(--bg-0)' : 'var(--fg-2)',
              transition: 'all var(--t-fast)',
            }}
          >{label}</button>
        );
      })}
    </div>
  );
}

function Footer({ t, navigate, lang, setLang }) {
  const s = t.home;
  const now = new Date();
  const time = now.toLocaleTimeString(lang === 'pt-BR' ? 'pt-BR' : 'en-US',
    { hour: '2-digit', minute: '2-digit', hour12: false, timeZone: 'America/Sao_Paulo' });
  return (
    <footer style={{
      borderTop: '1px solid var(--line)',
      padding: '80px 0 32px',
      background: 'var(--bg-0)',
      position: 'relative',
    }}>
      <div className="container">
        <div style={{
          display: 'grid',
          gridTemplateColumns: '1.4fr 1fr 1fr 1fr 1fr',
          gap: 48,
          marginBottom: 80,
        }} className="footer-grid">
          <div>
            <Logo onClick={() => navigate('home')} size="md" withSubtitle subtitle="Offensive Security · Application Security"/>
            <p style={{ color: 'var(--fg-2)', maxWidth: 280, marginTop: 20, fontSize: 14, lineHeight: 1.55 }}>
              {s.footerTagline}
            </p>
            <div style={{ display: 'flex', gap: 10, marginTop: 20 }}>
              <div className="status-pill">
                <span className="dot"/>
                {s.footerStatus}
              </div>
            </div>
          </div>

          <FooterCol title={s.footerSections.services}
            items={t.services.items.map(it => it.k)}
            onClick={(i) => navigate('services', t.services.items[i].slug)} />
          <FooterCol title={s.footerSections.company}
            items={s.footerLinks.company}
            onClick={(i) => { if (i === 0) navigate('about'); if (i === 2) navigate('certifications'); }} />
          <FooterCol title={s.footerSections.resources} items={s.footerLinks.resources} />
          <FooterCol title={s.footerSections.legal} items={s.footerLinks.legal} />
        </div>

        <div style={{
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          paddingTop: 24,
          borderTop: '1px solid var(--line)',
          fontFamily: 'var(--ff-mono)',
          fontSize: 11,
          letterSpacing: '0.04em',
          color: 'var(--fg-3)',
          gap: 16,
          flexWrap: 'wrap',
        }}>
          <div>{s.footerCopy}</div>
          <div style={{ display: 'flex', gap: 20, alignItems: 'center' }}>
            <span>{s.footerAddress}</span>
            <span>SÃO PAULO · {time}</span>
            <LangSwitch lang={lang} setLang={setLang} />
          </div>
        </div>
      </div>
    </footer>
  );
}

function FooterCol({ title, items, onClick }) {
  return (
    <div>
      <div className="mono-sm u-caps" style={{ color: 'var(--fg-3)', marginBottom: 20 }}>{title}</div>
      <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 12 }}>
        {items.map((it, i) => (
          <li key={i}>
            <button
              onClick={() => onClick && onClick(i)}
              style={{
                color: 'var(--fg-1)',
                fontSize: 14,
                padding: 0,
                textAlign: 'left',
                transition: 'color var(--t-fast)',
              }}
              onMouseEnter={(e) => e.currentTarget.style.color = 'var(--accent)'}
              onMouseLeave={(e) => e.currentTarget.style.color = 'var(--fg-1)'}
            >{it}</button>
          </li>
        ))}
      </ul>
    </div>
  );
}

Object.assign(window, { Header, Footer, Logo, LangSwitch });
