// Playouts screen — a broadcast "now / next" monitor. Filterable playout rail on the
// left; on the right, an on-air hero, up-next + playout-detail cards, a timeline, and
// an upcoming-items list. Mirrors PlayoutsScreen.tsx (ctv-playouts-* layout classes).
(function () {
  const NS = window.ChicoryTVDesignSystem_eb3b61;
  const { Badge, Button, Card, ChannelLogo, IconButton, Input, ProgressBar, StatusDot, Switch, Tooltip } = NS;
  const Ico = window.Ico;
  const mono = { fontFamily: "var(--font-mono)", fontVariantNumeric: "tabular-nums" };

  const PLAYOUTS = [
    { id: 1, num: "1.1", name: "Cartoon Junction", scheduleName: "Prime Time Cartoons", kind: "Classic", onAir: true, locked: false, now: "Tom & Jerry — The Cat Concerto" },
    { id: 2, num: "2.1", name: "News 24", scheduleName: "World Tonight", kind: "Classic", onAir: true, locked: false, now: "World Tonight — Evening bulletin" },
    { id: 3, num: "3.1", name: "Retro Toons Block", scheduleName: "Saturday AM Block", kind: "Block", onAir: false, locked: true, now: null },
    { id: 4, num: "4.2", name: "Synthwave Radio", scheduleName: "80s Block", kind: "Sequential", onAir: true, locked: false, now: "80s Block — Synthpop hour" },
    { id: 5, num: "6.1", name: "Kids Corner", scheduleName: "Sesame Loop", kind: "Classic", onAir: false, locked: false, now: null },
    { id: 6, num: "7.1", name: "Docu Nights", scheduleName: "true-crime.yml", kind: "Scripted", onAir: false, locked: false, now: null },
    { id: 7, num: "9.1", name: "PBS Kids Replay", scheduleName: "Sesame Street", kind: "Classic", onAir: true, locked: false, now: "Sesame Street — Episode 4102" },
    { id: 8, num: "11.1", name: "Movie Vault", scheduleName: "dizque-export.json", kind: "ExternalJson", onAir: false, locked: false, now: null },
  ];

  const DETAIL = {
    mode: "Flood",
    scheduleName: "Prime Time Cartoons",
    kind: "Classic",
    rebuild: "04:00",
    seed: "88421193",
  };

  const NEXT = { title: "Looney Tunes — Duck Amuck", start: "20:44", dur: "7m" };

  const ITEMS = [
    { start: "19:58", finish: "20:31", title: "Tom & Jerry — The Cat Concerto", dur: "33m", filler: false },
    { start: "20:31", finish: "20:34", title: "Bumper — Station ID", dur: "3m", filler: true },
    { start: "20:34", finish: "20:44", title: "Tom & Jerry — Puss n' Toots", dur: "10m", filler: false },
    { start: "20:44", finish: "20:51", title: "Looney Tunes — Duck Amuck", dur: "7m", filler: false },
    { start: "20:51", finish: "20:53", title: "Bumper — Coming up next", dur: "2m", filler: true },
    { start: "20:53", finish: "21:24", title: "Scooby-Doo — Mystery Mask Mix-Up", dur: "31m", filler: false },
    { start: "21:24", finish: "21:55", title: "Looney Tunes — Rabbit Fire", dur: "31m", filler: false },
  ];

  function nowProgress() {
    return 48;
  }

  function Row({ label, value }) {
    return (
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12 }}>
        <span style={{ font: "var(--text-xs)/1 var(--font-sans)", color: "var(--text-secondary)" }}>{label}</span>
        <span style={{ ...mono, font: "var(--weight-medium) var(--text-xs)/1 var(--font-mono)", color: "var(--text-primary)" }}>{value}</span>
      </div>
    );
  }

  function Timeline() {
    const toMin = (t) => { const [h, m] = t.split(":").map(Number); return h * 60 + m; };
    const start = toMin(ITEMS[0].start), end = toMin(ITEMS[ITEMS.length - 1].finish);
    const span = end - start, nowPct = 46;
    return (
      <div style={{ display: "grid", gap: 8 }}>
        <div style={{ position: "relative", display: "flex", height: 34, borderRadius: "var(--radius-sm)", overflow: "hidden", border: "1px solid var(--border-hairline)", background: "var(--ctv-bg-sunken)" }}>
          {ITEMS.map((it, i) => {
            const w = Math.max(((toMin(it.finish) - toMin(it.start)) / span) * 100, 2);
            return (
              <span key={i} title={it.title}
                style={{ display: "flex", alignItems: "center", overflow: "hidden", width: `${w}%`, borderRight: i < ITEMS.length - 1 ? "1px solid var(--ctv-bg)" : "none", background: it.filler ? "var(--ctv-surface-3)" : "var(--ctv-accent-soft)", color: it.filler ? "var(--text-secondary)" : "var(--ctv-accent)", font: "var(--weight-medium) var(--text-2xs)/1 var(--font-sans)", padding: "0 8px", whiteSpace: "nowrap", textOverflow: "ellipsis" }}>
                {w > 12 ? it.title : ""}
              </span>
            );
          })}
          <span style={{ position: "absolute", top: -3, bottom: -3, left: `${nowPct}%`, width: 2, background: "var(--status-live)", boxShadow: "0 0 8px var(--status-live)" }} />
        </div>
        <p style={{ display: "flex", justifyContent: "space-between", margin: 0, color: "var(--text-disabled)", font: "var(--text-2xs)/1 var(--font-mono)" }}>
          <span style={mono}>{ITEMS[0].start}</span>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 4, color: "var(--status-live)", fontFamily: "var(--font-sans)" }}><Ico n="Clock" s={12} /> now</span>
          <span style={mono}>{ITEMS[ITEMS.length - 1].finish}</span>
        </p>
      </div>
    );
  }

  function Playouts() {
    const [filter, setFilter] = React.useState("");
    const [selId, setSelId] = React.useState(1);
    const [showFiller, setShowFiller] = React.useState(true);

    const sel = PLAYOUTS.find((p) => p.id === selId) || PLAYOUTS[0];
    const q = filter.trim().toLowerCase();
    const filtered = q
      ? PLAYOUTS.filter((p) => p.name.toLowerCase().includes(q) || p.num.includes(q) || p.scheduleName.toLowerCase().includes(q))
      : PLAYOUTS;
    const warningsCount = 2;
    const visibleItems = showFiller ? ITEMS : ITEMS.filter((it) => !it.filler);

    return (
      <div style={{ display: "flex", flexDirection: "column", height: "100%", gap: 12, padding: 20, minHeight: 0 }}>
        {/* header */}
        <div style={{ display: "flex", alignItems: "center", gap: 10, border: "1px solid var(--border-hairline)", borderRadius: "var(--radius-md)", background: "var(--surface-card)", padding: "12px 20px", flex: "0 0 auto" }}>
          <Button variant="secondary" startIcon={<Ico n="RefreshCw" s={15} />}>Reset all playouts</Button>
          <span style={{ flex: 1 }} />
          <Badge tone={warningsCount > 0 ? "warn" : "neutral"} dot={warningsCount > 0}>{warningsCount} warnings</Badge>
          <Button variant="primary" startIcon={<Ico n="Plus" s={15} />}>Add Playout</Button>
        </div>

        {/* grid */}
        <div style={{ display: "grid", gridTemplateColumns: "260px minmax(0, 1fr)", gap: 20, flex: 1, minHeight: 0 }}>
          {/* rail */}
          <aside style={{ display: "flex", flexDirection: "column", minHeight: 0, overflow: "hidden", border: "1px solid var(--border-hairline)", borderRadius: "var(--radius-md)", background: "var(--surface-card)" }}>
            <div style={{ display: "grid", gap: 8, borderBottom: "1px solid var(--border-hairline)", padding: 12 }}>
              <Input size="sm" placeholder="Filter playouts..." value={filter} onChange={(e) => setFilter(e.target.value)} />
              <span style={{ color: "var(--text-disabled)", font: "var(--text-2xs)/1 var(--font-sans)" }}>
                {filtered.length === PLAYOUTS.length ? `${PLAYOUTS.length} playouts loaded` : `${filtered.length} of ${PLAYOUTS.length} playouts`}
              </span>
            </div>
            <div style={{ display: "grid", alignContent: "start", gap: 4, overflow: "auto", padding: 8 }}>
              {filtered.map((p) => {
                const active = p.id === sel.id;
                return (
                  <button key={p.id} type="button" onClick={() => setSelId(p.id)}
                    style={{ display: "grid", gridTemplateColumns: "30px minmax(0,1fr) 10px", alignItems: "center", gap: 10, width: "100%", border: "none", borderRadius: "var(--radius-sm)", background: active ? "var(--ctv-accent-soft)" : "transparent", color: "inherit", cursor: "pointer", padding: 8, textAlign: "left" }}>
                    <ChannelLogo name={p.name} size={30} />
                    <span style={{ display: "grid", minWidth: 0, gap: 4 }}>
                      <span style={{ display: "flex", alignItems: "center", gap: 6 }}>
                        <code style={{ ...mono, color: "var(--status-live)", fontSize: "var(--text-2xs)" }}>{p.num}</code>
                        <strong style={{ overflow: "hidden", color: "var(--text-primary)", font: "var(--weight-semibold) var(--text-sm)/1.2 var(--font-sans)", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{p.name}</strong>
                      </span>
                      <small style={{ overflow: "hidden", color: "var(--text-secondary)", font: "var(--text-2xs)/1.2 var(--font-sans)", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{p.now ?? p.scheduleName}</small>
                    </span>
                    {p.onAir && <StatusDot status="live" size={7} />}
                  </button>
                );
              })}
            </div>
          </aside>

          {/* monitor */}
          <section style={{ display: "flex", flexDirection: "column", gap: 16, minHeight: 0, overflow: "auto", border: "1px solid var(--border-hairline)", borderRadius: "var(--radius-md)", background: "var(--surface-card)", padding: 20 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
              <ChannelLogo name={sel.name} size={38} />
              <div style={{ display: "grid", minWidth: 0, gap: 4 }}>
                <span style={{ display: "flex", alignItems: "center", gap: 8, color: "var(--text-secondary)", font: "var(--text-xs)/1 var(--font-sans)" }}>
                  <code style={{ ...mono, fontSize: "var(--text-xs)" }}>{sel.num}</code>
                  {sel.onAir && <Badge tone="accent" dot>On air</Badge>}
                  {sel.locked && <Badge tone="warn" dot>Building…</Badge>}
                </span>
                <h2 style={{ margin: 0, color: "var(--text-primary)", font: "var(--weight-semibold) var(--text-md)/1.2 var(--font-sans)" }}>{sel.name}</h2>
              </div>
            </div>

            {/* now playing */}
            <div style={{ display: "grid", gridTemplateColumns: "210px minmax(0,1fr)", overflow: "hidden", border: "1px solid var(--border-hairline)", borderRadius: "var(--radius-md)", background: "var(--surface-card)" }}>
              <div style={{ position: "relative", display: "flex", alignItems: "center", justifyContent: "center", minHeight: 150, borderRight: "1px solid var(--border-hairline)", background: "var(--ctv-bg-sunken)", color: "var(--ctv-accent)" }}>
                <Ico n="Play" s={24} />
                <span style={{ position: "absolute", left: 10, bottom: 10 }}><Badge tone="neutral">Metadata preview only</Badge></span>
              </div>
              <div style={{ display: "flex", flexDirection: "column", justifyContent: "center", gap: 10, minWidth: 0, padding: 20 }}>
                <span style={{ color: "var(--status-live)", font: "var(--weight-semibold) var(--text-2xs)/1 var(--font-sans)", letterSpacing: "0.04em", textTransform: "uppercase" }}>On air now</span>
                <h3 style={{ margin: 0, color: "var(--text-primary)", font: "var(--weight-semibold) var(--text-lg)/1.2 var(--font-sans)" }}>{sel.now ?? "No current item reported"}</h3>
                <ProgressBar value={sel.now ? nowProgress() : 0} />
                <div style={{ display: "flex", justifyContent: "space-between", gap: 12, color: "var(--text-disabled)", font: "var(--text-2xs)/1 var(--font-mono)" }}>
                  <code style={mono}>19:58</code>
                  <code style={mono}>20:31</code>
                </div>
              </div>
            </div>

            {/* up next + playout detail */}
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
              <Card title="Up next">
                <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
                  <Ico n="Film" s={18} color="var(--ctv-accent)" />
                  <span style={{ display: "grid", minWidth: 0, gap: 4 }}>
                    <strong style={{ overflow: "hidden", color: "var(--text-primary)", font: "var(--weight-semibold) var(--text-sm)/1.2 var(--font-sans)", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{NEXT.title}</strong>
                    <small style={{ color: "var(--text-secondary)", font: "var(--text-2xs)/1.2 var(--font-sans)" }}>{NEXT.start} · {NEXT.dur}</small>
                  </span>
                </div>
              </Card>

              <Card title="Playout" actions={<Button size="sm" variant="ghost" startIcon={<Ico n="Pencil" s={13} />}>Edit details</Button>}>
                <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
                  <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
                    <Input disabled label="Mode" value={DETAIL.mode} />
                    <Input disabled label="Schedule" value={DETAIL.scheduleName} />
                    <Input disabled label="Kind" value={DETAIL.kind} />
                    <Input disabled label="Rebuild" value={DETAIL.rebuild} />
                    <Input disabled label="Seed" value={DETAIL.seed} />
                  </div>
                  <p style={{ margin: 0, color: "var(--text-secondary)", font: "var(--text-xs)/1.4 var(--font-sans)" }}>
                    The play order is saved and stays consistent across rebuilds. Reshuffle to roll a new order.
                  </p>
                  <div style={{ display: "flex", gap: 8 }}>
                    <Button size="sm" variant="secondary" startIcon={<Ico n="CalendarClock" s={13} />}>Alternate schedules</Button>
                  </div>
                  <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
                    <Button size="sm" variant="secondary" startIcon={<Ico n="RefreshCw" s={13} />}>Reset</Button>
                    <Button size="sm" variant="ghost" startIcon={<Ico n="Eraser" s={13} />}>Erase items and history</Button>
                    <Button size="sm" variant="ghost" startIcon={<Ico n="Dices" s={13} />}>Reshuffle</Button>
                    <Button size="sm" variant="danger" startIcon={<Ico n="Trash2" s={13} />}>Delete</Button>
                  </div>
                </div>
              </Card>
            </div>

            <Card title="Timeline" subtitle="Selected playout items">
              <Timeline />
            </Card>

            <Card title="Upcoming" subtitle="Next items" padded={false}
              actions={<Switch checked={showFiller} onChange={setShowFiller} label="Show filler" size="sm" />}>
              <div role="list" aria-label="Upcoming playout items">
                {visibleItems.map((it, i) => (
                  <div key={i} role="listitem"
                    style={{ display: "grid", gridTemplateColumns: "58px 14px minmax(0,1fr) auto 64px", alignItems: "center", gap: 10, borderTop: i ? "1px solid var(--border-hairline)" : "none", padding: "10px 16px", background: i === 0 ? "var(--ctv-live-soft)" : "transparent" }}>
                    <code style={{ ...mono, color: "var(--text-disabled)", fontSize: "var(--text-2xs)" }}>{it.start}</code>
                    <Ico n={it.filler ? "Sparkles" : "Film"} s={13} color="var(--ctv-accent)" />
                    <span style={{ overflow: "hidden", color: "var(--text-primary)", font: "var(--text-sm)/1 var(--font-sans)", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{it.title}</span>
                    {it.filler ? <Badge tone="neutral">Filler</Badge> : <span />}
                    <span style={{ display: "flex", alignItems: "center", gap: 6, justifySelf: "end" }}>
                      <small style={{ ...mono, color: "var(--text-disabled)", fontSize: "var(--text-2xs)" }}>{it.dur}</small>
                      <Tooltip label="Scheduling context">
                        <IconButton size="sm" variant="ghost" title="Scheduling context"><Ico n="Info" s={13} /></IconButton>
                      </Tooltip>
                    </span>
                  </div>
                ))}
              </div>
            </Card>
          </section>
        </div>
      </div>
    );
  }

  window.CTVPlayouts = Playouts;
})();
