// Blocks screen — grouped block library (list view) drilling into a block editor
// (metadata + ordered item table + item detail form), mirroring BlocksScreen.tsx's
// two-mode layout (list vs. editor) inside one static mockup.
(function () {
  const NS = window.ChicoryTVDesignSystem_eb3b61;
  const { Button, IconButton, Badge, Card, Input, Select, Checkbox, Tooltip } = NS;
  const Ico = window.Ico;
  const mono = { fontFamily: "var(--font-mono)", fontVariantNumeric: "tabular-nums" };

  const GROUPS = [
    {
      id: 1,
      name: "Anime Blocks",
      blocks: [
        { id: 101, name: "Toonami Late Night", minutes: 180 },
        { id: 102, name: "Saturday Morning Anime", minutes: 120 },
      ],
    },
    {
      id: 2,
      name: "News & Talk",
      blocks: [
        { id: 201, name: "Morning Briefing", minutes: 60 },
        { id: 202, name: "Evening Roundup", minutes: 90 },
        { id: 203, name: "Late Edition", minutes: 45 },
      ],
    },
    {
      id: 3,
      name: "Nostalgia",
      blocks: [{ id: 301, name: "90s Sitcom Hour", minutes: 60 }],
    },
    {
      id: 4,
      name: "Holiday Specials",
      blocks: [],
    },
  ];

  const ITEMS = [
    { key: "i1", collection: "Toonami Bumps & Filler", type: "Collection", order: "Shuffle", epg: true, watermarks: false },
    { key: "i2", collection: "Cowboy Bebop", type: "Television Show", order: "Season, Episode", epg: true, watermarks: false },
    { key: "i3", collection: "Trigun", type: "Television Show", order: "Season, Episode", epg: true, watermarks: true },
    { key: "i4", collection: "Late Night Interstitials", type: "Smart Collection", order: "Random", epg: false, watermarks: false },
    { key: "i5", collection: "\"toonami OR bebop\"", type: "Search Query", order: "Chronological", epg: true, watermarks: false },
  ];

  const COLLECTION_TYPE_OPTIONS = ["Collection", "Television Show", "Television Season", "Smart Collection", "Search Query"];
  const PLAYBACK_ORDER_OPTIONS = ["Chronological", "Shuffle", "Random", "Random Rotation"];
  const WATERMARKS = [{ id: 1, name: "Bottom-right bug" }, { id: 2, name: "Corner logo (translucent)" }];
  const GRAPHICS = [{ id: 1, name: "Now Playing lower third" }, { id: 2, name: "Up Next bumper" }];

  function Row({ label, children, control = 360, first }) {
    return (
      <div
        style={{
          display: "flex",
          alignItems: "flex-start",
          gap: 16,
          padding: "12px var(--pad-cell-x)",
          borderTop: first ? "none" : "1px solid var(--border-hairline)",
        }}
      >
        <div style={{ flex: 1, minWidth: 0, paddingTop: 6, font: "var(--text-sm)/1.3 var(--font-sans)", color: "var(--text-secondary)" }}>{label}</div>
        <div style={{ flex: `0 0 ${control}px` }}>{children}</div>
      </div>
    );
  }

  function FlushRow({ children, first }) {
    return (
      <div
        style={{
          display: "flex",
          alignItems: "center",
          gap: 10,
          padding: "0 var(--pad-cell-x)",
          height: 46,
          borderTop: first ? "none" : "1px solid var(--border-hairline)",
        }}
      >
        {children}
      </div>
    );
  }

  function MultiSelectMock({ options, selected }) {
    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
        {options.map((o) => (
          <Checkbox key={o.id} checked={selected.includes(o.id)} label={o.name} onChange={() => {}} />
        ))}
      </div>
    );
  }

  function BlockList({ onOpenBlock }) {
    const totalBlocks = GROUPS.reduce((n, g) => n + g.blocks.length, 0);
    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 }}>
          <Badge tone="neutral">{totalBlocks} blocks</Badge>
          <span style={{ flex: 1 }} />
          <Button size="sm" startIcon={<Ico n="FolderPlus" s={14} />}>New group</Button>
        </div>

        <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "12px 20px", borderBottom: "1px solid var(--border-hairline)", flex: "0 0 auto" }}>
          <div style={{ flex: 1, maxWidth: 360 }}>
            <Input leadingIcon={<Ico n="Search" s={14} />} placeholder="Search for blocks…" value="" onChange={() => {}} />
          </div>
        </div>

        <div style={{ flex: 1, overflow: "auto", padding: "16px 20px", display: "flex", flexDirection: "column", gap: 16 }}>
          {GROUPS.map((g) => (
            <Card
              key={g.id}
              padded={false}
              title={g.name}
              actions={
                <div style={{ display: "flex", gap: 8 }}>
                  <Button size="sm" variant="secondary" startIcon={<Ico n="Plus" s={14} />}>New block</Button>
                  <IconButton size="sm" variant="ghost" title="Delete group"><Ico n="Trash2" s={14} /></IconButton>
                </div>
              }
            >
              {g.blocks.length === 0 ? (
                <div style={{ padding: "18px var(--pad-cell-x)", font: "var(--text-sm)/1.4 var(--font-sans)", color: "var(--text-faint)" }}>No blocks in this group.</div>
              ) : (
                g.blocks.map((b, i) => (
                  <FlushRow key={b.id} first={i === 0}>
                    <Ico n="Boxes" s={15} color="var(--ctv-accent)" />
                    <button
                      type="button"
                      onClick={onOpenBlock}
                      style={{
                        flex: 1,
                        textAlign: "left",
                        background: "none",
                        border: "none",
                        cursor: "pointer",
                        padding: 0,
                        font: "var(--weight-medium) var(--text-sm)/1.3 var(--font-sans)",
                        color: "var(--ctv-accent)",
                      }}
                    >
                      {b.name}
                    </button>
                    <Badge tone="neutral">{b.minutes} min</Badge>
                    <Tooltip label="Copy block"><IconButton size="sm" variant="ghost" title="Copy block"><Ico n="Copy" s={14} /></IconButton></Tooltip>
                    <Tooltip label="Delete block"><IconButton size="sm" variant="ghost" title="Delete block"><Ico n="Trash2" s={14} /></IconButton></Tooltip>
                  </FlushRow>
                ))
              )}
            </Card>
          ))}
        </div>
      </div>
    );
  }

  function BlockEditor({ onBack }) {
    const [selectedKey, setSelectedKey] = React.useState("i2");
    const selected = ITEMS.find((it) => it.key === selectedKey) || 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 }}>
          <Button size="sm" variant="ghost" startIcon={<Ico n="ArrowLeft" s={14} />} onClick={onBack}>All blocks</Button>
          <span style={{ font: "var(--weight-medium) var(--text-sm)/1 var(--font-sans)", color: "var(--text-secondary)" }}>Anime Blocks / Edit block</span>
          <span style={{ flex: 1 }} />
          <Button size="sm" variant="secondary" startIcon={<Ico n="Eye" s={14} />}>Preview</Button>
          <Button size="sm" startIcon={<Ico n="Check" s={14} />}>Save block</Button>
        </div>

        <div style={{ flex: 1, overflow: "auto", padding: "16px 20px", display: "flex", flexDirection: "column", gap: 16 }}>
          <Card padded={false} title="Block">
            <Row control={360} first label="Block group">
              <Input disabled size="sm" value="Anime Blocks" onChange={() => {}} />
            </Row>
            <Row control={360} label="Block name">
              <Input size="sm" value="Toonami Late Night" onChange={() => {}} />
            </Row>
            <Row control={200} label="Duration (hours)">
              <Input size="sm" type="number" trailing="hours" value="3" onChange={() => {}} />
            </Row>
            <Row control={200} label="Duration (minutes)">
              <Select value="0" onChange={() => {}} options={["0", "15", "30", "45"]} />
            </Row>
            <Row control={360} label="Stop scheduling block items">
              <Select value="Before Duration End" onChange={() => {}} options={["Before Duration End", "After Duration End"]} />
            </Row>
          </Card>

          <Card padded={false} title="Block items" actions={<Button size="sm" variant="secondary" startIcon={<Ico n="Plus" s={14} />}>Add item</Button>}>
            <div style={{ overflow: "auto" }}>
              <table style={{ width: "100%", borderCollapse: "collapse" }}>
                <thead>
                  <tr>
                    <th style={{ 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)", borderBottom: "1px solid var(--border-hairline)" }}>Collection</th>
                    <th style={{ 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)", borderBottom: "1px solid var(--border-hairline)" }}>Playback order</th>
                    <th style={{ 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)", borderBottom: "1px solid var(--border-hairline)" }}>Show in EPG</th>
                    <th style={{ 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)", borderBottom: "1px solid var(--border-hairline)" }}>Disable watermarks</th>
                    <th style={{ textAlign: "right", padding: "0 var(--pad-cell-x)", height: 34, borderBottom: "1px solid var(--border-hairline)" }}></th>
                  </tr>
                </thead>
                <tbody>
                  {ITEMS.map((it, index) => {
                    const isSel = it.key === selectedKey;
                    return (
                      <tr
                        key={it.key}
                        onClick={() => setSelectedKey(it.key)}
                        style={{
                          cursor: "pointer",
                          background: isSel ? "var(--ctv-accent-soft)" : "transparent",
                          borderTop: index === 0 ? "none" : "1px solid var(--border-hairline)",
                        }}
                      >
                        <td style={{ padding: "0 var(--pad-cell-x)", height: 48, font: "var(--text-sm)/1.3 var(--font-sans)", color: "var(--text-primary)" }}>
                          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                            <span>{it.collection}</span>
                            <Badge tone="neutral">{it.type}</Badge>
                          </div>
                        </td>
                        <td style={{ padding: "0 var(--pad-cell-x)", height: 48, font: "var(--text-sm)/1.3 var(--font-sans)", color: "var(--text-secondary)" }}>{it.order}</td>
                        <td style={{ padding: "0 var(--pad-cell-x)", height: 48 }} onClick={(e) => e.stopPropagation()}>
                          <Checkbox checked={it.epg} onChange={() => {}} />
                        </td>
                        <td style={{ padding: "0 var(--pad-cell-x)", height: 48 }} onClick={(e) => e.stopPropagation()}>
                          <Checkbox checked={it.watermarks} onChange={() => {}} />
                        </td>
                        <td style={{ padding: "0 var(--pad-cell-x)", height: 48 }} onClick={(e) => e.stopPropagation()}>
                          <div style={{ display: "flex", gap: 2, justifyContent: "flex-end" }}>
                            <IconButton size="sm" variant="ghost" title="Duplicate"><Ico n="Copy" s={14} /></IconButton>
                            <IconButton size="sm" variant="ghost" title="Move up" disabled={index === 0}><Ico n="ArrowUp" s={14} /></IconButton>
                            <IconButton size="sm" variant="ghost" title="Move down" disabled={index === ITEMS.length - 1}><Ico n="ArrowDown" s={14} /></IconButton>
                            <IconButton size="sm" variant="ghost" title="Remove"><Ico n="Trash2" s={14} /></IconButton>
                          </div>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          </Card>

          {selected && (
            <Card padded={false} title="Block item">
              <Row control={360} first label="Collection type">
                <Select value={selected.type === "Television Show" ? "Television Show" : selected.type} onChange={() => {}} options={COLLECTION_TYPE_OPTIONS} />
              </Row>
              <Row control={360} label={selected.type}>
                <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
                  <Badge tone="accent">{selected.collection}</Badge>
                  <Input size="sm" placeholder="Type to search…" value="" onChange={() => {}} />
                </div>
              </Row>
              <Row control={360} label="Playback order">
                <Select value={selected.order} onChange={() => {}} options={PLAYBACK_ORDER_OPTIONS} />
              </Row>
              <Row control={360} label="Watermarks">
                <MultiSelectMock options={WATERMARKS} selected={selected.watermarks ? [1] : []} />
              </Row>
              <Row control={360} label="Graphics elements">
                <MultiSelectMock options={GRAPHICS} selected={[2]} />
              </Row>
            </Card>
          )}
        </div>
      </div>
    );
  }

  function Blocks() {
    const [mode, setMode] = React.useState("list");
    return mode === "list" ? <BlockList onOpenBlock={() => setMode("editor")} /> : <BlockEditor onBack={() => setMode("list")} />;
  }

  window.CTVBlocks = Blocks;
})();
