const { useState: useS_t, useEffect: useE_t, useRef: useR_t } = React;

// Featured agent — full-card character image with info overlaid on top.
// PRIYA gets a video; SURESH gets an image (looked up via AGENT_PHOTOS in primitives).
function FeaturedAgentCard({ a }) {
  const { t } = useLang();
  const [open, setOpen] = useS_t(false);
  const [hovering, setHovering] = useS_t(false);
  const videoRef = useR_t(null);
  const playedOnce = useR_t(false);
  const photo = (typeof AGENT_PHOTOS !== 'undefined') ? AGENT_PHOTOS[a.name] : null;

  // Play once on mount; loop only while hovering.
  useE_t(() => {
    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);
    try { v.currentTime = 0; v.play().catch(() => {}); } catch (e) {}
    return () => v.removeEventListener('ended', onEnded);
  }, []);

  useE_t(() => {
    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]);

  return (
    <Tilt max={8} scale={1.02} idle>
      <div
        onMouseEnter={() => setHovering(true)}
        onMouseLeave={() => setHovering(false)}
        className="relative rounded-3xl overflow-hidden h-full flex flex-col"
        style={{
          minHeight: 520,
          background: `linear-gradient(180deg, #0a0a14, #06060B)`,
          border: '1px solid rgba(255,255,255,0.08)',
          boxShadow: `0 24px 60px -30px ${a.accent}55, 0 1px 0 rgba(255,255,255,0.04) inset`,
        }}
      >
        {/* Background media — fills entire 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={a.name}
              style={{ width: '100%', height: '100%', objectFit: 'cover', objectPosition: 'center 18%' }}
            />
          ) : (
            <div style={{
              width: '100%', height: '100%',
              background: `radial-gradient(120% 80% at 50% 30%, ${a.accent}40, transparent 60%), linear-gradient(180deg, #1a1a26, #06060B)`,
            }} />
          )}
        </div>

        {/* Brand wash that picks up the agent accent */}
        <div className="absolute inset-0 pointer-events-none" style={{
          background: `radial-gradient(140% 80% at 50% 20%, ${a.accent}22, transparent 55%)`,
        }} />

        {/* Bottom gradient so text on the lower half stays readable */}
        <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) 28%, rgba(6,6,11,0) 45%, rgba(6,6,11,0.85) 100%)`,
        }} />

        {/* TOP — status row */}
        <div className="relative z-10 p-5 md:p-6 flex items-start justify-between">
          <div className="mono text-[10px] tracking-widest text-white/70" style={{ textShadow: '0 1px 8px rgba(0,0,0,0.6)' }}>
            AGENT_ID · {a.id.toUpperCase().padStart(3, '0')}
          </div>
          <div className="flex items-center gap-1.5 mono text-[10px] tracking-widest" style={{ color: a.accent, textShadow: `0 0 10px ${a.accent}66` }}>
            <span className="w-1.5 h-1.5 rounded-full" style={{ background: a.accent, boxShadow: `0 0 8px ${a.accent}` }}></span>
            LIVE
          </div>
        </div>

        {/* spacer pushes the info block to the bottom */}
        <div className="flex-1" />

        {/* BOTTOM — info block, image fully visible behind */}
        <div className="relative z-10 p-5 md:p-6 pt-2">
          <h3 className="text-3xl md:text-4xl font-display font-semibold text-white" style={{ textShadow: '0 2px 18px rgba(0,0,0,0.7)' }}>
            {a.name}
          </h3>
          <div className="text-white/85 text-sm mt-1" style={{ textShadow: '0 2px 12px rgba(0,0,0,0.7)' }}>
            {t(a.roleKey)}
          </div>
          <div className="flex gap-2 mt-3 flex-wrap">
            {a.tags.map((tg) => (
              <span key={tg} className="mono text-[10px] tracking-widest px-2.5 py-1 rounded-md text-white/85"
                style={{ background: 'rgba(0,0,0,0.45)', backdropFilter: 'blur(6px)', border: '1px solid rgba(255,255,255,0.14)' }}>
                {tg}
              </span>
            ))}
          </div>

          <div className="overflow-hidden transition-all duration-500" style={{ maxHeight: open ? 360 : 0, opacity: open ? 1 : 0 }}>
            <div className="mt-4 rounded-xl p-4" style={{ background: 'rgba(6,6,11,0.65)', border: '1px solid rgba(255,255,255,0.10)', backdropFilter: 'blur(12px)' }}>
              <ul className="space-y-2">
                {a.skillKeys.map((sk, i) => (
                  <li key={i} className="flex items-start gap-2.5 text-[13px] text-white/85">
                    <span className="mt-1.5 w-1.5 h-1.5 rounded-full flex-shrink-0" style={{ background: a.accent, boxShadow: `0 0 6px ${a.accent}` }}></span>
                    <span>{t(sk)}</span>
                  </li>
                ))}
              </ul>
            </div>
          </div>

          <button
            data-hot
            onClick={() => setOpen(!open)}
            className="mt-4 w-full text-[13px] font-medium py-2.5 rounded-lg border transition-all"
            style={{
              borderColor: open ? a.accent : 'rgba(255,255,255,0.18)',
              color: open ? a.accent : 'white',
              background: open ? `${a.accent}14` : 'rgba(0,0,0,0.35)',
              backdropFilter: 'blur(8px)',
              textShadow: '0 1px 6px rgba(0,0,0,0.6)',
            }}
          >
            {open ? t('team_show_less') : t('team_learn_more')}
          </button>
        </div>
      </div>
    </Tilt>
  );
}

function MiniAgentTile({ name, roleKey, hue }) {
  const { t } = useLang();
  return (
    <Tilt max={14} scale={1.05}>
      <div className="glass rounded-2xl p-4 flex flex-col items-center text-center" style={{ minHeight: 150 }}>
        <AgentAvatar name={name} hue={hue} size="sm" />
        <div className="text-sm font-display font-semibold text-white mt-3">{name}</div>
        <div className="text-[11px] text-white/50 mt-0.5 leading-tight">{t(roleKey)}</div>
      </div>
    </Tilt>
  );
}

function DeptAccordion({ d }) {
  const { t } = useLang();
  const [open, setOpen] = useS_t(false);
  const tone = d.badgeTone === 'cyan' ? { c: '#00F0FF', bg: 'rgba(0,240,255,0.10)' } : { c: '#8B5CF6', bg: 'rgba(139,92,246,0.10)' };
  return (
    <div className={`glass rounded-2xl p-6 ${open ? 'open' : ''}`}>
      <button
        data-hot
        onClick={() => setOpen(!open)}
        className="w-full flex items-center justify-between text-left"
      >
        <div className="flex items-center gap-4">
          <div className="mono text-xs text-white/40 w-8">{String(d.agents.length).padStart(2, '0')}</div>
          <div>
            <div className="text-xl md:text-2xl font-display font-semibold text-white">{t(d.nameKey)}</div>
            <div className="mono text-[10px] tracking-widest text-white/40 mt-1">{d.agents.length} {t('team_agents_label')}</div>
          </div>
        </div>
        <div className="flex items-center gap-3">
          <span className="mono text-[10px] tracking-widest px-2.5 py-1 rounded-md" style={{ color: tone.c, background: tone.bg, border: `1px solid ${tone.c}33` }}>{t(d.badgeKey)}</span>
          <svg className="chev w-5 h-5 text-white/60" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><polyline points="6 9 12 15 18 9"/></svg>
        </div>
      </button>

      <div className="overflow-hidden transition-all duration-500" style={{ maxHeight: open ? 1600 : 0, opacity: open ? 1 : 0 }}>
        <div className="hairline my-5"></div>
        <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-3">
          {d.agents.map(([n, rKey], i) => (
            <MiniAgentTile key={n} name={n} roleKey={rKey} hue={(i * 37 + (d.id.length * 30)) % 360} />
          ))}
        </div>
      </div>
    </div>
  );
}

function TeamSection() {
  const { t } = useLang();
  return (
    <section id="team" data-screen-label="04 AI Team" className="relative py-24 md:py-32">
      <div className="mx-auto max-w-7xl px-6 md:px-10">
        <SectionHeader
          tag={t('team_tag')}
          title={t('team_title')}
          subtitle={t('team_sub')}
        />

        <div className="grid md:grid-cols-2 gap-5 reveal max-w-4xl mx-auto">
          {FEATURED_AGENTS.map((a) => <FeaturedAgentCard key={a.id} a={a} />)}
        </div>

        <div className="mt-20 reveal">
          <div className="flex items-end justify-between mb-6 flex-wrap gap-4">
            <div>
              <div className="sec-tag mb-2">{t('team_full_tag')}</div>
              <h3 className="text-2xl md:text-3xl font-display font-semibold text-white">{t('team_full_title')}</h3>
            </div>
            <div className="mono text-xs text-white/40">{t('team_tap')}</div>
          </div>
          <div className="space-y-3">
            {ALL_DEPARTMENTS.map((d) => <DeptAccordion key={d.id} d={d} />)}
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { TeamSection });
