// Libraries screen — media-source cards (Local/Plex/Jellyfin/Emby), each holding a list of
// per-library rows with scan status/progress, plus an External Collections card for
// Plex/Jellyfin/Emby collection syncs. Mirrors LibrariesScreen.tsx's card+row composition.
(function () {
  const NS = window.ChicoryTVDesignSystem_eb3b61;
  const { Button, IconButton, Badge, StatusDot, ProgressBar, Tooltip } = NS;
  const Ico = window.Ico;
  const mono = { fontFamily: "var(--font-mono)", fontVariantNumeric: "tabular-nums" };

  const SOURCES = [
    {
      id: 1,
      kind: "Local",
      name: "Local Media",
      address: "Local connection",
      icon: "HardDrive",
      scanning: false,
      libraries: [
        { id: 11, name: "Movies", mediaKind: "Movies", icon: "Clapperboard", itemCount: 2418, lastScan: "2026-07-17T04:12:00Z", scanning: false, percent: null },
        { id: 12, name: "TV Shows", mediaKind: "Shows", icon: "MonitorPlay", itemCount: 5104, lastScan: "2026-07-17T04:31:00Z", scanning: false, percent: null },
        { id: 13, name: "Music Videos", mediaKind: "MusicVideos", icon: "Music", itemCount: 312, lastScan: "2026-07-14T22:05:00Z", scanning: false, percent: null },
      ],
    },
    {
      id: 2,
      kind: "Plex",
      name: "Plex Media Server",
      address: "192.168.1.40:32400",
      icon: "Server",
      scanning: true,
      libraries: [
        { id: 21, name: "Plex Movies", mediaKind: "Movies", icon: "Clapperboard", itemCount: 1842, lastScan: "2026-07-17T09:02:00Z", scanning: true, percent: 63 },
        { id: 22, name: "Plex TV", mediaKind: "Shows", icon: "MonitorPlay", itemCount: 3390, lastScan: "2026-07-16T18:44:00Z", scanning: false, percent: null },
      ],
    },
    {
      id: 3,
      kind: "Jellyfin",
      name: "Jellyfin Home Server",
      address: "jellyfin.tblindustries.be",
      icon: "Server",
      scanning: false,
      libraries: [
        { id: 31, name: "Anime", mediaKind: "Shows", icon: "MonitorPlay", itemCount: 861, lastScan: "2026-07-15T11:20:00Z", scanning: false, percent: null },
        { id: 32, name: "Other Videos", mediaKind: "OtherVideos", icon: "Film", itemCount: 204, lastScan: null, scanning: false, percent: null },
      ],
    },
    {
      id: 4,
      kind: "Emby",
      name: "Emby Archive",
      address: "192.168.1.62:8096",
      icon: "Server",
      scanning: false,
      libraries: [
        { id: 41, name: "Retro Cartoons", mediaKind: "Shows", icon: "MonitorPlay", itemCount: 148, lastScan: "2026-07-10T08:00:00Z", scanning: false, percent: null },
      ],
    },
  ];

  const COLLECTIONS_ROWS = [
    { family: "plex", name: "Plex Media Server", scanning: true },
    { family: "jellyfin", name: "Jellyfin Home Server", scanning: false },
    { family: "emby", name: "Emby Archive", scanning: false },
  ];

  function fmtTime(iso) {
    if (!iso) return null;
    const d = new Date(iso);
    return d.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
  }

  function familyLabel(f) {
    return f.charAt(0).toUpperCase() + f.slice(1);
  }

  const cardShell = { display: "flex", flexDirection: "column", gap: 0, border: "1px solid var(--border-hairline)", borderRadius: "var(--radius-md)", background: "var(--surface-card)", overflow: "hidden" };
  const kindIconWrap = (accent) => ({ display: "inline-flex", alignItems: "center", justifyContent: "center", width: 38, height: 38, borderRadius: "var(--radius-sm)", background: accent ? "var(--ctv-accent-soft)" : "var(--ctv-surface-3)", color: accent ? "var(--ctv-accent)" : "var(--text-secondary)", flex: "0 0 auto" });

  function SourceHead({ source }) {
    const accent = source.kind !== "Local";
    return (
      <div style={{ display: "flex", alignItems: "flex-start", gap: 12, padding: "14px 16px" }}>
        <span style={kindIconWrap(accent)}><Ico n={source.icon} s={18} /></span>
        <div style={{ minWidth: 0, flex: 1 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <h3 style={{ margin: 0, font: "var(--weight-semibold) var(--text-md)/1.2 var(--font-sans)", color: "var(--text-primary)" }}>{source.name}</h3>
            <StatusDot status={source.scanning ? "live" : "ok"} label={source.scanning ? "Scanning" : "Synced"} size={7} />
          </div>
          <span style={{ display: "block", marginTop: 2, font: "var(--text-xs)/1.3 var(--font-sans)", color: "var(--text-secondary)" }}>{source.address}</span>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 2, flex: "0 0 auto" }}>
          <Tooltip label={`Scan all libraries in ${source.name}`}>
            <IconButton size="sm" title="Scan all" disabled={source.scanning}><Ico n="RefreshCw" s={15} /></IconButton>
          </Tooltip>
          {source.kind !== "Local" && (
            <Tooltip label={`Manage ${source.name}`}>
              <IconButton size="sm" title="Manage"><Ico n="Settings" s={15} /></IconButton>
            </Tooltip>
          )}
        </div>
      </div>
    );
  }

  function LibraryRow({ library, editable, allowDeepScan }) {
    return (
      <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "10px 16px", borderTop: "1px solid var(--border-hairline)" }}>
        <span style={{ display: "inline-flex", alignItems: "center", justifyContent: "center", width: 26, height: 26, borderRadius: "var(--radius-xs)", background: "var(--ctv-surface-3)", color: "var(--text-secondary)", flex: "0 0 auto" }}>
          <Ico n={library.icon} s={14} />
        </span>
        <div style={{ minWidth: 0, flex: 1 }}>
          <strong style={{ display: "block", font: "var(--weight-medium) var(--text-sm)/1.3 var(--font-sans)", color: "var(--text-primary)" }}>{library.name}</strong>
          <span style={{ display: "block", marginTop: 1, font: "var(--text-xs)/1.3 var(--font-sans)", color: "var(--text-secondary)" }}>
            {library.mediaKind === "MusicVideos" ? "Music Videos" : library.mediaKind === "OtherVideos" ? "Other Videos" : library.mediaKind} · <span style={mono}>{library.itemCount.toLocaleString()}</span> items
          </span>
          <small style={{ display: "block", marginTop: 1, font: "var(--text-2xs)/1.3 var(--font-sans)", color: "var(--text-faint)" }}>
            {library.lastScan ? `Last scan ${fmtTime(library.lastScan)}` : "Never scanned"}
          </small>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 8, flex: "0 0 auto" }}>
          {library.scanning ? (
            <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
              <div style={{ width: 92 }}><ProgressBar value={library.percent} tone="accent" showLabel /></div>
              <Badge tone="accent" dot>Scanning</Badge>
            </div>
          ) : (
            <Badge tone="ok" dot>Synced</Badge>
          )}
          {allowDeepScan && (
            <Tooltip label={`Deep scan ${library.name}`}>
              <IconButton size="sm" title="Deep scan" disabled={library.scanning}><Ico n="ScanSearch" s={15} /></IconButton>
            </Tooltip>
          )}
          <Tooltip label={`Scan ${library.name}`}>
            <IconButton size="sm" title="Scan" disabled={library.scanning}><Ico n="RefreshCw" s={15} /></IconButton>
          </Tooltip>
          {editable && (
            <Tooltip label={`Edit ${library.name}`}>
              <IconButton size="sm" title="Edit"><Ico n="Settings" s={15} /></IconButton>
            </Tooltip>
          )}
        </div>
      </div>
    );
  }

  function SourceCard({ source }) {
    const totalItems = source.libraries.reduce((s, l) => s + l.itemCount, 0);
    const lastScans = source.libraries.map((l) => l.lastScan).filter(Boolean).sort();
    const lastScanLabel = source.scanning ? "Scanning now" : lastScans.length > 0 ? `Last scan ${fmtTime(lastScans[lastScans.length - 1])}` : "Never scanned";
    const isLocal = source.kind === "Local";
    return (
      <div style={cardShell}>
        <SourceHead source={source} />
        <div>
          {source.libraries.map((lib) => (
            <LibraryRow key={lib.id} library={lib} editable={isLocal} allowDeepScan={!isLocal} />
          ))}
        </div>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "10px 16px", borderTop: "1px solid var(--border-hairline)", background: "var(--ctv-bg-sunken)", font: "var(--text-xs)/1 var(--font-sans)", color: "var(--text-secondary)" }}>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}><Ico n="Clock" s={13} color="var(--text-disabled)" />{lastScanLabel}</span>
          <span><span style={mono}>{totalItems.toLocaleString()}</span> items · {source.libraries.length} librar{source.libraries.length === 1 ? "y" : "ies"}</span>
        </div>
      </div>
    );
  }

  function ExternalCollections() {
    return (
      <div style={cardShell}>
        <div style={{ display: "flex", alignItems: "flex-start", gap: 12, padding: "14px 16px" }}>
          <span style={kindIconWrap(false)}><Ico n="Library" s={18} /></span>
          <div style={{ minWidth: 0, flex: 1 }}>
            <h3 style={{ margin: 0, font: "var(--weight-semibold) var(--text-md)/1.2 var(--font-sans)", color: "var(--text-primary)" }}>External Collections</h3>
            <span style={{ display: "block", marginTop: 2, font: "var(--text-xs)/1.3 var(--font-sans)", color: "var(--text-secondary)" }}>Sync Plex, Jellyfin, and Emby collections into ErsatzTV.</span>
          </div>
        </div>
        <div>
          {COLLECTIONS_ROWS.map((row) => (
            <div key={row.family} style={{ display: "flex", alignItems: "center", gap: 12, padding: "10px 16px", borderTop: "1px solid var(--border-hairline)" }}>
              <span style={{ display: "inline-flex", alignItems: "center", justifyContent: "center", width: 26, height: 26, borderRadius: "var(--radius-xs)", background: "var(--ctv-surface-3)", color: "var(--text-secondary)", flex: "0 0 auto" }}>
                <Ico n="Server" s={14} />
              </span>
              <div style={{ minWidth: 0, flex: 1 }}>
                <strong style={{ display: "block", font: "var(--weight-medium) var(--text-sm)/1.3 var(--font-sans)", color: "var(--text-primary)" }}>{row.name}</strong>
                <span style={{ display: "block", marginTop: 1, font: "var(--text-xs)/1.3 var(--font-sans)", color: "var(--text-secondary)" }}>{familyLabel(row.family)} collections</span>
              </div>
              <div style={{ display: "flex", alignItems: "center", gap: 8, flex: "0 0 auto" }}>
                {row.scanning ? <Badge tone="accent" dot>Scanning</Badge> : <Badge tone="ok" dot>Idle</Badge>}
                <Tooltip label={`Deep scan ${row.name} collections`}>
                  <IconButton size="sm" title="Deep scan" disabled={row.scanning}><Ico n="ScanSearch" s={15} /></IconButton>
                </Tooltip>
                <Tooltip label={`Scan ${row.name} collections`}>
                  <IconButton size="sm" title="Scan" disabled={row.scanning}><Ico n="RefreshCw" s={15} /></IconButton>
                </Tooltip>
              </div>
            </div>
          ))}
        </div>
      </div>
    );
  }

  function AddSourceMenu() {
    const [open, setOpen] = React.useState(false);
    return (
      <div style={{ position: "relative" }}>
        <Button variant="primary" startIcon={<Ico n="Plus" s={15} />} onClick={() => setOpen((v) => !v)}>Add Source</Button>
        {open && (
          <div style={{ position: "absolute", top: "calc(100% + 6px)", right: 0, minWidth: 190, padding: 6, borderRadius: "var(--radius-md)", border: "1px solid var(--border-hairline)", background: "var(--surface-raised)", boxShadow: "var(--shadow-pop)", zIndex: 10 }}>
            {[{ icon: "HardDrive", label: "Local library" }, { icon: "Server", label: "Plex" }, { icon: "Server", label: "Jellyfin" }, { icon: "Server", label: "Emby" }].map((it) => (
              <button key={it.label} type="button" style={{ display: "flex", alignItems: "center", gap: 9, width: "100%", padding: "8px 10px", border: "none", background: "transparent", borderRadius: "var(--radius-sm)", cursor: "pointer", font: "var(--text-sm)/1 var(--font-sans)", color: "var(--text-primary)" }}
                onMouseEnter={(e) => (e.currentTarget.style.background = "var(--ctv-surface-2)")}
                onMouseLeave={(e) => (e.currentTarget.style.background = "transparent")}>
                <Ico n={it.icon} s={14} color="var(--text-secondary)" />{it.label}
              </button>
            ))}
          </div>
        )}
      </div>
    );
  }

  function Libraries() {
    const totalItems = SOURCES.reduce((sum, s) => sum + s.libraries.reduce((a, l) => a + l.itemCount, 0), 0);
    const activeScans = SOURCES.reduce((sum, s) => sum + s.libraries.filter((l) => l.scanning).length, 0);

    return (
      <div style={{ display: "flex", flexDirection: "column", height: "100%" }}>
        <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 16, padding: "16px 20px", borderBottom: "1px solid var(--border-hairline)", flex: "0 0 auto" }}>
          <div>
            <span style={{ display: "block", font: "var(--weight-semibold) var(--text-2xs)/1 var(--font-sans)", letterSpacing: "0.06em", textTransform: "uppercase", color: "var(--ctv-accent)" }}>Sources</span>
            <h2 style={{ margin: "4px 0 0", font: "var(--weight-semibold) var(--text-xl)/1.2 var(--font-sans)", color: "var(--text-primary)" }}>Media Libraries</h2>
            <p style={{ margin: "4px 0 0", font: "var(--text-sm)/1.4 var(--font-sans)", color: "var(--text-secondary)" }}>Monitor connected media sources and trigger per-library scans.</p>
          </div>
          <AddSourceMenu />
        </div>

        <div style={{ display: "flex", alignItems: "center", gap: 18, padding: "10px 20px", borderBottom: "1px solid var(--border-hairline)", flex: "0 0 auto", font: "var(--text-xs)/1 var(--font-sans)", color: "var(--text-secondary)" }}>
          <span><span style={mono}>{SOURCES.length}</span> sources</span>
          <span><span style={mono}>{totalItems.toLocaleString()}</span> items</span>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
            <StatusDot status={activeScans > 0 ? "live" : "ok"} size={7} pulse={activeScans > 0} />
            <span style={mono}>{activeScans}</span> active scan{activeScans === 1 ? "" : "s"}
          </span>
        </div>

        <div style={{ flex: 1, overflow: "auto", padding: "16px 20px" }}>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(360px, 1fr))", gap: 16 }}>
            {SOURCES.map((source) => (
              <SourceCard key={source.id} source={source} />
            ))}
          </div>

          <div style={{ marginTop: 16 }}>
            <ExternalCollections />
          </div>
        </div>
      </div>
    );
  }

  window.CTVLibraries = Libraries;
})();
