// Playback Troubleshooting screen — a diagnostic console for previewing a single media item or
// channel through the live segmenter: settings form → Play → an embedded HLS preview + a
// speed-colored FFmpeg log tail. Mirrors PlaybackTroubleshootingScreen.tsx's media-mode layout.
(function () {
  const NS = window.ChicoryTVDesignSystem_eb3b61;
  const { Button, Badge, StatusDot, Card, Input, Select, Checkbox, Spinner, Tooltip } = NS;
  const Ico = window.Ico;
  const mono = { fontFamily: "var(--font-mono)", fontVariantNumeric: "tabular-nums" };

  const PROFILE_OPTIONS = [
    { value: "1", label: "Direct — Copy" },
    { value: "2", label: "1080p — NVENC H.264" },
    { value: "3", label: "720p — Software x264" },
    { value: "4", label: "4K HDR — NVENC HEVC" },
  ];

  const SELECTOR_OPTIONS = [
    { value: "", label: "(none)" },
    { value: "best", label: "best" },
    { value: "eng-5.1", label: "eng-5.1" },
    { value: "commentary", label: "commentary" },
  ];

  const SUBTITLE_OPTIONS = [
    { value: "", label: "(none)" },
    { value: "14201", label: "14201: eng - English (SRT)" },
    { value: "14202", label: "14202: eng - English SDH (SRT)" },
    { value: "14203", label: "14203: fre - French (PGS)" },
  ];

  const WATERMARKS = [
    { id: 1, name: "Corner bug — ChicoryTV" },
    { id: 2, name: "Lower-third — Now Playing" },
  ];

  const GRAPHICS = [
    { id: 1, name: "Rating card overlay" },
    { id: 2, name: "Bumper — Up Next" },
  ];

  const LOG_TAIL = `[info] libx264 @ 0x5590c4a0: profile High, level 4.0, 4:2:0, 8-bit
[info] Stream mapping:
  Stream #0:0 -> #0:0 (h264 (native) -> h264 (libx264))
  Stream #0:1 -> #0:1 (aac (native) -> aac (native))
frame= 1240 fps= 62 q=23.0 size=   18432kB time=00:00:51.66 bitrate=2924.1kbits/s speed=1.29x
frame= 1480 fps= 61 q=23.0 size=   22016kB time=00:01:01.63 bitrate=2925.7kbits/s speed=1.27x
frame= 1720 fps= 60 q=23.0 size=   25600kB time=00:01:11.63 bitrate=2926.9kbits/s speed=1.25x
frame= 1960 fps= 60 q=23.0 size=   29184kB time=00:01:21.63 bitrate=2927.8kbits/s speed=1.26x`;

  function Row({ label, help, children }) {
    return (
      <div style={{ display: "flex", gap: 24, padding: "14px 0", borderTop: "1px solid var(--border-hairline)" }}>
        <div style={{ flex: "0 0 200px" }}>
          <div style={{ font: "var(--weight-medium) var(--text-sm)/1.3 var(--font-sans)", color: "var(--text-primary)" }}>{label}</div>
          {help && <div style={{ marginTop: 4, font: "var(--text-xs)/1.4 var(--font-sans)", color: "var(--text-faint)", maxWidth: 260 }}>{help}</div>}
        </div>
        <div style={{ flex: "0 0 340px", minWidth: 0 }}>{children}</div>
      </div>
    );
  }

  function CheckboxList({ items, selected, onToggle }) {
    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
        {items.map((it) => (
          <Checkbox key={it.id} checked={selected.includes(it.id)} onChange={() => onToggle(it.id)} label={it.name} />
        ))}
      </div>
    );
  }

  function PlaybackTroubleshooting() {
    const [profile, setProfile] = React.useState("2");
    const [selector, setSelector] = React.useState("");
    const [subtitle, setSubtitle] = React.useState("14201");
    const [watermarks, setWatermarks] = React.useState([1]);
    const [graphics, setGraphics] = React.useState([]);
    const [fromStart, setFromStart] = React.useState(false);
    const [seek, setSeek] = React.useState(2745);
    const [phase, setPhase] = React.useState("running"); // idle | starting | running

    const toggle = (arr, setArr, id) => setArr(arr.includes(id) ? arr.filter((x) => x !== id) : [...arr, id]);
    const isBusy = phase !== "idle";
    const speed = 1.26;
    const speedColor = speed < 0.9 ? "var(--status-error)" : speed > 1.1 ? "var(--status-ok)" : "var(--status-warn)";

    return (
      <div style={{ display: "flex", flexDirection: "column", height: "100%" }}>
        {/* action bar */}
        <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "12px 20px", borderBottom: "1px solid var(--border-hairline)", flex: "0 0 auto", minHeight: 58 }}>
          <Button size="sm" variant="secondary" startIcon={<Ico n="Download" s={14} />}>Download Results</Button>
          <Button size="sm" variant="secondary" startIcon={<Ico n="DownloadCloud" s={14} />}>Download Media Sample</Button>
          <span style={{ flex: 1 }} />
          <span style={{ display: "inline-flex", alignItems: "center", gap: 7, font: "var(--text-xs)/1 var(--font-sans)", color: "var(--text-secondary)" }}>
            <Ico n="Stethoscope" s={14} color="var(--text-disabled)" />
            Media #14582
          </span>
        </div>

        <div style={{ flex: 1, overflow: "auto", padding: "16px 20px", display: "flex", flexDirection: "column", gap: 16, maxWidth: 900 }}>
          {/* success notice */}
          <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "10px 14px", borderRadius: "var(--radius-md)", background: "var(--ctv-ok-soft)", border: "1px solid var(--border-hairline)" }}>
            <Ico n="CheckCircle2" s={16} color="var(--status-ok)" />
            <span style={{ font: "var(--text-sm)/1.3 var(--font-sans)", color: "var(--text-primary)" }}>FFmpeg troubleshooting process exited successfully</span>
            <span style={{ flex: 1 }} />
            <Tooltip label="Dismiss"><span style={{ cursor: "pointer", color: "var(--text-faint)" }}><Ico n="X" s={14} /></span></Tooltip>
          </div>

          <Card padded title="Movie Settings — Alien (1979)" subtitle="Preview a media item">
            <div style={{ display: "flex", flexDirection: "column" }}>
              <Row label="FFmpeg Profile">
                <Select value={profile} onChange={(e) => setProfile(e.target.value)} options={PROFILE_OPTIONS} fullWidth />
              </Row>
              <Row label="Stream Selector">
                <Select value={selector} onChange={(e) => setSelector(e.target.value)} options={SELECTOR_OPTIONS} fullWidth />
              </Row>
              <Row label="Subtitle">
                <Select value={selector === "" ? subtitle : ""} disabled={selector !== ""} onChange={(e) => setSubtitle(e.target.value)} options={SUBTITLE_OPTIONS} fullWidth />
              </Row>
              <Row label="Watermarks">
                <CheckboxList items={WATERMARKS} selected={watermarks} onToggle={(id) => toggle(watermarks, setWatermarks, id)} />
              </Row>
              <Row label="Graphics Elements">
                <CheckboxList items={GRAPHICS} selected={graphics} onToggle={(id) => toggle(graphics, setGraphics, id)} />
              </Row>
              <Row label="Start From Beginning">
                <Checkbox checked={fromStart} onChange={setFromStart} label="Start from the beginning" />
              </Row>
              <Row label="Seek Seconds">
                <Input type="number" value={String(seek)} disabled={fromStart} onChange={(e) => setSeek(Number(e.target.value) || 0)} fullWidth />
              </Row>
            </div>
          </Card>

          <Card padded title="Preview" subtitle="Live segmenter output">
            <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
              <Button variant="primary" startIcon={<Ico n="PlayCircle" s={15} />} disabled={isBusy}>Play</Button>
              {isBusy && (
                <span style={{ display: "inline-flex", alignItems: "center", gap: 8, font: "var(--text-sm)/1 var(--font-sans)", color: "var(--text-secondary)" }}>
                  <Spinner size={15} tone="accent" />
                  {phase === "starting" ? "Starting…" : "Transcoding…"}
                </span>
              )}
            </div>
            <div style={{ marginTop: 16, maxWidth: 720, aspectRatio: "16 / 9", width: "100%", background: "#000", borderRadius: "var(--radius-md)", position: "relative", overflow: "hidden", display: "flex", alignItems: "center", justifyContent: "center", border: "1px solid var(--border-hairline)" }}>
              <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 8, color: "rgba(255,255,255,0.55)" }}>
                <Ico n="Film" s={30} color="rgba(255,255,255,0.4)" />
                <span style={{ font: "var(--text-xs)/1 var(--font-sans)" }}>HLS preview stream</span>
              </div>
              <div style={{ position: "absolute", top: 10, left: 10 }}>
                <StatusDot status="live" pulse size={8} label="Live" />
              </div>
              <div style={{ position: "absolute", bottom: 10, right: 12, ...mono, fontSize: "var(--text-2xs)", color: "rgba(255,255,255,0.7)" }}>00:45:47 / 01:56:32</div>
            </div>
          </Card>

          <Card
            padded
            title={
              <span style={{ display: "inline-flex", alignItems: "center", gap: 8 }}>
                Logs
                <Badge tone="neutral" solid={false}>
                  <span style={{ ...mono, color: speedColor }}>Speed: {speed}x</span>
                </Badge>
              </span>
            }
          >
            <textarea
              readOnly
              rows={16}
              value={LOG_TAIL}
              style={{
                width: "100%",
                resize: "vertical",
                boxSizing: "border-box",
                padding: "12px 14px",
                borderRadius: "var(--radius-sm)",
                border: "1px solid var(--border-hairline)",
                background: "var(--ctv-bg-sunken)",
                color: "var(--text-secondary)",
                font: "var(--text-xs)/1.6 var(--font-mono)",
              }}
            />
          </Card>
        </div>
      </div>
    );
  }

  window.CTVPlaybackTroubleshooting = PlaybackTroubleshooting;
})();
