// Channels screen — a channel-group'd management table with an at-a-glance
// on-air treatment (accent rail + live now-playing lane) and a strong channel
// identity cell. Dense and scannable — the right tool for managing 128 channels.
(function () {
  const NS = window.ChicoryTVDesignSystem_eb3b61;
  const { Button, IconButton, Badge, StatusDot, ChannelLogo, Checkbox, Tooltip } = NS;
  const Ico = window.Ico;
  const D = window.CTV_DATA;
  const mono = { fontFamily: "var(--font-mono)", fontVariantNumeric: "tabular-nums" };

  const NOW = {
    "1.1": { t: "Tom & Jerry — The Cat Concerto", pct: 48 },
    "2.1": { t: "World Tonight — Evening bulletin", pct: 34 },
    "4.2": { t: "80s Block — Synthpop hour", pct: 51 },
    "9.1": { t: "Sesame Street — Episode 4102", pct: 82 },
  };

  const th = { textAlign: "left", padding: "0 var(--pad-cell-x)", height: 34, font: "var(--weight-medium) var(--text-2xs)/1 var(--font-sans)", letterSpacing: "0.04em", textTransform: "uppercase", color: "var(--text-disabled)", whiteSpace: "nowrap", position: "sticky", top: 0, background: "var(--surface-card)", borderBottom: "1px solid var(--border-hairline)", zIndex: 2 };
  const td = { padding: "0 var(--pad-cell-x)", height: 56, font: "var(--text-sm)/1.3 var(--font-sans)", color: "var(--text-primary)", verticalAlign: "middle" };
  const cellCheck = { padding: "0 0 0 14px", width: 30 };

  function Marker({ children, title }) {
    return <span title={title} style={{ display: "inline-flex", alignItems: "center", justifyContent: "center", minWidth: 15, height: 15, padding: "0 3px", borderRadius: "var(--radius-xs)", border: "1px solid var(--border-control)", font: "var(--weight-semibold) 9px/1 var(--font-mono)", color: "var(--text-disabled)", background: "var(--ctv-surface-3)" }}>{children}</span>;
  }

  function Channels() {
    const [view, setView] = React.useState("all");
    const [hover, setHover] = React.useState(null);
    const [sel, setSel] = React.useState({});

    let rows = D.channels;
    if (view === "onair") rows = rows.filter((c) => c.live);
    else if (view === "disabled") rows = rows.filter((c) => !c.enabled);
    else if (view === "noplayout") rows = rows.filter((c) => c.playouts === 0);

    // group, preserving first-seen order
    const groups = [];
    const gmap = {};
    rows.forEach((c) => { if (!gmap[c.group]) { gmap[c.group] = []; groups.push(c.group); } gmap[c.group].push(c); });

    const selCount = Object.values(sel).filter(Boolean).length;
    const allOn = rows.length > 0 && rows.every((c) => sel[c.num]);
    const someOn = selCount > 0 && !allOn;
    const toggleAll = () => { if (allOn) setSel({}); else { const n = {}; rows.forEach((c) => (n[c.num] = true)); setSel(n); } };
    const toggleOne = (num) => setSel((s) => ({ ...s, [num]: !s[num] }));

    const counts = { all: D.channels.length, onair: D.channels.filter((c) => c.live).length, disabled: D.channels.filter((c) => !c.enabled).length, noplayout: D.channels.filter((c) => c.playouts === 0).length };

    const Segmented = () => (
      <div style={{ display: "inline-flex", gap: 2, padding: 2, borderRadius: "var(--radius-sm)", background: "var(--ctv-bg-sunken)", border: "1px solid var(--border-hairline)" }}>
        {[{ v: "all", l: "All", c: counts.all }, { v: "onair", l: "On air", c: counts.onair }, { v: "disabled", l: "Disabled", c: counts.disabled }, { v: "noplayout", l: "No playout", c: counts.noplayout }].map((o) => {
          const on = o.v === view;
          return (
            <button key={o.v} type="button" onClick={() => setView(o.v)}
              style={{ display: "inline-flex", alignItems: "center", gap: 6, height: 26, padding: "0 11px", border: "none", borderRadius: "var(--radius-xs)", cursor: "pointer", background: on ? "var(--ctv-surface-3)" : "transparent", color: on ? "var(--text-primary)" : "var(--text-secondary)", font: `${on ? "var(--weight-medium)" : "var(--weight-normal)"} var(--text-xs)/1 var(--font-sans)` }}>
              {o.l}<span style={{ ...mono, fontSize: "var(--text-2xs)", color: on && o.v === "onair" ? "var(--status-live)" : "var(--text-disabled)" }}>{o.c}</span>
            </button>
          );
        })}
      </div>
    );

    const renderRow = (c, first) => {
      const dim = !c.enabled;
      const isSel = sel[c.num];
      const isHover = hover === c.num;
      const now = NOW[c.num];
      const rowBg = isSel ? "var(--ctv-accent-soft)" : isHover ? "var(--ctv-surface-2)" : c.live ? "var(--ctv-live-soft)" : "transparent";
      return (
        <tr key={c.num} onMouseEnter={() => setHover(c.num)} onMouseLeave={() => setHover(null)}
          style={{ borderTop: first ? "none" : "1px solid var(--border-hairline)", background: rowBg, boxShadow: c.live ? "inset 2px 0 0 var(--status-live)" : "none", transition: "background var(--dur-fast)" }}>
          <td style={{ ...td, ...cellCheck }}><Checkbox checked={!!isSel} onChange={() => toggleOne(c.num)} /></td>
          <td style={{ ...td, ...mono, width: 62 }}>
            <span style={{ display: "inline-flex", alignItems: "center", gap: 6, opacity: dim ? 0.55 : 1 }}>
              {c.live ? <StatusDot status="live" size={7} /> : <span style={{ width: 7 }} />}
              <span style={{ color: "var(--status-live)" }}>{c.num}</span>
            </span>
          </td>
          <td style={{ ...td, opacity: dim ? 0.55 : 1 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 11 }}>
              <ChannelLogo name={c.name} size={34} />
              <div style={{ minWidth: 0 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 7 }}>
                  <span style={{ font: "var(--weight-medium) var(--text-sm)/1.2 var(--font-sans)", color: "var(--text-primary)" }}>{c.name}</span>
                  {!c.enabled && <Marker title="Disabled">D</Marker>}
                  {!c.epg && <Marker title="Hidden from EPG">H</Marker>}
                  {c.playouts === 0 && <Badge tone="error">No playout</Badge>}
                  {/* Immutable creation-provenance: only AutoTuned is badged; user-created/legacy are unmarked. */}
                  {c.origin === "AutoTuned" && <span title="Created by Auto-Tune from a channel lineup"><Badge tone="neutral">Auto-tuned</Badge></span>}
                </div>
                <div style={{ marginTop: 3, font: "var(--text-2xs)/1 var(--font-sans)", color: "var(--text-disabled)" }}>{c.lang}</div>
              </div>
            </div>
          </td>
          <td style={{ ...td, opacity: dim ? 0.55 : 1, width: 250 }}>
            {now ? (
              <div style={{ minWidth: 0 }}>
                <div style={{ font: "var(--text-xs)/1.2 var(--font-sans)", color: "var(--text-secondary)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", maxWidth: 220 }}>{now.t}</div>
                <div style={{ marginTop: 6, display: "flex", alignItems: "center", gap: 8 }}>
                  <div style={{ height: 3, width: 150, borderRadius: 999, background: "var(--ctv-surface-3)", overflow: "hidden" }}>
                    <div style={{ width: now.pct + "%", height: "100%", background: "var(--status-live)" }} />
                  </div>
                  <span style={{ ...mono, font: "var(--text-2xs)/1 var(--font-mono)", color: "var(--text-disabled)" }}>{now.pct}%</span>
                </div>
              </div>
            ) : <span style={{ font: "var(--text-xs)/1 var(--font-sans)", color: "var(--text-faint)" }}>{c.enabled ? "Idle" : "Off air"}</span>}
          </td>
          <td style={{ ...td, opacity: dim ? 0.55 : 1, width: 130 }}><Badge tone={c.mode === "HLS Direct" ? "neutral" : "accent"}>{c.mode}</Badge></td>
          <td style={{ ...td, ...mono, color: c.profile === "—" ? "var(--text-disabled)" : "var(--text-secondary)", opacity: dim ? 0.55 : 1, width: 130 }}>{c.profile}</td>
          <td style={{ ...td, width: 150 }}>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "flex-end", gap: 2, opacity: isHover ? 1 : 0.5, transition: "opacity var(--dur-fast)" }}>
              <Tooltip label="Preview"><IconButton size="sm" title="Preview" variant={c.live ? "solid" : "ghost"} disabled={!c.live}><Ico n="Play" s={15} /></IconButton></Tooltip>
              <Tooltip label="Edit"><IconButton size="sm" title="Edit"><Ico n="Pencil" s={15} /></IconButton></Tooltip>
              <Tooltip label="Troubleshoot"><IconButton size="sm" title="Troubleshoot"><Ico n="Stethoscope" s={15} /></IconButton></Tooltip>
              <Tooltip label="Delete"><IconButton size="sm" title="Delete"><Ico n="Trash2" s={15} /></IconButton></Tooltip>
            </div>
          </td>
        </tr>
      );
    };

    return (
      <div style={{ display: "flex", flexDirection: "column", height: "100%" }}>
        {/* action bar */}
        <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "12px 20px", borderBottom: "1px solid var(--border-hairline)", flex: "0 0 auto", minHeight: 58 }}>
          {selCount > 0 ? (
            <React.Fragment>
              <span style={{ font: "var(--weight-medium) var(--text-sm)/1 var(--font-sans)", color: "var(--text-primary)" }}><span style={mono}>{selCount}</span> selected</span>
              <span style={{ width: 1, height: 18, background: "var(--border-hairline)" }} />
              <Button size="sm" variant="secondary" startIcon={<Ico n="Hash" s={14} />}>Renumber</Button>
              <Button size="sm" variant="secondary" startIcon={<Ico n="FolderInput" s={14} />}>Move to group</Button>
              <Button size="sm" variant="danger" startIcon={<Ico n="Trash2" s={14} />}>Delete</Button>
              <span style={{ flex: 1 }} />
              <Button size="sm" variant="ghost" onClick={() => setSel({})}>Clear</Button>
            </React.Fragment>
          ) : (
            <React.Fragment>
              <Segmented />
              <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)" }}>
                <StatusDot status="live" size={7} /><span style={mono}>{counts.onair}</span> on air
              </span>
              <Button variant="primary" startIcon={<Ico n="Plus" s={15} />}>Add Channel</Button>
            </React.Fragment>
          )}
        </div>

        <div style={{ flex: 1, overflow: "auto", padding: "16px 20px" }}>
          <div style={{ border: "1px solid var(--border-hairline)", borderRadius: "var(--radius-md)", overflow: "hidden", background: "var(--surface-card)" }}>
            <table style={{ width: "100%", borderCollapse: "collapse" }}>
              <thead><tr>
                <th style={{ ...th, ...cellCheck }}><Checkbox checked={allOn} indeterminate={someOn} onChange={toggleAll} /></th>
                <th style={th}>No.</th>
                <th style={th}>Channel</th>
                <th style={th}>Now playing</th>
                <th style={th}>Streaming</th>
                <th style={th}>FFmpeg</th>
                <th style={{ ...th, textAlign: "right" }}></th>
              </tr></thead>
              <tbody>
                {groups.map((g) => (
                  <React.Fragment key={g}>
                    <tr>
                      <td colSpan={7} style={{ padding: "0 var(--pad-cell-x)", height: 32, background: "var(--ctv-bg-sunken)", borderTop: "1px solid var(--border-hairline)", borderBottom: "1px solid var(--border-hairline)" }}>
                        <span style={{ display: "inline-flex", alignItems: "center", gap: 8 }}>
                          <Ico n="Folder" s={13} color="var(--text-disabled)" />
                          <span style={{ font: "var(--weight-semibold) var(--text-2xs)/1 var(--font-sans)", letterSpacing: "0.05em", textTransform: "uppercase", color: "var(--text-secondary)" }}>{g}</span>
                          <span style={{ ...mono, font: "var(--text-2xs)/1 var(--font-mono)", color: "var(--text-disabled)" }}>{gmap[g].length}</span>
                        </span>
                      </td>
                    </tr>
                    {gmap[g].map((c, i) => renderRow(c, i === 0))}
                  </React.Fragment>
                ))}
              </tbody>
            </table>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "10px 16px", borderTop: "1px solid var(--border-hairline)", font: "var(--text-xs)/1 var(--font-sans)", color: "var(--text-secondary)" }}>
              <span><span style={mono}>{rows.length}</span> of <span style={mono}>128</span> channels · <span style={mono}>{groups.length}</span> groups</span>
              <span style={{ display: "inline-flex", alignItems: "center", gap: 4 }}>
                <IconButton size="sm" title="Prev"><Ico n="ChevronLeft" s={16} /></IconButton>
                <span style={{ ...mono, fontSize: "var(--text-xs)", padding: "0 6px", color: "var(--text-secondary)" }}>1 / 12</span>
                <IconButton size="sm" title="Next"><Ico n="ChevronRight" s={16} /></IconButton>
              </span>
            </div>
          </div>
        </div>
      </div>
    );
  }

  window.CTVChannels = Channels;
})();
