// RemoteLibrariesEdit screen — Plex/Jellyfin/Emby library sync preferences: a sortable
// name/media-kind table with a per-row sync Switch, plus a save/discard toolbar.
(function () {
  const NS = window.ChicoryTVDesignSystem_eb3b61;
  const { Button, Card, Switch, Badge } = NS;
  const Ico = window.Ico;
  const mono = { fontFamily: "var(--font-mono)", fontVariantNumeric: "tabular-nums" };

  const LIBRARIES = [
    { id: 1, name: "Movies", mediaKind: "Movies", sync: true },
    { id: 2, name: "TV Shows", mediaKind: "Shows", sync: true },
    { id: 3, name: "Kids Movies", mediaKind: "Movies", sync: false },
    { id: 4, name: "Anime", mediaKind: "Shows", sync: true },
    { id: 5, name: "Home Videos", mediaKind: "OtherVideos", sync: false },
    { id: 6, name: "Music Videos", mediaKind: "MusicVideos", sync: true },
    { id: 7, name: "Live Feeds", mediaKind: "RemoteStreams", sync: false },
    { id: 8, name: "Documentaries", mediaKind: "Movies", sync: true },
  ];

  function formatMediaKind(kind) {
    switch (kind) {
      case "MusicVideos":
        return "Music Videos";
      case "OtherVideos":
        return "Other Videos";
      case "RemoteStreams":
        return "Remote Streams";
      default:
        return kind;
    }
  }

  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: 52, font: "var(--text-sm)/1.3 var(--font-sans)", color: "var(--text-primary)", verticalAlign: "middle" };

  function SortButton({ label, active, dir, onClick }) {
    return (
      <button type="button" onClick={onClick} style={{ display: "inline-flex", alignItems: "center", gap: 6, border: "none", background: "transparent", padding: 0, cursor: "pointer", font: `${active ? "var(--weight-medium)" : "inherit"} inherit`, color: active ? "var(--text-primary)" : "var(--text-disabled)" }}>
        {label}
        <Ico n="ArrowUpDown" s={13} color={active ? "var(--ctv-accent)" : "var(--text-faint)"} />
      </button>
    );
  }

  function RemoteLibrariesEdit() {
    const [sortColumn, setSortColumn] = React.useState("name");
    const [sortDir, setSortDir] = React.useState("asc");
    const [draft, setDraft] = React.useState(LIBRARIES);
    const [saving] = React.useState(false);

    const toggleSort = (col) => {
      if (sortColumn === col) setSortDir((d) => (d === "asc" ? "desc" : "asc"));
      else {
        setSortColumn(col);
        setSortDir("asc");
      }
    };

    const sorted = [...draft].sort((a, b) => {
      const left = sortColumn === "name" ? a.name : a.mediaKind;
      const right = sortColumn === "name" ? b.name : b.mediaKind;
      const cmp = left.localeCompare(right);
      return sortDir === "asc" ? cmp : -cmp;
    });

    const setSync = (id, next) => setDraft((cur) => cur.map((l) => (l.id === id ? { ...l, sync: next } : l)));

    const dirty = draft.some((l) => {
      const orig = LIBRARIES.find((o) => o.id === l.id);
      return orig && orig.sync !== l.sync;
    });

    const syncedCount = draft.filter((l) => l.sync).length;

    return (
      <div style={{ display: "flex", flexDirection: "column", height: "100%" }}>
        {/* header */}
        <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 16, padding: "18px 20px 16px", borderBottom: "1px solid var(--border-hairline)", flex: "0 0 auto" }}>
          <div style={{ minWidth: 0 }}>
            <div style={{ font: "var(--weight-semibold) var(--text-2xs)/1 var(--font-sans)", letterSpacing: "0.06em", textTransform: "uppercase", color: "var(--ctv-accent)" }}>Plex libraries</div>
            <div style={{ marginTop: 6, font: "var(--weight-semibold) var(--text-xl)/1.2 var(--font-sans)", color: "var(--text-primary)" }}>Edit libraries</div>
            <div style={{ marginTop: 4, font: "var(--text-sm)/1.4 var(--font-sans)", color: "var(--text-secondary)" }}>Choose which Plex libraries ErsatzTV syncs.</div>
          </div>
          <Button variant="ghost" startIcon={<Ico n="ArrowLeft" s={14} />}>Back to Plex</Button>
        </div>

        <div style={{ flex: 1, overflow: "auto", padding: "16px 20px" }}>
          {/* summary strip */}
          <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 14, font: "var(--text-xs)/1 var(--font-sans)", color: "var(--text-secondary)" }}>
            <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
              <Ico n="Library" s={13} color="var(--text-disabled)" />
              <span style={mono}>{draft.length}</span> libraries discovered
            </span>
            <span style={{ width: 1, height: 14, background: "var(--border-hairline)" }} />
            <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
              <span style={{ width: 6, height: 6, borderRadius: "50%", background: "var(--status-ok)" }} />
              <span style={mono}>{syncedCount}</span> syncing
            </span>
            {dirty && <Badge tone="warn">Unsaved changes</Badge>}
          </div>

          <Card padded={false}>
            <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}><SortButton label="Name" active={sortColumn === "name"} onClick={() => toggleSort("name")} /></th>
                    <th style={th}><SortButton label="Media Kind" active={sortColumn === "mediaKind"} onClick={() => toggleSort("mediaKind")} /></th>
                    <th style={{ ...th, width: 160 }}>Sync</th>
                  </tr>
                </thead>
                <tbody>
                  {sorted.map((library, i) => (
                    <tr key={library.id} style={{ borderTop: i === 0 ? "none" : "1px solid var(--border-hairline)" }}>
                      <td style={td}>
                        <span style={{ display: "inline-flex", alignItems: "center", gap: 9 }}>
                          <Ico n="Folder" s={14} color="var(--text-disabled)" />
                          <span style={{ font: "var(--weight-medium) var(--text-sm)/1.2 var(--font-sans)" }}>{library.name}</span>
                        </span>
                      </td>
                      <td style={{ ...td, color: "var(--text-secondary)" }}>{formatMediaKind(library.mediaKind)}</td>
                      <td style={td}>
                        <Switch checked={library.sync} disabled={saving} onChange={(next) => setSync(library.id, next)} label={`Sync ${library.name}`} size="sm" />
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </Card>
        </div>

        {/* toolbar */}
        <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "12px 20px", borderTop: "1px solid var(--border-hairline)", flex: "0 0 auto" }}>
          <span style={{ flex: 1 }} />
          <Button disabled={!dirty} variant="ghost">Discard</Button>
          <Button disabled={!dirty} startIcon={<Ico n="Check" s={14} />}>Save</Button>
        </div>
      </div>
    );
  }

  window.CTVRemoteLibrariesEdit = RemoteLibrariesEdit;
})();
