/* HLiD — Hero & Pillar sections */
const { useState, useEffect, useRef } = React;

/* Minimal in-view hook */
function useInView(threshold = 0.2) {
  const ref = useRef(null);
  const [inView, setInView] = useState(false);
  useEffect(() => {
    if (!ref.current) return;
    const io = new IntersectionObserver(([e]) => e.isIntersecting && setInView(true), { threshold });
    io.observe(ref.current);
    return () => io.disconnect();
  }, [threshold]);
  return [ref, inView];
}

/* Number tick-up */
function Counter({ to, suffix = '', prefix = '', duration = 1600 }) {
  const [ref, inView] = useInView(0.4);
  const [n, setN] = useState(0);
  useEffect(() => {
    if (!inView) return;
    const prefersReduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    if (prefersReduced) { setN(to); return; }
    const start = performance.now();
    let raf;
    const tick = (now) => {
      const p = Math.min(1, (now - start) / duration);
      const eased = 1 - Math.pow(1 - p, 3);
      setN(Math.floor(to * eased));
      if (p < 1) raf = requestAnimationFrame(tick);
      else setN(to);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [inView, to, duration]);
  return <span ref={ref}>{prefix}{n.toLocaleString('en-US')}{suffix}</span>;
}

/* Reveal wrapper */
function Reveal({ children, delay = 0, as: Tag = 'div', className = '' }) {
  const [ref, inView] = useInView(0.15);
  return (
    <Tag
      ref={ref}
      className={className}
      style={{
        opacity: inView ? 1 : 0,
        transform: inView ? 'translateY(0)' : 'translateY(12px)',
        transition: `opacity 600ms cubic-bezier(0.22,1,0.36,1) ${delay}ms, transform 600ms cubic-bezier(0.22,1,0.36,1) ${delay}ms`
      }}
    >
      {children}
    </Tag>
  );
}

/* ------------ NAV ------------ */
function TopNav() {
  const { locale, setLocale, t } = useT();
  return (
    <nav className="fixed top-0 left-0 right-0 z-50 bg-bg/70 backdrop-blur-md border-b border-border">
      <div className="max-w-7xl mx-auto px-6 md:px-8 h-14 flex items-center gap-8">
        <a href="#top" className="flex items-center gap-2.5 focus-ring shrink-0">
          <img src="assets/logo-square.png" alt="HLiD" className="w-6 h-6 object-contain block shrink-0" />
          <span className="font-display font-bold text-[15px] tracking-tight leading-none">HLiD</span>
        </a>
        <div className="hidden md:flex items-center gap-7 text-[13px] text-fg-muted leading-none">
          <a href="#problem" className="hover:text-fg transition-colors">{t('nav.product')}</a>
          <a href="#workflow" className="hover:text-fg transition-colors">{t('nav.workflow')}</a>
          <a href="#observability" className="hover:text-fg transition-colors">{t('nav.observability')}</a>
          <a href="#integrations" className="hover:text-fg transition-colors">{t('nav.integrations')}</a>
          <a href="#case" className="hover:text-fg transition-colors">{t('nav.customers')}</a>
        </div>
        <div className="flex-1" />
        <div className="hidden sm:flex items-center gap-1.5 font-mono text-[10px] uppercase tracking-[0.2em] text-signal leading-none">
          <span className="relative w-1.5 h-1.5 rounded-full bg-signal">
            <span className="absolute inset-0 rounded-full bg-signal animate-ping opacity-60"/>
          </span>
          {t('nav.live')}
        </div>
        <div className="flex items-center border border-border rounded-[3px] font-mono text-[10px] tracking-[0.15em] leading-none">
          {['EN','DE'].map(l => (
            <button key={l} onClick={() => setLocale(l)}
              className={`px-2 py-1.5 transition-colors focus-ring ${locale === l ? 'text-fg bg-bg-elevated' : 'text-fg-subtle hover:text-fg'}`}>
              {l}
            </button>
          ))}
        </div>
        <a href="#next" className="hidden md:inline-block px-4 py-1.5 bg-fg text-bg font-mono text-[11px] uppercase tracking-[0.15em] rounded-[3px] hover:bg-fg/90 transition-colors focus-ring leading-none">{t('nav.cta')}</a>
      </div>
    </nav>
  );
}

/* ------------ HERO ------------ */
function Hero() {
  const { t } = useT();
  const videoRef = useRef(null);
  const [muted, setMuted] = useState(true);
  const [chromeVisible, setChromeVisible] = useState(false);

  useEffect(() => {
    // Reveal overlay text after 4s OR on first scroll — whichever first.
    const tRef = setTimeout(() => setChromeVisible(true), 4000);
    const onScroll = () => { if (window.scrollY > 30) setChromeVisible(true); };
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => { clearTimeout(tRef); window.removeEventListener('scroll', onScroll); };
  }, []);

  const toggleMute = () => {
    if (!videoRef.current) return;
    videoRef.current.muted = !videoRef.current.muted;
    setMuted(videoRef.current.muted);
  };

  return (
    <section id="top" className="relative w-full overflow-hidden bg-black" style={{ height: '100svh', minHeight: '560px' }}>
      <video
        ref={videoRef}
        className="absolute inset-0 w-full h-full object-cover"
        src="assets/hero.mp4"
        autoPlay muted loop playsInline
        preload="metadata"
        poster="assets/hero-poster.jpg"
        aria-label={t('hero.videoAria')}
      >
      </video>

      {/* Protection gradient bottom-up */}
      <div className="absolute inset-0 bg-gradient-to-t from-bg via-bg/20 to-transparent pointer-events-none" />
      <div className="absolute inset-0 bg-gradient-to-b from-bg/50 via-transparent to-transparent pointer-events-none" />

      {/* Top micro-caption */}
      <div
        className="absolute top-20 left-6 md:left-8 font-mono text-[10px] uppercase tracking-[0.22em] text-fg-muted pointer-events-none"
        style={{ opacity: chromeVisible ? 1 : 0, transition: 'opacity 800ms ease-out' }}
      >
        <div className="flex items-center gap-3">
          <span className="w-6 h-px bg-fg-faint" />
          {t('hero.caption')}
        </div>
      </div>

      {/* Wordmark bottom-left */}
      <div
        className="absolute bottom-10 md:bottom-14 left-6 md:left-10 pointer-events-none"
        style={{ opacity: chromeVisible ? 1 : 0, transform: chromeVisible ? 'translateY(0)' : 'translateY(8px)', transition: 'opacity 900ms ease-out, transform 900ms ease-out' }}
      >
        <div className="font-display font-bold text-fg leading-none" style={{ fontSize: 'clamp(4rem, 11vw, 10rem)', letterSpacing: '-0.045em' }}>
          HLiD<span className="text-amber">.</span>
        </div>
        <div className="mt-4 font-mono text-[11px] md:text-xs uppercase tracking-[0.3em] text-fg-muted">
          {t('hero.tagline')}
        </div>
      </div>

      {/* CTA bottom-right */}
      <div
        className="absolute bottom-10 md:bottom-14 right-6 md:right-10 flex items-end gap-4"
        style={{ opacity: chromeVisible ? 1 : 0, transform: chromeVisible ? 'translateY(0)' : 'translateY(8px)', transition: 'opacity 900ms ease-out 200ms, transform 900ms ease-out 200ms' }}
      >
        <div className="hidden md:block text-right">
          <div className="font-mono text-[10px] uppercase tracking-[0.22em] text-fg-subtle mb-2">{t('hero.stamps')}</div>
        </div>
        <a href="#next" className="group inline-flex items-center gap-3 bg-fg text-bg px-5 py-3 font-mono text-[11px] uppercase tracking-[0.2em] rounded-[3px] hover:bg-fg/90 transition-colors focus-ring">
          {t('hero.cta')}
          <svg width="14" height="10" viewBox="0 0 14 10" fill="none" className="transition-transform group-hover:translate-x-0.5">
            <path d="M1 5h12M8 1l4 4-4 4" stroke="currentColor" strokeWidth="1.4" strokeLinecap="square"/>
          </svg>
        </a>
      </div>

      {/* Mute toggle — always visible */}
      <button
        onClick={toggleMute}
        className="absolute bottom-6 right-6 md:top-20 md:bottom-auto md:right-8 z-20 flex items-center gap-2 bg-bg/70 backdrop-blur-md border border-border text-fg-muted hover:text-fg hover:border-border-strong px-3 py-2 rounded-[3px] font-mono text-[10px] uppercase tracking-[0.2em] transition-colors focus-ring"
        aria-label={muted ? t('hero.soundOn') : t('hero.soundOff')}
      >
        {muted ? (
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"><path d="M3 9v6h4l5 4V5L7 9H3z"/><line x1="23" y1="9" x2="17" y2="15"/><line x1="17" y1="9" x2="23" y2="15"/></svg>
        ) : (
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"><path d="M3 9v6h4l5 4V5L7 9H3z"/><path d="M15.5 8.5a5 5 0 010 7"/><path d="M18.5 5.5a9 9 0 010 13"/></svg>
        )}
        {muted ? t('hero.soundOff') : t('hero.soundOn')}
      </button>

      {/* Scroll cue */}
      <div
        className="absolute bottom-4 left-1/2 -translate-x-1/2 font-mono text-[9px] uppercase tracking-[0.3em] text-fg-subtle hidden md:flex items-center gap-2"
        style={{ opacity: chromeVisible ? 0.6 : 0, transition: 'opacity 1000ms ease-out' }}
      >
        <span>{t('hero.scroll')}</span>
        <span className="w-px h-6 bg-fg-faint relative overflow-hidden">
          <span className="absolute inset-x-0 top-0 h-2 bg-fg" style={{ animation: 'scrollCue 2.2s ease-in-out infinite' }}/>
        </span>
      </div>
      <style>{`@keyframes scrollCue { 0%{transform:translateY(-100%)} 100%{transform:translateY(600%)} }`}</style>
    </section>
  );
}

/* ------------ THREE PILLARS BAR ------------ */
function Pillars() {
  const { t } = useT();
  const items = [
    ['01', t('pillars.01.title'), t('pillars.01.body')],
    ['02', t('pillars.02.title'), t('pillars.02.body')],
    ['03', t('pillars.03.title'), t('pillars.03.body')],
  ];
  return (
    <section className="relative border-t border-border bg-bg">
      <div className="max-w-7xl mx-auto px-6 md:px-8 py-14 md:py-20">
        <div className="grid grid-cols-1 md:grid-cols-3 divide-y md:divide-y-0 md:divide-x divide-border">
          {items.map(([n, t, d], i) => (
            <Reveal key={n} delay={i * 80}>
              <div className="py-8 md:py-0 md:px-8 first:md:pl-0 last:md:pr-0">
                <div className="font-mono text-[11px] tracking-[0.22em] uppercase text-fg-subtle mb-6">{n}</div>
                <div className="font-display font-bold text-[28px] md:text-[32px] tracking-tighter text-fg leading-[1.05] mb-3">{t}</div>
                <p className="text-[14px] text-fg-muted leading-relaxed max-w-sm">{d}</p>
              </div>
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Hero, TopNav, Pillars, Counter, Reveal, useInView });
