/* Sosh Insider — Bali :: SOSH TV video player + animated video placeholders */
const { useState: useS2, useRef: useR2, useEffect: useE2 } = React;

function shade(hex, amt) {
  const h = hex.replace("#", "");
  let r = parseInt(h.slice(0, 2), 16),
    g = parseInt(h.slice(2, 4), 16),
    b = parseInt(h.slice(4, 6), 16);
  const f = (x) =>
    Math.max(0, Math.min(255, Math.round(amt >= 0 ? x + (255 - x) * amt : x * (1 + amt))));
  return `rgb(${f(r)},${f(g)},${f(b)})`;
}

/* Canvas screen: TV static when stopped, animated "footage" placeholder when playing. */
function VideoScreen({ clip, playing, tint }) {
  const ref = useR2(null);
  const raf = useR2(0);

  useE2(() => {
    const cv = ref.current;
    if (!cv) return;
    const ctx = cv.getContext("2d");
    const W = (cv.width = 320);
    const H = (cv.height = 180);
    const reduced =
      window.matchMedia &&
      window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    const t0 = performance.now();
    let last = 0;

    const drawStatic = () => {
      const img = ctx.createImageData(W, H);
      const d = img.data;
      for (let i = 0; i < d.length; i += 4) {
        const v = (Math.random() * 255) | 0;
        d[i] = d[i + 1] = d[i + 2] = v;
        d[i + 3] = 255;
      }
      ctx.putImageData(img, 0, 0);
    };

    const drawFootage = (now) => {
      const ts = (now - t0) / 1000;
      const g = ctx.createLinearGradient(0, 0, 0, H);
      g.addColorStop(0, shade(tint, 0.55));
      g.addColorStop(0.55, shade(tint, 0.05));
      g.addColorStop(1, shade(tint, -0.4));
      ctx.fillStyle = g;
      ctx.fillRect(0, 0, W, H);
      // drifting caustic light shafts
      ctx.globalAlpha = 0.16;
      ctx.fillStyle = "#e8feff";
      for (let k = 0; k < 7; k++) {
        const x = ((ts * 26 + k * 58) % (W + 120)) - 60;
        ctx.save();
        ctx.transform(1, 0, -0.55, 1, x, 0);
        ctx.fillRect(0, 0, 22, H);
        ctx.restore();
      }
      // rising bubbles
      ctx.globalAlpha = 0.5;
      ctx.fillStyle = "#dffbff";
      for (let b = 0; b < 14; b++) {
        const seed = b * 97.3;
        const bx = (Math.sin(seed) * 0.5 + 0.5) * W;
        const by = H - ((ts * 18 + seed * 13) % (H + 20));
        const r = 1 + (b % 3);
        ctx.beginPath();
        ctx.arc(bx, by, r, 0, 7);
        ctx.fill();
      }
      ctx.globalAlpha = 1;
      // a few stray static specks so it still reads "tape"
      for (let s = 0; s < 60; s++) {
        ctx.fillStyle = Math.random() > 0.5 ? "rgba(255,255,255,0.18)" : "rgba(0,0,0,0.15)";
        ctx.fillRect((Math.random() * W) | 0, (Math.random() * H) | 0, 1, 1);
      }
    };

    const frame = (now) => {
      raf.current = requestAnimationFrame(frame);
      if (now - last < 70) return;
      last = now;
      playing ? drawFootage(now) : drawStatic();
    };

    if (reduced) {
      playing ? drawFootage(performance.now()) : drawStatic();
    } else {
      // paint one frame immediately so a freshly-mounted screen is never blank
      playing ? drawFootage(performance.now()) : drawStatic();
      raf.current = requestAnimationFrame(frame);
    }
    return () => cancelAnimationFrame(raf.current);
  }, [playing, tint, clip && clip.id]);

  return (
    <canvas
      ref={ref}
      style={{
        width: "100%",
        height: "100%",
        display: "block",
        imageRendering: "pixelated",
        background: "#0b0b0b",
      }}
    />
  );
}

/* SOSH TV logo lockup */
function SoshTVMark({ small }) {
  return (
    <div style={{ display: "flex", alignItems: "baseline", gap: 4, lineHeight: 1 }}>
      <span className="pixel" style={{ fontSize: small ? 9 : 13, color: "#fff", textShadow: "1px 1px 0 #000" }}>
        SOSH
      </span>
      <span
        className="pixel"
        style={{
          fontSize: small ? 9 : 13,
          color: "#fff",
          background: "var(--terracotta)",
          padding: "1px 3px",
          textShadow: "1px 1px 0 rgba(0,0,0,0.4)",
        }}
      >
        TV
      </span>
    </div>
  );
}

/* The hero player window (Poolsuite-style) */
function TVWindow({ clips, index, playing, onSet, geom, onClose, onTitleDown, onFocus, z, narrow }) {
  const clip = clips[index];
  const [progress, setProgress] = useS2(0);

  useE2(() => {
    setProgress(0);
    if (!playing) return;
    const id = setInterval(() => {
      setProgress((p) => {
        if (p >= 100) {
          onSet({ index: (index + 1) % clips.length, playing: true });
          return 0;
        }
        return p + 1.1;
      });
    }, 90);
    return () => clearInterval(id);
  }, [playing, index]);

  const nav = (d) => {
    window.SFX && SFX.shutter();
    onSet({ index: (index + d + clips.length) % clips.length, playing });
  };

  return (
    <div onMouseDown={onFocus} style={{ position: "absolute", left: geom.x, top: geom.y, width: geom.w, zIndex: z }}>
      <MacWindow
        title="SOSH TV — Best of Bali"
        onClose={onClose}
        onTitleDown={onTitleDown}
        zoomable={false}
        style={{ position: "relative", width: "100%" }}
      >
        {/* screen */}
        <div style={{ position: "relative", aspectRatio: "16 / 9", background: "#0b0b0b", borderBottom: "2px solid var(--line)" }}>
          <VideoScreen clip={clip} playing={playing} tint={clip.tint} />
          <div style={{ position: "absolute", top: 9, left: 10 }}>
            <SoshTVMark />
          </div>
          {/* center play/pause */}
          <button
            data-clickable
            onClick={() => {
              window.SFX && SFX.click();
              onSet({ index, playing: !playing });
            }}
            aria-label={playing ? "Pause" : "Play"}
            style={{
              position: "absolute",
              inset: 0,
              margin: "auto",
              width: 60,
              height: 60,
              background: "rgba(20,16,13,0.35)",
              border: "2px solid rgba(255,255,255,0.85)",
              color: "#fff",
              fontSize: 22,
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              opacity: playing ? 0 : 1,
              transition: "opacity 0.2s",
            }}
            onMouseEnter={(e) => (e.currentTarget.style.opacity = 1)}
            onMouseLeave={(e) => (e.currentTarget.style.opacity = playing ? 0 : 1)}
          >
            {playing ? "❚❚" : "▶"}
          </button>
          {playing && (
            <div className="mono" style={{ position: "absolute", bottom: 8, left: 10, color: "#e8feff", fontSize: 13, textShadow: "1px 1px 0 #000", letterSpacing: 1 }}>
              ● REC {clip.runtime}
            </div>
          )}
        </div>

        {/* file bar */}
        <div style={{ display: "flex", alignItems: "center", gap: 6, padding: "3px 8px", borderBottom: "2px solid var(--line)", background: "var(--paper2)" }}>
          <span className="mono" style={{ fontSize: 13, flex: 1, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
            {clip.file}
          </span>
          <span className="mono" style={{ fontSize: 12, color: "var(--ink-soft)" }}>1920×1080</span>
        </div>
        {/* progress */}
        <div style={{ height: 6, background: "var(--paper2)", borderBottom: "2px solid var(--line)" }}>
          <div style={{ width: progress + "%", height: "100%", background: "var(--terracotta)" }} />
        </div>

        {/* now showing */}
        <div style={{ padding: "10px 12px 6px", background: "var(--paper)" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <span className="pixel" style={{ fontSize: 10 }}>SOSH INSIDER: ON AIR</span>
            <span style={{ width: 8, height: 8, borderRadius: "50%", background: playing ? "#d23b2e" : "var(--ink-soft)", boxShadow: playing ? "0 0 0 2px rgba(210,59,46,0.25)" : "none" }} />
          </div>
          <div className="serif" style={{ fontSize: 18, marginTop: 4 }}>
            {clip.title} <span style={{ color: "var(--ink-soft)" }}>— {clip.place}</span>
          </div>
        </div>

        {/* transport */}
        <div style={{ display: "flex", alignItems: "center", gap: 7, padding: "4px 12px 12px", background: "var(--paper)", flexWrap: "wrap" }}>
          <PixelButton accent onClick={() => onSet({ index, playing: !playing })} style={{ minWidth: 60, justifyContent: "center" }}>
            {playing ? "❚❚ Pause" : "▶ Play"}
          </PixelButton>
          <PixelButton onClick={() => { window.SFX && SFX.close(); onSet({ index, playing: false }); }}>■</PixelButton>
          <PixelButton onClick={() => nav(-1)}>◀◀</PixelButton>
          <PixelButton onClick={() => nav(1)}>▶▶</PixelButton>
          <div style={{ flex: 1 }} />
          <span className="mono" style={{ fontSize: 13, color: "var(--ink-soft)", whiteSpace: "nowrap" }}>
            CLIP {index + 1}/{clips.length}
          </span>
        </div>

        {/* channel bar */}
        <div style={{ display: "flex", alignItems: "center", gap: 8, padding: "7px 10px", borderTop: "2px solid var(--line)", background: "var(--paper2)" }}>
          <span className="mono" style={{ fontSize: 13, flex: 1, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
            Reel: Below the Surface
          </span>
          <span className="pixel" style={{ fontSize: 8, border: "2px solid var(--line)", padding: "3px 6px 2px", background: "var(--paper)" }}>
            LIVE ▾
          </span>
        </div>
      </MacWindow>
    </div>
  );
}

Object.assign(window, { VideoScreen, SoshTVMark, TVWindow, shade });
