// Collections screen — manual vs. smart collection management, a flush
// browse list per tab, and a drill-in "manage items" detail pane for a
// manual collection (list + reorder-ready detail, mirroring the live SPA).
(function () {
  const NS = window.ChicoryTVDesignSystem_eb3b61;
  const { Button, IconButton, Badge, Card, Switch } = NS;
  const Ico = window.Ico;
  const mono = { fontFamily: "var(--font-mono)", fontVariantNumeric: "tabular-nums" };

  const MANUAL = [
    { id: 1, name: "Halloween Marathon", custom: true, count: 18 },
    { id: 2, name: "Saturday Morning Cartoons", custom: true, count: 42 },
    { id: 3, name: "Best of Kurosawa", custom: false, count: 11 },
    { id: 4, name: "90s Music Videos", custom: false, count: 63 },
    { id: 5, name: "Rainy Day Comfort Movies", custom: true, count: 9 },
  ];

  const SMART = [
    { id: 1, name: "Recent Action Movies", query: 'genre:"action" AND released:2015-2026', count: 27 },
    { id: 2, name: "80s Synthpop", query: 'genre:"synthpop" AND released:1980-1989', count: 14 },
    { id: 3, name: "Unwatched Documentaries", query: 'genre:"documentary" AND played:false', count: 38 },
  ];

  const ITEMS = [
    { id: 1, title: "The Cat Concerto", type: "Episode" },
    { id: 2, title: "Puss Gets the Boot", type: "Episode" },
    { id: 3, title: "Jerry and the Lion", type: "Episode" },
    { id: 4, title: "The Night Before Halloween", type: "Movie" },
    { id: 5, title: "Trick or Treat House", type: "Movie" },
    { id: 6, title: "Season 3", type: "Season" },
    { id: 7, title: "Hocus Pocus", type: "Movie" },
    { id: 8, title: "The Great Pumpkin", type: "Episode" },
  ];

  const rowStyle = (first) => ({
    display: "flex",
    alignItems: "center",
    gap: 10,
    padding: "0 var(--pad-cell-x)",
    height: 46,
    borderTop: first ? "none" : "1px solid var(--border-hairline)",
  });

  const flushMain = { flex: 1, minWidth: 0, font: "var(--text-sm)/1.3 var(--font-sans)", color: "var(--text-primary)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" };

  function Segmented({ view, setView, counts }) {
    return (
      <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: "manual", l: "Manual", c: counts.manual }, { v: "smart", l: "Smart", c: counts.smart }].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: "var(--text-disabled)" }}>{o.c}</span>
            </button>
          );
        })}
      </div>
    );
  }

  function ManualItemsPane({ collection, onBack }) {
    const [reordering, setReordering] = React.useState(false);
    return (
      <div style={{ display: "flex", flexDirection: "column", height: "100%" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "12px 20px", borderBottom: "1px solid var(--border-hairline)", flex: "0 0 auto", minHeight: 58 }}>
          <Button size="sm" variant="ghost" startIcon={<Ico n="ArrowLeft" s={14} />} onClick={onBack}>All collections</Button>
          <span style={{ font: "var(--weight-medium) var(--text-sm)/1 var(--font-sans)", color: "var(--text-primary)" }}>{collection.name}</span>
          <span style={{ flex: 1 }} />
          {collection.custom && !reordering && (
            <Button size="sm" variant="secondary" startIcon={<Ico n="ArrowUp" s={14} />} onClick={() => setReordering(true)}>Reorder</Button>
          )}
          <Button size="sm" variant="primary" startIcon={<Ico n="Plus" s={14} />} disabled={reordering}>Add items</Button>
        </div>

        <div style={{ flex: 1, overflow: "auto", padding: "16px 20px" }}>
          <Card padded={false}>
            {ITEMS.map((item, i) => (
              <div key={item.id} style={rowStyle(i === 0)}>
                <Ico n="ListVideo" s={15} color="var(--text-disabled)" />
                <span style={flushMain}>{item.title}</span>
                <Badge tone="neutral">{item.type}</Badge>
                {reordering ? (
                  <React.Fragment>
                    <IconButton size="sm" variant="ghost" title={`Move ${item.title} up`} disabled={i === 0}><Ico n="ArrowUp" s={14} /></IconButton>
                    <IconButton size="sm" variant="ghost" title={`Move ${item.title} down`} disabled={i === ITEMS.length - 1}><Ico n="ArrowDown" s={14} /></IconButton>
                  </React.Fragment>
                ) : (
                  <IconButton size="sm" variant="ghost" title={`Remove ${item.title}`}><Ico n="Trash2" s={14} /></IconButton>
                )}
              </div>
            ))}
          </Card>
        </div>

        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "10px 20px", borderTop: "1px solid var(--border-hairline)", flex: "0 0 auto" }}>
          {reordering ? (
            <React.Fragment>
              <span style={{ font: "var(--text-xs)/1 var(--font-sans)", color: "var(--text-secondary)" }}><span style={mono}>{ITEMS.length}</span> items</span>
              <div style={{ display: "flex", gap: 8 }}>
                <Button size="sm" variant="ghost" onClick={() => setReordering(false)}>Cancel</Button>
                <Button size="sm" variant="primary" onClick={() => setReordering(false)}>Save order</Button>
              </div>
            </React.Fragment>
          ) : (
            <span style={{ font: "var(--text-xs)/1 var(--font-sans)", color: "var(--text-secondary)" }}>Showing <span style={mono}>{ITEMS.length}</span> of <span style={mono}>{collection.count}</span></span>
          )}
        </div>
      </div>
    );
  }

  function Collections() {
    const [view, setView] = React.useState("manual");
    const [selected, setSelected] = React.useState(null);

    if (selected) {
      return <ManualItemsPane collection={selected} onBack={() => setSelected(null)} />;
    }

    return (
      <div style={{ display: "flex", flexDirection: "column", height: "100%" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "12px 20px", borderBottom: "1px solid var(--border-hairline)", flex: "0 0 auto", minHeight: 58 }}>
          <Segmented view={view} setView={setView} counts={{ manual: MANUAL.length, smart: SMART.length }} />
          <span style={{ flex: 1 }} />
          {view === "manual" ? (
            <Button variant="primary" size="sm" startIcon={<Ico n="Plus" s={14} />}>New collection</Button>
          ) : (
            <Button variant="primary" size="sm" startIcon={<Ico n="Plus" s={14} />}>New smart collection</Button>
          )}
        </div>

        <div style={{ flex: 1, overflow: "auto", padding: "16px 20px" }}>
          {view === "manual" ? (
            <Card padded={false}>
              {MANUAL.map((c, i) => (
                <div key={c.id} style={rowStyle(i === 0)}>
                  <Ico n="FolderTree" s={15} color="var(--ctv-accent)" />
                  <button type="button" onClick={() => setSelected(c)}
                    style={{ ...flushMain, textAlign: "left", background: "none", border: "none", padding: 0, cursor: "pointer", font: "var(--weight-medium) var(--text-sm)/1.3 var(--font-sans)", color: "var(--text-primary)" }}>
                    {c.name}
                  </button>
                  <span style={{ ...mono, font: "var(--text-2xs)/1 var(--font-mono)", color: "var(--text-disabled)" }}>{c.count} items</span>
                  <label style={{ display: "inline-flex", alignItems: "center", gap: 7, cursor: "pointer" }} title="Use custom playback order">
                    <Switch checked={c.custom} size="sm" />
                    <span style={{ font: "var(--text-xs)/1 var(--font-sans)", color: "var(--text-secondary)" }}>Custom order</span>
                  </label>
                  <IconButton size="sm" variant="ghost" title="Manage items" onClick={() => setSelected(c)}><Ico n="ListVideo" s={14} /></IconButton>
                  <IconButton size="sm" variant="ghost" title="Rename"><Ico n="Pencil" s={14} /></IconButton>
                  <IconButton size="sm" variant="ghost" title="Delete"><Ico n="Trash2" s={14} /></IconButton>
                </div>
              ))}
            </Card>
          ) : (
            <Card padded={false}>
              {SMART.map((c, i) => (
                <div key={c.id} style={rowStyle(i === 0)}>
                  <Ico n="Sparkles" s={15} color="var(--ctv-accent)" />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ font: "var(--weight-medium) var(--text-sm)/1.3 var(--font-sans)", color: "var(--text-primary)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{c.name}</div>
                    <div style={{ ...mono, marginTop: 2, font: "var(--text-2xs)/1.3 var(--font-mono)", color: "var(--text-disabled)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{c.query}</div>
                  </div>
                  <span style={{ ...mono, font: "var(--text-2xs)/1 var(--font-mono)", color: "var(--text-disabled)" }}>{c.count} matches</span>
                  <IconButton size="sm" variant="ghost" title="Edit"><Ico n="Pencil" s={14} /></IconButton>
                  <IconButton size="sm" variant="ghost" title="Delete"><Ico n="Trash2" s={14} /></IconButton>
                </div>
              ))}
            </Card>
          )}

          <div style={{ display: "flex", alignItems: "flex-start", gap: 10, marginTop: 16, padding: "12px 14px", borderRadius: "var(--radius-md)", background: "var(--ctv-surface-2)", border: "1px solid var(--border-hairline)" }}>
            <Ico n="Info" s={14} color="var(--text-disabled)" />
            <span style={{ font: "var(--text-xs)/1.5 var(--font-sans)", color: "var(--text-secondary)" }}>
              Multi-collections, rerun collections and playlists aren't available here yet — manage them in the Classic UI for now.
            </span>
          </div>
        </div>
      </div>
    );
  }

  window.CTVCollections = Collections;
})();
