// Striped SVG placeholder media blocks (image / video / audio waveform)

const HUD_DEFAULT = "PLACEHOLDER";

function StripeFill({ hue = 0, sat = 0, variant = "diag" }) {
  // Returns a pair of subtle stripes + centered label slot
  const id = `p_${Math.random().toString(36).slice(2, 8)}`;
  return (
    <svg
      xmlns="http://www.w3.org/2000/svg"
      viewBox="0 0 100 100"
      preserveAspectRatio="none"
      style={{ position: "absolute", inset: 0, width: "100%", height: "100%" }}
    >
      <defs>
        <pattern id={id} patternUnits="userSpaceOnUse" width="6" height="6" patternTransform={variant === "diag" ? "rotate(45)" : "rotate(0)"}>
          <rect width="6" height="6" fill="#0A0A0A" />
          <line x1="0" y1="0" x2="0" y2="6" stroke="#141414" strokeWidth="1" />
        </pattern>
      </defs>
      <rect width="100" height="100" fill={`url(#${id})`} />
    </svg>
  );
}

function MediaPlaceholder({
  kind = "image",   // image | video | print
  ratio = "4x5",
  hud = HUD_DEFAULT,
  hudR,
  fn = ["file.tif", "—"],
  label = "Image — drop asset here",
  asset,           // optional real image src
  onCursor,
}) {
  const [hovered, setHovered] = React.useState(false);
  const cls = [
    "media",
    `media-ratio-${ratio}`,
    kind === "video" ? "is-video" : "",
    asset ? "has-asset" : "",
  ].join(" ");
  return (
    <div
      className={cls}
      onMouseEnter={() => { setHovered(true); onCursor && onCursor(true); }}
      onMouseLeave={() => { setHovered(false); onCursor && onCursor(false); }}
    >
      {asset ? (
        <img src={asset} alt={label} className="m-asset" />
      ) : (
        <>
          <StripeFill variant={kind === "video" ? "horiz" : "diag"} />
          <div style={{ position: "absolute", inset: 0, display: "flex", alignItems: "center", justifyContent: "center", pointerEvents: "none" }}>
            <div style={{ textAlign: "center", color: "#3A3A3A", fontSize: 10, letterSpacing: "0.18em", textTransform: "uppercase", maxWidth: "70%" }}>
              {label}
              <div style={{ marginTop: 8, color: "#2B2B2B", fontSize: 9 }}>
                {kind === "video" ? "[ HOVER TO AUTOPLAY ]" : kind === "print" ? "[ SCREEN PRINT ]" : "[ IMAGE ]"}
              </div>
            </div>
          </div>
        </>
      )}
      {/* corner markers */}
      <CornerMarks />
      <div className="m-hud">{hud}</div>
      {hudR && <div className="m-hud-r">{hudR}</div>}
      <div className="m-fn">
        <span>{fn[0]}</span>
        <span>{fn[1] || ""}</span>
      </div>
      {kind === "video" && <div className="m-play-ind">▶ {hovered ? "PLAYING" : "HOVER"}</div>}
    </div>
  );
}

function CornerMarks() {
  const s = { position: "absolute", width: 8, height: 8, borderColor: "#2B2B2B", borderStyle: "solid" };
  return (
    <>
      <span style={{ ...s, top: 0, left: 0, borderWidth: "1px 0 0 1px" }} />
      <span style={{ ...s, top: 0, right: 0, borderWidth: "1px 1px 0 0" }} />
      <span style={{ ...s, bottom: 0, left: 0, borderWidth: "0 0 1px 1px" }} />
      <span style={{ ...s, bottom: 0, right: 0, borderWidth: "0 1px 1px 0" }} />
    </>
  );
}

function AudioPlayer({ title = "untitled.wav", meta = "WAV · 44.1k · 02:14", dur = "02:14", seed = 1 }) {
  const [playing, setPlaying] = React.useState(false);
  const [pos, setPos] = React.useState(0);
  React.useEffect(() => {
    if (!playing) return;
    const iv = setInterval(() => {
      setPos((p) => (p + 1) % 60);
    }, 120);
    return () => clearInterval(iv);
  }, [playing]);

  // Generate deterministic waveform
  const bars = React.useMemo(() => {
    const arr = [];
    let s = seed * 9301 + 49297;
    for (let i = 0; i < 60; i++) {
      s = (s * 9301 + 49297) % 233280;
      const r = s / 233280;
      // weight middle heavier
      const env = 0.35 + 0.65 * Math.sin((i / 60) * Math.PI);
      arr.push(Math.max(3, Math.round((r * 0.7 + env * 0.3) * 20)));
    }
    return arr;
  }, [seed]);

  const tt = (frac) => {
    const sec = Math.round(frac * 134); // ~2:14 max
    const m = Math.floor(sec / 60).toString().padStart(1, "0");
    const s = (sec % 60).toString().padStart(2, "0");
    return `${m}:${s}`;
  };

  return (
    <div className={`audio${playing ? " is-play" : ""}`}>
      <button className={`aud-play${playing ? " is-play" : ""}`} onClick={() => setPlaying((p) => !p)}>
        {playing ? "■" : "▶"}
      </button>
      <div className="audio-body">
        <div className="audio-title">
          <span>{title}</span>
          <span className="at-dim">{meta}</span>
        </div>
        <div className="audio-wave">
          {bars.map((h, i) => (
            <span
              key={i}
              className={playing && i <= pos ? "act" : ""}
              style={{ height: `${h}px` }}
            />
          ))}
        </div>
      </div>
      <div className="audio-time">
        {playing ? tt(pos / 60) : "0:00"} / {dur}
      </div>
    </div>
  );
}

Object.assign(window, { MediaPlaceholder, AudioPlayer, CornerMarks });
