// ─── Shared components ────────────────────────────────────────────────────────

const { useState, useEffect, useRef } = React;

// Intersection observer hook for scroll animations
function useFadeUp(threshold = 0.15) {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const obs = new IntersectionObserver(
      ([entry]) => { if (entry.isIntersecting) { el.classList.add('visible'); obs.unobserve(el); } },
      { threshold }
    );
    obs.observe(el);
    return () => obs.disconnect();
  }, []);
  return ref;
}

// ─── Logo Mark ────────────────────────────────────────────────────────────────
function TesseraLogo({ size = 36 }) {
  const id = 'lg' + size;
  return (
    <svg width={size} height={size} viewBox="0 0 36 36" fill="none" xmlns="http://www.w3.org/2000/svg">
      <defs>
        <linearGradient id={id} x1="0" y1="0" x2="36" y2="36" gradientUnits="userSpaceOnUse">
          <stop offset="0%" stopColor="#10B981"/>
          <stop offset="50%" stopColor="#0891B2"/>
          <stop offset="100%" stopColor="#1D4ED8"/>
        </linearGradient>
      </defs>
      {/* Back square */}
      <rect x="8" y="2" width="22" height="22" rx="4" fill={`url(#${id})`} opacity="0.7"/>
      {/* Front square */}
      <rect x="2" y="10" width="22" height="22" rx="4" fill={`url(#${id})`}/>
      {/* Intersection highlight */}
      <rect x="8" y="10" width="16" height="14" rx="2" fill="white" opacity="0.18"/>
    </svg>
  );
}

// ─── Wordmark ─────────────────────────────────────────────────────────────────
function Wordmark({ light = false }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10, textDecoration: 'none' }}>
      <TesseraLogo size={32} />
      <div style={{ display: 'flex', flexDirection: 'column', lineHeight: 1 }}>
        <span style={{
          fontFamily: 'var(--font)',
          fontWeight: 700,
          fontSize: 15,
          letterSpacing: '0.18em',
          color: light ? '#fff' : 'var(--text-dark)',
          textTransform: 'uppercase',
        }}>TESSERA</span>
        <span style={{
          fontFamily: 'var(--font)',
          fontWeight: 500,
          fontSize: 9,
          letterSpacing: '0.22em',
          background: 'var(--grad)',
          WebkitBackgroundClip: 'text',
          WebkitTextFillColor: 'transparent',
          backgroundClip: 'text',
          textTransform: 'uppercase',
          marginTop: 2,
        }}>ANALYTICS AI</span>
      </div>
    </div>
  );
}

// ─── Gradient Button ──────────────────────────────────────────────────────────
function GradBtn({ children, href = '#contact', onClick, small = false }) {
  const [hov, setHov] = useState(false);
  return (
    <a
      href={href}
      onClick={onClick}
      onMouseEnter={() => setHov(true)}
      onMouseLeave={() => setHov(false)}
      style={{
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        padding: small ? '9px 20px' : '13px 28px',
        background: hov
          ? 'linear-gradient(90deg, #0891B2, #1D4ED8, #10B981)'
          : 'linear-gradient(90deg, #10B981, #0891B2, #1D4ED8)',
        color: '#fff',
        fontFamily: 'var(--font)',
        fontWeight: 600,
        fontSize: small ? 13 : 14,
        letterSpacing: '0.02em',
        borderRadius: 6,
        textDecoration: 'none',
        border: 'none',
        cursor: 'pointer',
        transition: 'background 0.4s ease, box-shadow 0.3s ease, transform 0.2s ease',
        boxShadow: hov ? '0 0 24px rgba(8,145,178,0.45)' : '0 0 0 rgba(0,0,0,0)',
        transform: hov ? 'translateY(-1px)' : 'none',
        backgroundSize: '200%',
      }}
    >{children}</a>
  );
}

// ─── Ghost Button ─────────────────────────────────────────────────────────────
function GhostBtn({ children, href = '#examples', onClick, dark = true }) {
  const [hov, setHov] = useState(false);
  return (
    <a
      href={href}
      onClick={onClick}
      onMouseEnter={() => setHov(true)}
      onMouseLeave={() => setHov(false)}
      style={{
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        padding: '12px 27px',
        background: 'transparent',
        color: dark ? (hov ? '#fff' : 'rgba(255,255,255,0.8)') : (hov ? 'var(--text-dark)' : 'var(--text-muted)'),
        fontFamily: 'var(--font)',
        fontWeight: 500,
        fontSize: 14,
        letterSpacing: '0.02em',
        borderRadius: 6,
        textDecoration: 'none',
        border: dark ? '1px solid rgba(255,255,255,0.25)' : '1px solid #CBD5E1',
        cursor: 'pointer',
        transition: 'all 0.25s ease',
        borderColor: hov ? (dark ? 'rgba(255,255,255,0.5)' : '#94A3B8') : undefined,
      }}
    >{children}</a>
  );
}

// ─── Section Eyebrow ──────────────────────────────────────────────────────────
function Eyebrow({ children, light = false }) {
  return (
    <p style={{
      fontFamily: 'var(--font)',
      fontSize: 11,
      fontWeight: 600,
      letterSpacing: '0.2em',
      textTransform: 'uppercase',
      color: light ? 'var(--teal)' : 'var(--green)',
      marginBottom: 16,
    }}>{children}</p>
  );
}

// ─── Gradient underline heading ───────────────────────────────────────────────
function GradUnderline({ style: s }) {
  return <div style={{ width: 48, height: 3, background: 'var(--grad)', borderRadius: 2, marginTop: 14, ...s }} />;
}

// ─── Placeholder screenshot block ────────────────────────────────────────────
function ScreenPlaceholder({ label, dark = false, aspectRatio = '16/9' }) {
  return (
    <div style={{
      width: '100%',
      aspectRatio,
      borderRadius: 10,
      background: dark
        ? 'repeating-linear-gradient(45deg, #0d2638 0px, #0d2638 10px, #0a1e2c 10px, #0a1e2c 20px)'
        : 'repeating-linear-gradient(45deg, #e2e8f0 0px, #e2e8f0 10px, #f1f5f9 10px, #f1f5f9 20px)',
      border: dark ? '1px solid rgba(8,145,178,0.25)' : '1px solid #CBD5E1',
      display: 'flex',
      flexDirection: 'column',
      alignItems: 'center',
      justifyContent: 'center',
      gap: 8,
    }}>
      <div style={{
        fontFamily: 'monospace',
        fontSize: 11,
        color: dark ? 'rgba(8,145,178,0.6)' : '#94A3B8',
        textAlign: 'center',
        padding: '0 20px',
        lineHeight: 1.6,
      }}>{label}</div>
    </div>
  );
}

// ─── Check icon ───────────────────────────────────────────────────────────────
function CheckIcon({ color = '#10B981', size = 16 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 16 16" fill="none">
      <circle cx="8" cy="8" r="7.5" stroke={color} strokeOpacity="0.3"/>
      <path d="M5 8l2 2 4-4" stroke={color} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  );
}

// ─── Sticky Header ────────────────────────────────────────────────────────────
function Header() {
  const [scrolled, setScrolled] = useState(false);
  const [menuOpen, setMenuOpen] = useState(false);

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

  const navLinks = [
    { label: 'Problem', href: '#problem' },
    { label: 'What We Build', href: '#what-we-build' },
    { label: 'Examples', href: '#examples' },
    { label: 'How We Work', href: '#how-we-work' },
    { label: 'FAQ', href: '#faq' },
  ];

  return (
    <header style={{
      position: 'fixed', top: 0, left: 0, right: 0, zIndex: 1000,
      background: scrolled ? 'rgba(7,22,35,0.92)' : 'rgba(7,22,35,0.6)',
      backdropFilter: 'blur(16px)',
      WebkitBackdropFilter: 'blur(16px)',
      borderBottom: scrolled ? '1px solid rgba(8,145,178,0.15)' : '1px solid transparent',
      transition: 'background 0.3s, border-color 0.3s',
    }}>
      {/* Top gradient bar */}
      <div style={{ height: 2, background: 'linear-gradient(90deg, #10B981, #0891B2, #1D4ED8)' }} />
      <div className="container" style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', height: 60 }}>
        <a href="#" style={{ textDecoration: 'none' }}>
          <Wordmark light />
        </a>

        {/* Desktop nav */}
        <nav style={{ display: 'flex', alignItems: 'center', gap: 32 }} className="desktop-nav">
          {navLinks.map(l => (
            <a key={l.href} href={l.href} style={{
              color: 'rgba(255,255,255,0.65)',
              fontSize: 13,
              fontWeight: 500,
              textDecoration: 'none',
              letterSpacing: '0.01em',
              transition: 'color 0.2s',
            }}
              onMouseEnter={e => e.target.style.color = '#fff'}
              onMouseLeave={e => e.target.style.color = 'rgba(255,255,255,0.65)'}
            >{l.label}</a>
          ))}
        </nav>

        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <GradBtn href="#contact" small>Book a scoping call</GradBtn>
          {/* Hamburger */}
          <button
            onClick={() => setMenuOpen(!menuOpen)}
            style={{ display: 'none', background: 'none', border: 'none', cursor: 'pointer', padding: 4 }}
            className="hamburger"
            aria-label="Toggle menu"
          >
            <svg width="22" height="22" viewBox="0 0 22 22" fill="none">
              {menuOpen
                ? <><path d="M5 5l12 12M17 5L5 17" stroke="white" strokeWidth="1.8" strokeLinecap="round"/></>
                : <><path d="M3 6h16M3 11h16M3 16h16" stroke="white" strokeWidth="1.8" strokeLinecap="round"/></>
              }
            </svg>
          </button>
        </div>
      </div>

      {/* Mobile menu */}
      {menuOpen && (
        <div style={{
          background: 'rgba(7,22,35,0.98)',
          borderTop: '1px solid rgba(255,255,255,0.08)',
          padding: '16px 24px 24px',
        }}>
          {navLinks.map(l => (
            <a key={l.href} href={l.href} onClick={() => setMenuOpen(false)} style={{
              display: 'block', color: 'rgba(255,255,255,0.75)', fontSize: 15,
              fontWeight: 500, textDecoration: 'none', padding: '10px 0',
              borderBottom: '1px solid rgba(255,255,255,0.07)',
            }}>{l.label}</a>
          ))}
          <div style={{ marginTop: 20 }}>
            <GradBtn href="#contact">Book a scoping call</GradBtn>
          </div>
        </div>
      )}

      <style>{`
        @media (max-width: 768px) {
          .desktop-nav { display: none !important; }
          .hamburger { display: flex !important; }
        }
      `}</style>
    </header>
  );
}

Object.assign(window, {
  useFadeUp, TesseraLogo, Wordmark, GradBtn, GhostBtn,
  Eyebrow, GradUnderline, ScreenPlaceholder, CheckIcon, Header
});
