// mixes.jsx — Recent mixes section with real <audio> drop slots
// Each track row accepts drag-and-drop OR file picker → creates an object
// URL and plays it back with custom controls.

function fmtTime(s) {
  if (!s || !Number.isFinite(s)) return "0:00";
  const m = Math.floor(s / 60);
  const sec = Math.floor(s % 60);
  return `${m}:${sec.toString().padStart(2, "0")}`;
}

function TrackRow({ track, accent, idx }) {
  const audioRef = React.useRef(null);
  const fileInputRef = React.useRef(null);
  const [playing, setPlaying] = React.useState(false);
  const [time, setTime] = React.useState(0);
  const [duration, setDuration] = React.useState(0);
  const [src, setSrc] = React.useState(null);
  const [fileName, setFileName] = React.useState(null);
  const [dragOver, setDragOver] = React.useState(false);

  React.useEffect(() => {
    const a = audioRef.current;
    if (!a) return;
    const onPlay = () => setPlaying(true);
    const onPause = () => setPlaying(false);
    const onEnded = () => setPlaying(false);
    const onTime = () => setTime(a.currentTime);
    const onMeta = () => setDuration(a.duration || 0);
    a.addEventListener("play", onPlay);
    a.addEventListener("pause", onPause);
    a.addEventListener("ended", onEnded);
    a.addEventListener("timeupdate", onTime);
    a.addEventListener("loadedmetadata", onMeta);
    return () => {
      a.removeEventListener("play", onPlay);
      a.removeEventListener("pause", onPause);
      a.removeEventListener("ended", onEnded);
      a.removeEventListener("timeupdate", onTime);
      a.removeEventListener("loadedmetadata", onMeta);
    };
  }, [src]);

  // Pause others when one starts.
  React.useEffect(() => {
    if (!playing) return;
    const stopOthers = (e) => {
      if (e.detail === audioRef.current) return;
      audioRef.current?.pause();
    };
    document.addEventListener("__mix_play", stopOthers);
    return () => document.removeEventListener("__mix_play", stopOthers);
  }, [playing]);

  const toggle = () => {
    const a = audioRef.current;
    if (!a || !src) {
      // No source yet — open file picker.
      fileInputRef.current?.click();
      return;
    }
    if (playing) {
      a.pause();
    } else {
      document.dispatchEvent(new CustomEvent("__mix_play", { detail: a }));
      a.play().catch(() => {});
    }
  };

  const loadFile = (f) => {
    if (!f || !f.type.startsWith("audio/")) return;
    if (src) URL.revokeObjectURL(src);
    const url = URL.createObjectURL(f);
    setSrc(url);
    setFileName(f.name);
    setTime(0);
    setPlaying(false);
  };

  const onDrop = (e) => {
    e.preventDefault();
    setDragOver(false);
    loadFile(e.dataTransfer.files?.[0]);
  };

  const seek = (e) => {
    const a = audioRef.current;
    if (!a || !duration) return;
    const r = e.currentTarget.getBoundingClientRect();
    const pct = (e.clientX - r.left) / r.width;
    a.currentTime = Math.max(0, Math.min(duration, pct * duration));
  };

  const progressPct = duration ? (time / duration) * 100 : 0;
  const hasSrc = !!src;

  return (
    <div
      onDrop={onDrop}
      onDragOver={(e) => { e.preventDefault(); setDragOver(true); }}
      onDragLeave={() => setDragOver(false)}
      className="b-track-row"
      style={{
        display: "grid",
        gridTemplateColumns: "auto 64px 1fr 2fr 110px 110px",
        gap: 24,
        alignItems: "center",
        padding: "24px 28px",
        borderTop: idx === 0 ? "1px solid rgba(255,255,255,.1)" : "none",
        borderBottom: "1px solid rgba(255,255,255,.1)",
        background: dragOver ? "rgba(58,141,255,.08)" : (playing ? "rgba(255,255,255,.02)" : "transparent"),
        transition: "background .2s",
        position: "relative",
      }}
    >
      {/* track index */}
      <div style={{
        fontFamily: "'JetBrains Mono', monospace",
        fontSize: 12,
        color: "rgba(236,236,236,.4)",
        letterSpacing: 1.5,
        width: 28,
      }}>
        {String(idx + 1).padStart(2, "0")}
      </div>

      {/* play button */}
      <button
        onClick={toggle}
        aria-label={playing ? "Pause" : "Play"}
        style={{
          width: 56, height: 56,
          borderRadius: 28,
          background: playing ? accent : "rgba(255,255,255,.08)",
          border: hasSrc ? "none" : `1px dashed rgba(255,255,255,.25)`,
          color: playing ? "#0a0a0a" : "#fff",
          cursor: "pointer",
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          transition: "background .15s, transform .15s",
          flexShrink: 0,
        }}
        onMouseEnter={(e) => (e.currentTarget.style.transform = "scale(1.05)")}
        onMouseLeave={(e) => (e.currentTarget.style.transform = "scale(1)")}
      >
        {!hasSrc ? (
          <svg width="18" height="18" viewBox="0 0 18 18" fill="none" stroke="currentColor" strokeWidth="1.6">
            <path d="M9 2v14M2 9h14" strokeLinecap="round" />
          </svg>
        ) : playing ? (
          <svg width="14" height="16" viewBox="0 0 14 16" fill="currentColor"><rect x="0" y="0" width="5" height="16"/><rect x="9" y="0" width="5" height="16"/></svg>
        ) : (
          <svg width="14" height="16" viewBox="0 0 14 16" fill="currentColor"><path d="M1 0L13 8L1 16Z" /></svg>
        )}
      </button>

      {/* title + meta */}
      <div style={{ minWidth: 0 }}>
        <div style={{
          fontFamily: "'Fraunces', Georgia, serif",
          fontSize: 22,
          fontWeight: 400,
          letterSpacing: -0.4,
          color: "#ececec",
          marginBottom: 4,
          whiteSpace: "nowrap",
          overflow: "hidden",
          textOverflow: "ellipsis",
        }}>{track.title}</div>
        <div style={{
          fontFamily: "'JetBrains Mono', monospace",
          fontSize: 11,
          color: "rgba(236,236,236,.5)",
          letterSpacing: 1.2,
        }}>
          {track.date} · {track.genre}
          {fileName && (
            <span style={{ marginLeft: 10, color: accent }}>♪ {fileName}</span>
          )}
        </div>
      </div>

      {/* progress / drop zone */}
      <div
        onClick={hasSrc ? seek : () => fileInputRef.current?.click()}
        style={{
          height: 32,
          cursor: hasSrc ? "pointer" : "pointer",
          position: "relative",
          display: "flex",
          alignItems: "center",
        }}
      >
        {!hasSrc ? (
          <div style={{
            width: "100%",
            border: dragOver ? `1px solid ${accent}` : "1px dashed rgba(255,255,255,.18)",
            borderRadius: 4,
            padding: "8px 14px",
            fontFamily: "'JetBrains Mono', monospace",
            fontSize: 11,
            letterSpacing: 1.5,
            color: dragOver ? accent : "rgba(236,236,236,.4)",
            textTransform: "uppercase",
            textAlign: "center",
            transition: "border-color .15s, color .15s",
          }}>
            ↓ {track.dropHint || "Drop audio file"}
          </div>
        ) : (
          <div style={{ width: "100%", height: 4, background: "rgba(255,255,255,.08)", borderRadius: 2, position: "relative" }}>
            <div style={{
              position: "absolute",
              left: 0, top: 0,
              height: "100%",
              width: `${progressPct}%`,
              background: accent,
              borderRadius: 2,
              transition: "width .1s linear",
            }} />
            <div style={{
              position: "absolute",
              left: `${progressPct}%`,
              top: "50%",
              transform: "translate(-50%, -50%)",
              width: 10, height: 10,
              borderRadius: 5,
              background: accent,
              boxShadow: "0 0 0 3px rgba(58,141,255,.2)",
              opacity: playing ? 1 : 0.7,
            }} />
          </div>
        )}
      </div>

      {/* duration */}
      <div style={{
        fontFamily: "'JetBrains Mono', monospace",
        fontSize: 13,
        color: "rgba(236,236,236,.6)",
        textAlign: "right",
        fontVariantNumeric: "tabular-nums",
        letterSpacing: 0.5,
      }}>
        {hasSrc ? `${fmtTime(time)} / ${fmtTime(duration)}` : track.dur}
      </div>

      {/* download / external link icon */}
      <div style={{
        fontFamily: "'JetBrains Mono', monospace",
        fontSize: 11,
        color: "rgba(236,236,236,.4)",
        letterSpacing: 1.5,
        textAlign: "right",
      }}>
        SET {String(idx + 1).padStart(3, "0")}
      </div>

      <audio ref={audioRef} src={src || undefined} preload="metadata" />
      <input
        ref={fileInputRef}
        type="file"
        accept="audio/*"
        style={{ display: "none" }}
        onChange={(e) => loadFile(e.target.files?.[0])}
      />
    </div>
  );
}

function MixesKicker({ accent, children }) {
  return (
    <div style={{
      fontFamily: "'JetBrains Mono', monospace",
      fontSize: 12,
      letterSpacing: 2,
      color: accent,
      textTransform: "uppercase",
      display: "flex",
      alignItems: "center",
      gap: 10,
    }}>
      <span style={{ width: 24, height: 1, background: accent }} />
      <span>{children}</span>
    </div>
  );
}

function MixesSection({ t, accent, bg, bgAlt, mutedColor, fg }) {
  return (
    <section className="b-section b-mixes" style={{
      padding: "var(--b-pad-y) var(--b-pad-x)",
      background: bg,
      borderTop: "1px solid rgba(255,255,255,.06)",
      borderBottom: "1px solid rgba(255,255,255,.06)",
    }}>
      <div style={{
        display: "flex",
        justifyContent: "space-between",
        alignItems: "flex-end",
        marginBottom: 56,
        flexWrap: "wrap",
        gap: 24,
      }}>
        <div>
          <MixesKicker accent={accent}>{t.mixes.kicker}</MixesKicker>
          <h2 style={{
            fontFamily: "'Fraunces', Georgia, serif",
            fontSize: "clamp(48px, 7vw, 80px)",
            fontWeight: 400,
            lineHeight: 1,
            letterSpacing: -2,
            margin: "20px 0 0",
          }}>{t.mixes.title}</h2>
        </div>
        <p style={{
          fontSize: 14,
          color: mutedColor,
          maxWidth: 360,
          margin: 0,
          fontFamily: "'JetBrains Mono', monospace",
          letterSpacing: 0.3,
          lineHeight: 1.6,
        }}>
          <span style={{ color: accent }}>※</span> {t.mixes.note}
        </p>
      </div>

      <div style={{
        background: bgAlt,
        borderRadius: 8,
        border: "1px solid rgba(255,255,255,.06)",
        overflow: "hidden",
      }}>
        {t.mixes.tracks.map((tk, i) => (
          <TrackRow
            key={i}
            track={{ ...tk, dropHint: t.mixes.drop_hint }}
            idx={i}
            accent={accent}
          />
        ))}
      </div>
    </section>
  );
}

Object.assign(window, { MixesSection });
