// Team: Constellation map of 19 members + filter by school type + hover preview card
function TeamSection({ t, lang }) {
  const team = window.AstroniaData.team;
  const [filter, setFilter] = React.useState('ALL');
  const [selected, setSelected] = React.useState(null);
  const [hover, setHover] = React.useState(null); // { member, x, y } in container px

  const containerRef = React.useRef(null);

  // Hover-Card schließen, wenn Filter wechselt — sonst bleibt sie an einer leeren Position kleben
  React.useEffect(() => { setHover(null); }, [filter]);

  const positions = React.useMemo(() => [
    [12, 18], [22, 12], [32, 22], [42, 14], [52, 26], [10, 38], [24, 42], [38, 38], [50, 46],
    [62, 16], [74, 24], [86, 14], [70, 40], [82, 36], [90, 48], [60, 50],
    [22, 56], [44, 58], [70, 56],
  ], []);

  const visible = team.map((m, i) => ({ ...m, i, pos: positions[i] }))
    .filter(m => filter === 'ALL' || m.role === filter);

  const filters = [
    { id: 'ALL', label: t('teamFilterAll'), count: 19 },
    { id: 'AHS', label: 'AHS', count: 9 },
    { id: 'BMHS', label: 'BMHS', count: 7 },
    { id: 'BS', label: 'BS', count: 3 },
  ];

  const colorForRole = (r) => {
    if (r === 'AHS') return 'oklch(0.84 0.15 82)';
    if (r === 'BMHS') return 'oklch(0.72 0.17 45)';
    return 'oklch(0.65 0.20 305)';
  };

  const handleEnter = (m, e) => {
    const rect = containerRef.current.getBoundingClientRect();
    const dot = e.currentTarget.getBoundingClientRect();
    setHover({
      member: m,
      x: dot.left - rect.left + dot.width / 2,
      y: dot.top - rect.top,
      starHeight: dot.height,
      containerWidth: rect.width,
      containerHeight: rect.height,
    });
  };

  return (
    <section className="section">
      <div className="eyebrow">{t('teamEyebrow')}</div>
      <h2 style={{ fontSize: 'clamp(40px, 6vw, 72px)', lineHeight: 1.05, marginBottom: 18 }}>
        {t('teamTitle')}
      </h2>
      <p style={{ fontSize: 17, color: 'var(--ink-soft)', maxWidth: 600, marginBottom: 28 }}>
        {t('teamLead')}
      </p>

      <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', marginBottom: 28 }}>
        {filters.map(f => (
          <button key={f.id}
            onClick={() => setFilter(f.id)}
            style={{
              padding: '8px 16px', borderRadius: 999, fontSize: 13,
              fontFamily: 'inherit', fontWeight: 500, cursor: 'pointer',
              border: '1px solid var(--line)',
              background: filter === f.id ? 'var(--ink-bright)' : 'transparent',
              color: filter === f.id ? 'var(--bg-deep)' : 'var(--ink-soft)',
              transition: 'all .25s ease',
              display: 'inline-flex', alignItems: 'center', gap: 8,
            }}>
            {f.label}
            <span style={{
              fontSize: 11, padding: '2px 7px', borderRadius: 999,
              background: filter === f.id ? 'oklch(0.16 0.04 60 / 0.15)' : 'oklch(1 0 0 / 0.08)',
              color: 'inherit',
            }}>{f.count}</span>
          </button>
        ))}
      </div>

      <div ref={containerRef} style={{
        position: 'relative', width: '100%', aspectRatio: '16 / 9',
        marginBottom: 32,
      }}
      onMouseLeave={() => setHover(null)}>
       <div style={{
         position: 'absolute', inset: 0,
         background:
           'radial-gradient(ellipse at 30% 30%, oklch(0.30 0.16 290 / 0.32), transparent 55%),' +
           'radial-gradient(ellipse at 75% 75%, oklch(0.30 0.18 60 / 0.28), transparent 55%),' +
           'radial-gradient(ellipse at 50% 60%, oklch(0.18 0.08 270 / 0.7), oklch(0.10 0.05 268 / 0.6))',
         border: '1px solid oklch(0.84 0.15 82 / 0.25)',
         borderRadius: 28,
         overflow: 'hidden',
         boxShadow: '0 30px 80px -30px oklch(0 0 0 / 0.6), 0 0 0 1px oklch(0.84 0.15 82 / 0.05) inset',
       }}>
        {/* Distant background starfield */}
        <svg viewBox="0 0 1600 900" preserveAspectRatio="xMidYMid slice"
          style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', pointerEvents: 'none' }}>
          {Array.from({ length: 140 }).map((_, i) => {
            const cx = (i * 173 + 37) % 1600;
            const cy = (i * 91 + 53) % 900;
            const r = (i % 11 === 0) ? 1.8 : (i % 5 === 0 ? 1.2 : 0.7);
            return <circle key={i} cx={cx} cy={cy} r={r} fill="oklch(0.99 0.02 80)"
              opacity={0.18 + (i % 5) * 0.08}
              style={{ animation: `bgTw ${4 + (i % 5)}s ease-in-out ${(i % 9) * 0.3}s infinite` }} />;
          })}
          <style>{`@keyframes bgTw { 0%,100% { opacity: 1; } 50% { opacity: 0.25; } }`}</style>
        </svg>

        {/* Hero "19 ✦" mark — sits in the back layer of the canvas */}
        <div style={{
          position: 'absolute', inset: 0,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          pointerEvents: 'none', zIndex: 0,
        }}>
          <div style={{ textAlign: 'center', opacity: 0.10 }}>
            <div style={{
              fontFamily: '"Cormorant Garamond", serif', fontWeight: 400,
              fontSize: 'clamp(180px, 28vw, 360px)', lineHeight: 0.9,
              color: 'var(--gold)',
              letterSpacing: '-0.02em',
            }}>19</div>
          </div>
        </div>

        <svg viewBox="0 0 100 60" preserveAspectRatio="none" style={{
          position: 'absolute', inset: 0, width: '100%', height: '100%',
        }}>
          <defs>
            <linearGradient id="constLine" x1="0" y1="0" x2="1" y2="1">
              <stop offset="0" stopColor="oklch(0.84 0.15 82)" stopOpacity="0.0" />
              <stop offset="0.5" stopColor="oklch(0.84 0.15 82)" stopOpacity="0.55" />
              <stop offset="1" stopColor="oklch(0.65 0.20 305)" stopOpacity="0.0" />
            </linearGradient>
          </defs>
          {visible.map((m, idx) => {
            if (idx === 0) return null;
            const prev = visible[idx - 1];
            return (
              <line key={`c-${idx}`}
                x1={prev.pos[0]} y1={prev.pos[1]}
                x2={m.pos[0]} y2={m.pos[1]}
                stroke="url(#constLine)" strokeWidth="0.12"
                strokeDasharray="0.8 0.5"
                style={{ animation: `lineFade .8s ease ${idx * 0.05}s both` }} />
            );
          })}
          <style>{`@keyframes lineFade { from { opacity: 0; } to { opacity: 1; } }`}</style>
        </svg>

        {visible.map((m, idx) => (
          <button key={m.i}
            onClick={() => setSelected(m)}
            onMouseEnter={(e) => handleEnter(m, e)}
            style={{
              position: 'absolute',
              left: `${m.pos[0]}%`,
              top: `${m.pos[1] / 60 * 100}%`,
              transform: 'translate(-50%, -50%)',
              background: 'transparent', border: 'none', cursor: 'pointer', padding: 0,
              zIndex: 2,
              animation: `fadeUp .6s ease ${idx * 0.04}s both, gentleFloat ${4 + (idx % 5)}s ease-in-out ${idx * 0.2}s infinite`,
            }}>
            <div className="team-star" style={{
              width: 22, height: 22, borderRadius: '50%',
              background: `radial-gradient(circle, oklch(0.99 0.02 80) 0%, ${colorForRole(m.role)} 55%, transparent 78%)`,
              boxShadow: `0 0 22px ${colorForRole(m.role)}, 0 0 6px oklch(0.99 0.02 80)`,
              transition: 'transform .25s ease',
            }} />
            <div style={{
              fontSize: 9, letterSpacing: '0.12em', textTransform: 'uppercase',
              color: 'var(--ink-soft)', marginTop: 4, textAlign: 'center', whiteSpace: 'nowrap',
              transform: 'translateX(-50%)', position: 'absolute', left: '50%', top: '120%',
              textShadow: '0 1px 6px oklch(0.05 0.04 270)',
            }}>{m.name}</div>
          </button>
        ))}

        <ClusterLabel x="32%" y="8%" label="AHS" color="oklch(0.84 0.15 82)" />
        <ClusterLabel x="80%" y="8%" label="BMHS" color="oklch(0.72 0.17 45)" />
        <ClusterLabel x="46%" y="92%" label="BS" color="oklch(0.65 0.20 305)" />

        <style>{`
          @keyframes fadeUp { from { opacity: 0; transform: translate(-50%, -30%); } to { opacity: 1; transform: translate(-50%, -50%); } }
          @keyframes gentleFloat { 0%, 100% { transform: translate(-50%, -50%); } 50% { transform: translate(-50%, calc(-50% - 4px)); } }
          .team-star:hover { transform: scale(1.6); }
          @keyframes hoverIn { from { opacity: 0; } to { opacity: 1; } }
        `}</style>
       </div>

        {/* Hover preview card — sits in the outer container so it can extend past the canvas without being clipped */}
        {hover && (
          <HoverCard
            member={hover.member}
            x={hover.x}
            y={hover.y}
            starHeight={hover.starHeight}
            containerWidth={hover.containerWidth}
            containerHeight={hover.containerHeight}
            color={colorForRole(hover.member.role)}
            lang={lang}
          />
        )}
      </div>

      {/* Click detail card (persistent) */}
      {selected && (
        <div className="card" style={{
          display: 'flex', gap: 24, alignItems: 'center', flexWrap: 'wrap',
          animation: 'sectionIn .35s ease',
        }}>
          <PhotoPlaceholder size={96} color={colorForRole(selected.role)} photo={selected.photo} name={selected.name} />
          <div style={{ flex: 1, minWidth: 200 }}>
            <div style={{ fontSize: 11, letterSpacing: '0.2em', textTransform: 'uppercase', color: colorForRole(selected.role), marginBottom: 6 }}>
              {selected.role}{selected.rank ? ` · ${lang === 'de' ? 'Platz' : 'Rank'} ${selected.rank}` : ''}
            </div>
            <div style={{ fontFamily: '"Cormorant Garamond", serif', fontSize: 28 }}>{selected.name}</div>
          </div>
          <button className="btn" onClick={() => setSelected(null)} style={{ padding: '8px 16px', fontSize: 12 }}>×</button>
        </div>
      )}

      {/* === Team Video — appears AFTER constellation === */}
      <div style={{ marginTop: 72 }}>
        <TeamVideo t={t} lang={lang} />
      </div>

      <style>{`
        .member-card:hover {
          transform: translateY(-3px);
          box-shadow: 0 12px 32px -8px oklch(0 0 0 / 0.5);
        }
      `}</style>
    </section>
  );
}

function HoverCard({ member, x, y, starHeight = 22, containerWidth = 0, containerHeight = 0, color, lang }) {
  const W = 220;
  const ESTIMATED_H = 350; // photo (≈245) + padding (24) + meta (~80) + border
  const GAP = 12;

  const spaceAbove = y;
  const spaceBelow = containerHeight - (y + starHeight);
  // Prefer above; flip below only when there's clearly not enough room above
  const flipBelow = spaceAbove < ESTIMATED_H + GAP && spaceBelow > spaceAbove;

  // Clamp horizontally so the card never escapes the container sideways
  const halfW = W / 2;
  const minX = halfW + 8;
  const maxX = (containerWidth || 9999) - halfW - 8;
  const cardX = Math.max(minX, Math.min(maxX, x));

  const cardY = flipBelow ? y + starHeight + GAP : y - GAP;
  const transform = flipBelow ? 'translate(-50%, 0)' : 'translate(-50%, -100%)';

  return (
    <div style={{
      position: 'absolute', left: cardX, top: cardY,
      transform,
      width: W,
      pointerEvents: 'none',
      zIndex: 5,
      animation: 'hoverIn .22s cubic-bezier(.2,.9,.2,1) both',
    }}>
      <div style={{
        background: 'oklch(0.16 0.05 265 / 0.92)',
        backdropFilter: 'blur(18px) saturate(1.4)',
        WebkitBackdropFilter: 'blur(18px) saturate(1.4)',
        border: `1px solid ${color}`,
        borderRadius: 16,
        padding: 12,
        boxShadow: `0 12px 36px oklch(0 0 0 / 0.5), 0 0 28px ${color.replace(')', ' / 0.25)')}`,
      }}>
        <PhotoPlaceholder size={196} color={color} photo={member.photo} name={member.name} fullWidth />
        <div style={{ marginTop: 12, padding: '0 4px' }}>
          <div style={{
            fontSize: 10, letterSpacing: '0.22em', textTransform: 'uppercase',
            color: color, marginBottom: 4, fontWeight: 500,
          }}>{member.role}{member.rank ? ` · ${lang === 'de' ? 'Platz' : 'Rank'} ${member.rank}` : ''}</div>
          <div style={{
            fontFamily: '"Cormorant Garamond", serif', fontSize: 22, lineHeight: 1.1,
            color: 'var(--ink-bright)',
          }}>{member.name}</div>
        </div>
      </div>
      {/* Pointer notch — points toward the star (down when card is above, up when card is below) */}
      <div style={{
        position: 'absolute',
        ...(flipBelow ? { top: -6 } : { bottom: -6 }),
        left: '50%',
        transform: 'translateX(-50%) rotate(45deg)',
        width: 12, height: 12,
        background: 'oklch(0.16 0.05 265 / 0.92)',
        ...(flipBelow
          ? { borderLeft: `1px solid ${color}`, borderTop: `1px solid ${color}` }
          : { borderRight: `1px solid ${color}`, borderBottom: `1px solid ${color}` }),
      }}></div>
    </div>
  );
}

function PhotoPlaceholder({ size, color, photo, name, fullWidth }) {
  return (
    <div style={{
      width: fullWidth ? '100%' : size,
      aspectRatio: fullWidth ? '4 / 5' : '1 / 1',
      height: fullWidth ? undefined : size,
      borderRadius: fullWidth ? 12 : '50%',
      background: `linear-gradient(160deg, oklch(0.30 0.08 268), oklch(0.18 0.06 268))`,
      border: `1.5px solid ${color}`,
      position: 'relative', overflow: 'hidden',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      flexShrink: 0,
    }}>
      {photo ? (
        <img src={photo} alt={name || ''} loading="lazy"
          style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' }} />
      ) : (
        <>
          <svg viewBox="0 0 100 100" preserveAspectRatio="none" style={{
            position: 'absolute', inset: 0, width: '100%', height: '100%', opacity: 0.6,
          }}>
            {[[20,30],[60,15],[80,45],[35,70],[70,80],[15,85],[50,50],[88,72]].map(([cx,cy],i) => (
              <circle key={i} cx={cx} cy={cy} r="0.6" fill="oklch(0.95 0.05 85)" />
            ))}
          </svg>
          <div style={{
            position: 'relative', zIndex: 1, textAlign: 'center',
            fontFamily: '"Cormorant Garamond", serif',
          }}>
            <div style={{
              fontSize: fullWidth ? 44 : 28, color: color, lineHeight: 1, marginBottom: 4,
            }}>✦</div>
            <div style={{
              fontSize: fullWidth ? 10 : 9,
              letterSpacing: '0.25em', textTransform: 'uppercase',
              color: 'oklch(0.65 0.04 260)', fontFamily: 'Outfit, sans-serif',
            }}>Foto folgt</div>
          </div>
        </>
      )}
    </div>
  );
}

function ClusterLabel({ x, y, label, color }) {
  return (
    <div style={{
      position: 'absolute', left: x, top: y,
      transform: 'translate(-50%, -50%)',
      fontSize: 11, letterSpacing: '0.3em', textTransform: 'uppercase',
      color, fontWeight: 500,
      padding: '4px 10px',
      background: 'oklch(0.14 0.05 268 / 0.6)',
      borderRadius: 999,
      border: `1px solid ${color}`,
      pointerEvents: 'none',
    }}>{label}</div>
  );
}

Object.assign(window, { TeamSection });
