// Middle sections: Showreel, Audio, Clients
function ShowreelGrid({ content }) {
  const [playing, setPlaying] = useState(null);
  const hoverTimers = useRef({});
  const videoRefs = useRef({});

  const onEnter = (idx) => {
    clearTimeout(hoverTimers.current[idx]);
    hoverTimers.current[idx] = setTimeout(() => {
      setPlaying(idx);
      const v = videoRefs.current[idx];
      if (v) { v.currentTime = 0; v.play().catch(() => {}); }
    }, 180);
  };
  const onLeave = (idx) => {
    clearTimeout(hoverTimers.current[idx]);
    const v = videoRefs.current[idx];
    if (v) v.pause();
    if (playing === idx) setPlaying(null);
  };

  // Placeholder thumbs — use deterministic SVG gradient patterns
  const thumbBg = (i, kunde) => {
    const hues = [12, 28, 210, 150, 340, 260];
    const h = hues[i % hues.length];
    return `linear-gradient(135deg,
      hsl(${h}, 28%, 28%) 0%,
      hsl(${h}, 38%, 14%) 50%,
      hsl(${(h + 40) % 360}, 30%, 20%) 100%)`;
  };

  return (
    <section className="section" id="showreel">
      <div className="container">
        <div className="section-head">
          <div className="side">
            {content.side.map((s, i) => (
              <span key={i} className={i === 0 ? "num" : ""}>{s}</span>
            ))}
          </div>
          <div>
            <RevealWords as="h2" parts={content.title} />
            <Reveal as="p" style={{ color: "var(--muted)", marginTop: 20, maxWidth: "52ch" }}>
              {content.intro}
            </Reveal>
          </div>
        </div>

        <div className="video-grid">
          {content.videos.map((v, i) => (
            <Reveal
              as="article"
              key={i}
              className={`video-card ${v.featured ? "featured" : ""} ${playing === i ? "playing" : ""}`}
              onMouseEnter={() => onEnter(i)}
              onMouseLeave={() => onLeave(i)}
            >
              <div className="thumb" style={{ background: thumbBg(i, v.kunde) }}>
                <PlaceholderArt seed={i} />
              </div>
              {v.video && (
                <video
                  ref={(el) => { videoRefs.current[i] = el; }}
                  src={v.video}
                  muted
                  loop
                  playsInline
                  preload="metadata"
                />
              )}
              <div className="overlay">
                <div className="top">
                  <span>{v.kunde} · {v.typ}</span>
                  <span>{v.jahr}</span>
                </div>
                <div>
                  <div className="play"><Icon.Play /></div>
                </div>
                <div className="meta">
                  <h4>{v.title}</h4>
                  <span className="dur">{v.dur}</span>
                </div>
              </div>
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
}

function PlaceholderArt({ seed = 0 }) {
  // Abstract studio-ish SVG, not literal
  const patterns = [
    <g><rect x="40" y="60" width="120" height="3" fill="#fff" opacity=".15"/><rect x="40" y="70" width="80" height="3" fill="#fff" opacity=".1"/></g>,
    <g><circle cx="50%" cy="50%" r="36" fill="none" stroke="#fff" strokeWidth="1" opacity=".22"/><circle cx="50%" cy="50%" r="56" fill="none" stroke="#fff" strokeWidth="1" opacity=".12"/></g>,
    <g>{Array.from({ length: 18 }).map((_, i) => <rect key={i} x={10 + i * 11} y={90 - (i * 3) % 40} width="4" height={20 + (i * 7) % 50} fill="#fff" opacity=".18"/>)}</g>,
    <g><path d="M20 100 Q 50 60 90 100 T 180 100" stroke="#fff" strokeWidth="1.2" fill="none" opacity=".3"/><path d="M20 120 Q 50 80 90 120 T 180 120" stroke="#fff" strokeWidth="1.2" fill="none" opacity=".18"/></g>,
    <g><rect x="60" y="60" width="4" height="80" fill="#fff" opacity=".2"/><rect x="72" y="50" width="4" height="100" fill="#fff" opacity=".28"/><rect x="84" y="70" width="4" height="60" fill="#fff" opacity=".18"/></g>,
    <g><polygon points="100,50 140,120 60,120" fill="none" stroke="#fff" strokeWidth="1" opacity=".22"/></g>,
  ];
  return (
    <svg width="100%" height="100%" viewBox="0 0 200 200" preserveAspectRatio="xMidYMid slice" style={{ position: "absolute", inset: 0 }}>
      {patterns[seed % patterns.length]}
    </svg>
  );
}

function AudioSamples({ content }) {
  const [cat, setCat] = useState(content.categories[0].id);
  const [playingId, setPlayingId] = useState(null);
  const audioRef = useRef(null);
  const tracks = content.tracks[cat] || [];

  const stopAudio = () => {
    const a = audioRef.current;
    if (a) { a.pause(); a.removeAttribute('src'); a.load(); }
    setPlayingId(null);
  };

  const togglePlay = (id, src) => {
    if (playingId === id) {
      stopAudio();
      return;
    }
    setPlayingId(id);
    if (!src) return;
    const a = audioRef.current;
    if (!a) return;
    a.src = src;
    a.play().catch(() => setPlayingId(null));
  };

  useEffect(() => () => stopAudio(), []);

  return (
    <section className="section" id="hoerproben">
      <div className="container">
        <div className="section-head">
          <div className="side">
            {content.side.map((s, i) => (
              <span key={i} className={i === 0 ? "num" : ""}>{s}</span>
            ))}
          </div>
          <RevealWords as="h2" parts={content.title} />
        </div>

        <Reveal>
          <div className="audio-tabs" role="tablist">
            {content.categories.map((c) => (
              <button
                key={c.id}
                role="tab"
                aria-selected={cat === c.id}
                className={`audio-tab ${cat === c.id ? "active" : ""}`}
                onClick={() => { setCat(c.id); stopAudio(); }}
              >
                {c.label} <span className="count">[{c.count}]</span>
              </button>
            ))}
          </div>

          <div className="audio-list">
            {tracks.map((t, i) => {
              const id = `${cat}-${i}`;
              const isPlaying = playingId === id;
              const hasFile = !!t.file;
              return (
                <div key={id} className={`audio-row ${isPlaying ? "playing" : ""} ${hasFile ? "has-file" : "no-file"}`}>
                  <button
                    className="audio-play"
                    aria-label={isPlaying ? "Pause" : "Play"}
                    title={hasFile ? "" : "Hörprobe folgt — Demo-Visual"}
                    onClick={() => togglePlay(id, t.file)}
                  >
                    {isPlaying ? <Icon.Pause /> : <Icon.Play />}
                  </button>
                  <div className="audio-title">
                    <b>{t.title}</b>
                    <span>{t.tag}</span>
                  </div>
                  <div className="audio-wave">
                    {isPlaying
                      ? <AnimatedWave height={36} bars={140} />
                      : <StaticWave height={36} bars={80} seed={i + 1 + cat.length * 3} />}
                  </div>
                  <div className="audio-dur">{t.dur}</div>
                </div>
              );
            })}
          </div>
          <audio
            ref={audioRef}
            preload="none"
            onEnded={() => setPlayingId(null)}
            style={{ display: 'none' }}
          />
        </Reveal>
      </div>
    </section>
  );
}

function Clients({ content }) {
  return (
    <section className="section" id="kunden">
      <div className="container">
        <div className="section-head">
          <div className="side">
            {content.side.map((s, i) => (
              <span key={i} className={i === 0 ? "num" : ""}>{s}</span>
            ))}
          </div>
          <RevealWords as="h2" parts={content.title} />
        </div>

        <Reveal>
          <div className="logos">
            {content.logos.map((l, i) => (
              <div key={i} className="logo" title={l.name}>
                <img
                  src={`/assets/logos/${l.slug}.png`}
                  alt={l.name}
                  loading="lazy"
                  onError={(e) => {
                    e.currentTarget.style.display = 'none';
                    const fallback = e.currentTarget.nextSibling;
                    if (fallback) fallback.style.display = 'inline';
                  }}
                />
                <span className="mark-text" style={{ display: 'none' }}>{l.name}</span>
                {l.project && (
                  <div className="hover-preview">
                    <span>▶ {l.project}</span>
                  </div>
                )}
              </div>
            ))}
          </div>
        </Reveal>
      </div>
    </section>
  );
}

Object.assign(window, { ShowreelGrid, AudioSamples, Clients });
