const { useState: useState_h, useRef: useRef_h, useEffect: useEffect_h } = React;

// Particle starfield + connecting lines on hero canvas
function Starfield() {
  const ref = useRef_h(null);
  useEffect_h(() => {
    const canvas = ref.current;
    if (!canvas) return;
    const ctx = canvas.getContext('2d');
    let w, h, dpr;
    const stars = [];
    const N = 110;

    function resize() {
      dpr = Math.min(window.devicePixelRatio || 1, 2);
      w = canvas.clientWidth;
      h = canvas.clientHeight;
      canvas.width = w * dpr;
      canvas.height = h * dpr;
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
    }
    resize();
    window.addEventListener('resize', resize);

    for (let i = 0; i < N; i++) {
      stars.push({
        x: Math.random() * w,
        y: Math.random() * h,
        z: Math.random() * 0.8 + 0.2,
        vx: (Math.random() - 0.5) * 0.15,
        vy: (Math.random() - 0.5) * 0.15,
        r: Math.random() * 1.4 + 0.3,
      });
    }

    let raf = 0;
    function tick() {
      ctx.clearRect(0, 0, w, h);
      // soft gradient overlay
      const grd = ctx.createRadialGradient(w * 0.7, h * 0.4, 0, w * 0.7, h * 0.4, Math.max(w, h) * 0.6);
      grd.addColorStop(0, 'rgba(0, 240, 255, 0.05)');
      grd.addColorStop(1, 'rgba(0,0,0,0)');
      ctx.fillStyle = grd;
      ctx.fillRect(0, 0, w, h);

      for (const s of stars) {
        s.x += s.vx;
        s.y += s.vy;
        if (s.x < 0) s.x = w;
        if (s.x > w) s.x = 0;
        if (s.y < 0) s.y = h;
        if (s.y > h) s.y = 0;
        ctx.beginPath();
        ctx.arc(s.x, s.y, s.r * s.z, 0, Math.PI * 2);
        ctx.fillStyle = `rgba(${180 + 75 * s.z}, ${230 + 25 * s.z}, 255, ${0.25 + s.z * 0.5})`;
        ctx.fill();
      }
      // connecting lines for nearby stars
      for (let i = 0; i < stars.length; i++) {
        for (let j = i + 1; j < stars.length; j++) {
          const a = stars[i], b = stars[j];
          const dx = a.x - b.x, dy = a.y - b.y;
          const d2 = dx * dx + dy * dy;
          if (d2 < 110 * 110) {
            const o = (1 - d2 / (110 * 110)) * 0.18;
            ctx.strokeStyle = `rgba(0, 240, 255, ${o})`;
            ctx.lineWidth = 0.6;
            ctx.beginPath();
            ctx.moveTo(a.x, a.y); ctx.lineTo(b.x, b.y);
            ctx.stroke();
          }
        }
      }
      raf = requestAnimationFrame(tick);
    }
    raf = requestAnimationFrame(tick);
    return () => { cancelAnimationFrame(raf); window.removeEventListener('resize', resize); };
  }, []);
  return <canvas ref={ref} className="absolute inset-0 w-full h-full" style={{ display: 'block' }} />;
}

// Live waveform visual for hero agent (decorative)
function Waveform({ bars = 28, color = '#00F0FF' }) {
  const [t, setT] = useState_h(0);
  useEffect_h(() => {
    let raf;
    let last = performance.now();
    const tick = (now) => {
      if (now - last > 60) { setT((x) => x + 1); last = now; }
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, []);
  return (
    <div className="flex items-center gap-[3px] h-12">
      {Array.from({ length: bars }).map((_, i) => {
        const h = 6 + Math.abs(Math.sin((t + i) * 0.45 + i)) * 38;
        return (
          <div key={i} style={{
            width: 3, height: h,
            background: color,
            borderRadius: 2,
            opacity: 0.4 + (h / 44) * 0.6,
            boxShadow: `0 0 8px ${color}88`,
          }}></div>
        );
      })}
    </div>
  );
}

function HeroAgentCard() {
  const { t } = useLang();
  const photo = (typeof AGENT_PHOTOS !== 'undefined') ? AGENT_PHOTOS['PRIYA'] : null;
  const [calling, setCalling] = useState_h(false);
  const [elapsed, setElapsed] = useState_h(0);
  const videoRef = useRef_h(null);
  const playedOnce = useRef_h(false);
  const [hovering, setHovering] = useState_h(false);

  useEffect_h(() => {
    if (!calling) { setElapsed(0); return; }
    const id = setInterval(() => setElapsed((s) => s + 1), 1000);
    return () => clearInterval(id);
  }, [calling]);

  // S38: bridge React UI state to webcall.js (LiveKit) events
  useEffect_h(() => {
    const onConnected = () => setCalling(true);
    const onEnded = () => setCalling(false);
    const onError = (e) => {
      setCalling(false);
      alert((e && e.detail) || 'Call failed');
    };
    const onTryCall = () => window.dispatchEvent(new CustomEvent('hunara-call-start'));
    window.addEventListener('hunara-call-connected', onConnected);
    window.addEventListener('hunara-call-ended', onEnded);
    window.addEventListener('hunara-call-error', onError);
    window.addEventListener('try-call', onTryCall);
    return () => {
      window.removeEventListener('hunara-call-connected', onConnected);
      window.removeEventListener('hunara-call-ended', onEnded);
      window.removeEventListener('hunara-call-error', onError);
      window.removeEventListener('try-call', onTryCall);
    };
  }, []);

  // Play video once on mount; pause when it ends; loop only while hovering.
  useEffect_h(() => {
    const v = videoRef.current;
    if (!v) return;
    const onEnded = () => {
      playedOnce.current = true;
      if (hovering) {
        try { v.currentTime = 0; v.play().catch(() => {}); } catch (e) {}
      } else {
        v.pause();
      }
    };
    v.addEventListener('ended', onEnded);
    // initial autoplay
    try { v.currentTime = 0; v.play().catch(() => {}); } catch (e) {}
    return () => v.removeEventListener('ended', onEnded);
  }, []);

  // React to hover changes once initial play is done
  useEffect_h(() => {
    const v = videoRef.current;
    if (!v) return;
    if (hovering) {
      try { v.play().catch(() => {}); } catch (e) {}
    } else if (playedOnce.current) {
      try { v.pause(); } catch (e) {}
    }
  }, [hovering]);

  const fmt = (s) => `${String(Math.floor(s/60)).padStart(2,'0')}:${String(s%60).padStart(2,'0')}`;

  return (
    <Tilt max={8} scale={1.02} idle>
      <div
        onMouseEnter={() => setHovering(true)}
        onMouseLeave={() => setHovering(false)}
        className="relative rounded-3xl overflow-hidden"
        style={{
          width: 'min(440px, 92vw)',
          height: 'min(620px, 78vh)',
          background: 'linear-gradient(180deg, #0a0a14, #06060B)',
          border: '1px solid rgba(255,255,255,0.10)',
          boxShadow: '0 30px 80px -30px rgba(0,240,255,0.45), 0 1px 0 rgba(255,255,255,0.05) inset',
        }}
      >
        {/* Background media — fills the whole card */}
        <div className="absolute inset-0">
          {photo && photo.video ? (
            <video
              ref={videoRef}
              src={photo.video}
              poster={photo.poster}
              muted autoPlay playsInline
              style={{ width: '100%', height: '100%', objectFit: 'cover', objectPosition: 'center 18%' }}
            />
          ) : photo && photo.src ? (
            <img src={photo.src} alt="PRIYA" style={{ width: '100%', height: '100%', objectFit: 'cover', objectPosition: 'center 18%' }} />
          ) : (
            <div style={{ width: '100%', height: '100%', background: 'radial-gradient(120% 80% at 50% 30%, #00F0FF40, transparent 60%), linear-gradient(180deg, #1a1a26, #06060B)' }} />
          )}
        </div>

        {/* Cyan brand wash */}
        <div className="absolute inset-0 pointer-events-none" style={{
          background: 'radial-gradient(140% 80% at 50% 18%, rgba(0,240,255,0.18), transparent 55%)',
        }} />

        {/* Bottom gradient for text legibility */}
        <div className="absolute inset-0 pointer-events-none" style={{
          background: 'linear-gradient(180deg, rgba(6,6,11,0.55) 0%, rgba(6,6,11,0) 22%, rgba(6,6,11,0) 38%, rgba(6,6,11,0.92) 100%)',
        }} />

        {/* TOP — status row */}
        <div className="relative z-10 flex items-center justify-between p-5 md:p-6">
          <div className="flex items-center gap-2 px-2.5 py-1 rounded-md" style={{ background: 'rgba(0,0,0,0.35)', backdropFilter: 'blur(8px)', border: '1px solid rgba(52,211,153,0.25)' }}>
            <span className="w-2 h-2 rounded-full bg-emerald-400" style={{ boxShadow: '0 0 12px #34d399' }}></span>
            <span className="mono text-[11px] tracking-widest text-emerald-300/95">{calling ? 'LIVE · ON-CALL' : 'AVAILABLE'}</span>
          </div>
          <span className="mono text-xs text-white/85 px-2 py-1 rounded-md" style={{ background: 'rgba(0,0,0,0.4)', backdropFilter: 'blur(8px)' }}>{fmt(elapsed)}</span>
        </div>

        {/* spacer */}
        <div style={{ height: 'calc(100% - 280px)' }} />

        {/* BOTTOM — info layer */}
        <div className="relative z-10 px-6 pb-6">
          <div className="mono text-[11px] tracking-widest text-cyan1" style={{ textShadow: '0 0 10px rgba(0,240,255,0.4), 0 2px 8px rgba(0,0,0,0.7)' }}>
            AGENT_ID · 001
          </div>
          <div className="mt-1 text-4xl md:text-5xl font-display font-semibold text-white tracking-tight" style={{ textShadow: '0 2px 18px rgba(0,0,0,0.75)' }}>
            PRIYA
          </div>
          <div className="text-white/85 text-base mt-1" style={{ textShadow: '0 2px 12px rgba(0,0,0,0.75)' }}>
            {t('priya_role')}
          </div>

          {/* tags */}
          <div className="flex flex-wrap items-center gap-2 mt-3">
            {['Voice', 'WhatsApp', 'CRM-sync', 'GU · HI · EN'].map((tg) => (
              <span key={tg} className="mono text-[10px] tracking-widest px-2.5 py-1 rounded-md text-white/90"
                style={{ background: 'rgba(0,0,0,0.45)', backdropFilter: 'blur(8px)', border: '1px solid rgba(255,255,255,0.14)' }}>
                {tg}
              </span>
            ))}
          </div>

          {/* Web call CTA */}
          <button
            data-hot
            onClick={() => {
              if (!calling) {
                setCalling(true);
                window.dispatchEvent(new CustomEvent('hunara-call-start'));
              } else {
                setCalling(false);
                window.dispatchEvent(new CustomEvent('hunara-call-end'));
              }
            }}
            className="mt-5 w-full py-3.5 rounded-xl font-medium flex items-center justify-center gap-2 transition-all"
            style={calling ? {
              background: 'linear-gradient(135deg, #ef4444, #b91c1c)',
              color: 'white',
              boxShadow: '0 10px 30px -8px rgba(239,68,68,0.55)',
              border: '1px solid rgba(255,255,255,0.15)',
            } : {
              background: 'linear-gradient(135deg, #00F0FF, #00B8D4)',
              color: '#001216',
              boxShadow: '0 10px 30px -8px rgba(0,240,255,0.65)',
              border: '1px solid rgba(255,255,255,0.25)',
            }}
          >
            {calling ? (
              <><span className="relative flex h-2 w-2"><span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-white opacity-75"></span><span className="relative inline-flex rounded-full h-2 w-2 bg-white"></span></span><span>End Call</span></>
            ) : (
              <><span>📞</span><span>Call Priya Now</span></>
            )}
          </button>

          {/* Live waveform when calling */}
          {calling && (
            <div className="mt-3 flex items-center justify-center">
              <Waveform color="#00F0FF" bars={32} />
            </div>
          )}
        </div>

        {/* floating particles */}
        <span className="float-dot" style={{ top: 28, right: 36, animationDelay: '0s' }}></span>
        <span className="float-dot" style={{ top: 80, right: 20, animationDelay: '1.2s', background: '#FFB800', boxShadow: '0 0 8px #FFB800' }}></span>
        <span className="float-dot" style={{ bottom: 60, left: 24, animationDelay: '2.4s', background: '#8B5CF6', boxShadow: '0 0 8px #8B5CF6' }}></span>
      </div>
    </Tilt>
  );
}

function Hero({ onBookDemo }) {
  const { t } = useLang();
  const headline = t('hero_headline');
  const [shown, setShown] = useState_h(0);
  useEffect_h(() => {
    setShown(0);
    const id = setInterval(() => setShown((n) => {
      if (n >= headline.length) { clearInterval(id); return n; }
      return n + 1;
    }), 28);
    return () => clearInterval(id);
  }, [headline]);

  return (
    <section id="home" className="relative min-h-screen overflow-hidden pt-28 md:pt-36 pb-20">
      <div className="absolute inset-0">
        <Starfield />
      </div>

      <div className="relative z-10 mx-auto max-w-7xl px-6 md:px-10 grid md:grid-cols-12 gap-10 md:gap-14 items-center">
        <div className="md:col-span-7">
          <div className="reveal sec-tag mb-6 flex items-center gap-2">
            <span className="inline-block w-6 h-px bg-cyan1 opacity-70"></span>
            <span>{t('hero_tag')}</span>
          </div>

          <h1 className="reveal text-5xl md:text-7xl lg:text-[88px] font-semibold leading-[1.02] tracking-tight text-white">
            <span style={{ background: 'linear-gradient(180deg, #fff 60%, rgba(255,255,255,0.55))', WebkitBackgroundClip: 'text', WebkitTextFillColor: 'transparent' }}>
              {headline.slice(0, shown)}
            </span>
            <span className="inline-block w-[3px] h-[1em] align-middle ml-1" style={{ background: 'var(--cyan)', boxShadow: '0 0 10px var(--cyan)' }}></span>
          </h1>

          <p className="reveal mt-6 text-lg md:text-xl text-white/65 max-w-2xl">
            {t('hero_sub')}
          </p>

          <div className="reveal mt-8 flex flex-wrap items-center gap-3">
            <Magnetic className="btn-primary px-6 py-3.5 rounded-xl font-medium flex items-center gap-2" onClick={() => window.dispatchEvent(new CustomEvent('hunara-call-start'))}>
              <span>📞</span><span>{t('hero_btn_call')}</span>
            </Magnetic>
            <Magnetic className="btn-whatsapp px-6 py-3.5 rounded-xl font-medium flex items-center gap-2">
              <span>💬</span><span>{t('hero_btn_wa')}</span>
            </Magnetic>
            <a href="#team" className="btn-ghost px-6 py-3.5 rounded-xl font-medium" data-hot>{t('hero_btn_meet')}</a>
          </div>

          <div className="reveal mt-12 grid grid-cols-3 gap-4 max-w-xl">
            <Stat n={4} label={t('hero_stat_lang')} suffix="" />
            <Stat n={24} label={t('hero_stat_uptime')} suffix="" prefixOk="x" />
            <Stat n={48} label={t('hero_stat_setup')} suffix="h" />
          </div>
        </div>

        <div className="md:col-span-5 flex md:justify-end justify-center reveal">
          <HeroAgentCard />
        </div>
      </div>

      {/* scroll indicator */}
      <div className="absolute left-1/2 -translate-x-1/2 bottom-6 z-10 flex flex-col items-center gap-2">
        <div className="scroll-arrow"></div>
        <span className="mono text-[10px] tracking-widest text-white/40">SCROLL</span>
      </div>
    </section>
  );
}

function Stat({ n, label, suffix = '', prefixOk = '' }) {
  return (
    <div>
      <div className="text-3xl md:text-4xl font-display font-semibold text-white">
        <Counter value={n} suffix={suffix} />
      </div>
      <div className="mono text-[11px] tracking-widest text-white/45 mt-1">{label}</div>
    </div>
  );
}

Object.assign(window, { Hero, Starfield });
