// Decos screen — group'd deco library (list+card view) with a full-detail editor
// for watermark / graphics / break-content / filler override rules per deco.
(function () {
  const NS = window.ChicoryTVDesignSystem_eb3b61;
  const { Button, IconButton, Badge, Card, Input, Select, Checkbox } = NS;
  const Ico = window.Ico;
  const mono = { fontFamily: "var(--font-mono)", fontVariantNumeric: "tabular-nums" };

  const GROUPS = [
    { id: 1, name: "Default" },
    { id: 2, name: "Weeknights" },
    { id: 3, name: "Retro Block" },
  ];

  const DECOS = [
    { id: 101, groupId: 1, name: "Standard Bug" },
    { id: 102, groupId: 1, name: "No Overlay" },
    { id: 201, groupId: 2, name: "News Ticker" },
    { id: 202, groupId: 2, name: "Prime Time Bumper" },
    { id: 301, groupId: 3, name: "Retro Bumper" },
    { id: 302, groupId: 3, name: "VHS Overlay" },
    { id: 303, groupId: 3, name: "Static Break Loop" },
  ];

  const WATERMARK_MODE_OPTIONS = [
    { label: "Inherit", value: "Inherit" },
    { label: "Disable", value: "Disable" },
    { label: "Replace", value: "Override" },
    { label: "Merge", value: "Merge" },
  ];
  const BASIC_MODE_OPTIONS = [
    { label: "Inherit", value: "Inherit" },
    { label: "Disable", value: "Disable" },
    { label: "Override", value: "Override" },
  ];
  const FILLER_TYPE_OPTIONS = [
    { label: "Collection", value: "Collection" },
    { label: "Television Show", value: "TelevisionShow" },
    { label: "Television Season", value: "TelevisionSeason" },
    { label: "Artist", value: "Artist" },
    { label: "Multi Collection", value: "MultiCollection" },
    { label: "Smart Collection", value: "SmartCollection" },
  ];
  const PLACEMENT_LABEL = {
    BlockStart: "Block Start",
    BlockFinish: "Block Finish",
    BetweenBlockItems: "Between Block Items",
    ChapterMarkers: "At Chapter Markers",
  };

  const WATERMARKS = [
    { id: 1, name: "Bug — bottom right" },
    { id: 2, name: "Bug — bottom left, translucent" },
    { id: 3, name: "Station ID corner mark" },
  ];
  const GRAPHICS = [
    { id: 1, name: "Now/Next lower third" },
    { id: 2, name: "Weather crawl" },
    { id: 3, name: "Retro scanlines overlay" },
  ];
  const BREAK_ITEMS = [
    { key: "b1", placement: "BlockStart", collectionType: "Playlist", selectionName: "Bumper Playlist — Retro" },
    { key: "b2", placement: "BetweenBlockItems", collectionType: "Collection", selectionName: "Commercial Bumps 90s" },
    { key: "b3", placement: "ChapterMarkers", collectionType: "Playlist", selectionName: "Station ID Loop" },
  ];

  const EDIT_DRAFT = {
    groupName: "Retro Block",
    name: "Retro Bumper",
    watermarkMode: "Override",
    watermarkIds: [1, 3],
    useWatermarkDuringFiller: true,
    graphicsMode: "Merge",
    graphicsIds: [3],
    useGraphicsDuringFiller: false,
    breakContentMode: "Override",
    defaultFillerMode: "Override",
    defaultFillerType: "Collection",
    defaultFillerName: "Retro Filler Loop",
    defaultFillerTrimToFit: true,
    deadAirMode: "Inherit",
  };

  function Row({ label, children, control = 360, first = false }) {
    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 }}>
          <span style={{ font: "var(--text-sm)/1.3 var(--font-sans)", color: "var(--text-secondary)" }}>{label}</span>
        </div>
        <div style={{ flex: `0 0 ${control}px` }}>{children}</div>
      </div>
    );
  }

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

  function EmptyNote({ children }) {
    return (
      <div style={{ padding: "18px var(--pad-cell-x)", font: "var(--text-sm)/1.4 var(--font-sans)", color: "var(--text-faint)" }}>
        {children}
      </div>
    );
  }

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

  function Decos() {
    const [screen, setScreen] = React.useState("list"); // "list" | "edit"
    const [selectedBreak, setSelectedBreak] = React.useState(BREAK_ITEMS[0].key);
    const [draft, setDraft] = React.useState(EDIT_DRAFT);

    const patch = (p) => setDraft((d) => ({ ...d, ...p }));
    const watermarkActive = draft.watermarkMode === "Override" || draft.watermarkMode === "Merge";
    const graphicsActive = draft.graphicsMode === "Override" || draft.graphicsMode === "Merge";
    const selectedBreakItem = BREAK_ITEMS.find((b) => b.key === selectedBreak) || null;

    const openEditor = () => setScreen("edit");
    const backToList = () => setScreen("list");

    if (screen === "edit") {
      return (
        <div style={{ display: "flex", flexDirection: "column", height: "100%", overflow: "auto" }}>
          {/* 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, position: "sticky", top: 0, background: "var(--surface-app)", zIndex: 3 }}>
            <Button size="sm" variant="ghost" startIcon={<Ico n="ArrowLeft" s={14} />} onClick={backToList}>All decos</Button>
            <span style={{ font: "var(--weight-medium) var(--text-sm)/1 var(--font-sans)", color: "var(--text-secondary)" }}>{draft.groupName} / Edit deco</span>
            <span style={{ flex: 1 }} />
            <Button size="sm" startIcon={<Ico n="Check" s={14} />}>Save deco</Button>
          </div>

          <div style={{ padding: "16px 20px", display: "flex", flexDirection: "column", gap: 16, maxWidth: 900 }}>
            <Card padded={false} title="Deco">
              <Row label="Deco group" first>
                <Input size="sm" disabled value={draft.groupName} />
              </Row>
              <Row label="Deco name">
                <Input size="sm" value={draft.name} onChange={() => {}} />
              </Row>
            </Card>

            <Card padded={false} title="Watermark">
              <Row label="Watermark mode" first>
                <Select value={draft.watermarkMode} options={WATERMARK_MODE_OPTIONS} onChange={(e) => patch({ watermarkMode: e.target.value })} />
              </Row>
              <Row label="Watermarks">
                <MultiSelect options={WATERMARKS} selected={draft.watermarkIds} disabled={!watermarkActive} />
              </Row>
              <Row label="Use watermark during filler">
                <Checkbox checked={draft.useWatermarkDuringFiller} disabled={draft.watermarkMode !== "Override"} onChange={(v) => patch({ useWatermarkDuringFiller: v })} />
              </Row>
            </Card>

            <Card padded={false} title="Graphics elements">
              <Row label="Graphics elements mode" first>
                <Select value={draft.graphicsMode} options={WATERMARK_MODE_OPTIONS} onChange={(e) => patch({ graphicsMode: e.target.value })} />
              </Row>
              <Row label="Graphics elements">
                <MultiSelect options={GRAPHICS} selected={draft.graphicsIds} disabled={!graphicsActive} />
              </Row>
              <Row label="Use graphics elements during filler">
                <Checkbox checked={draft.useGraphicsDuringFiller} disabled={draft.graphicsMode !== "Override"} onChange={(v) => patch({ useGraphicsDuringFiller: v })} />
              </Row>
            </Card>

            <Card
              padded={false}
              title="Break content"
              actions={draft.breakContentMode === "Override" ? <Button size="sm" variant="secondary" startIcon={<Ico n="Plus" s={14} />}>Add break content</Button> : undefined}
            >
              <Row label="Break content mode" first>
                <Select value={draft.breakContentMode} options={BASIC_MODE_OPTIONS} onChange={(e) => patch({ breakContentMode: e.target.value })} />
              </Row>
              {draft.breakContentMode === "Override" && (
                <table style={{ width: "100%", borderCollapse: "collapse" }}>
                  <thead>
                    <tr>
                      {["Placement", "Type", "Name", ""].map((h) => (
                        <th key={h} style={{ textAlign: "left", padding: "0 var(--pad-cell-x)", height: 32, font: "var(--weight-medium) var(--text-2xs)/1 var(--font-sans)", letterSpacing: "0.04em", textTransform: "uppercase", color: "var(--text-disabled)", borderTop: "1px solid var(--border-hairline)", borderBottom: "1px solid var(--border-hairline)", background: "var(--ctv-bg-sunken)" }}>{h}</th>
                      ))}
                    </tr>
                  </thead>
                  <tbody>
                    {BREAK_ITEMS.map((item) => {
                      const active = item.key === selectedBreak;
                      return (
                        <tr key={item.key} onClick={() => setSelectedBreak(item.key)} style={{ cursor: "pointer", background: active ? "var(--ctv-accent-soft)" : "transparent", borderBottom: "1px solid var(--border-hairline)" }}>
                          <td style={{ padding: "0 var(--pad-cell-x)", height: 44, font: "var(--text-sm)/1.3 var(--font-sans)", color: "var(--text-primary)" }}>{PLACEMENT_LABEL[item.placement]}</td>
                          <td style={{ padding: "0 var(--pad-cell-x)", height: 44, font: "var(--text-sm)/1.3 var(--font-sans)", color: "var(--text-secondary)" }}>{item.collectionType}</td>
                          <td style={{ padding: "0 var(--pad-cell-x)", height: 44, font: "var(--text-sm)/1.3 var(--font-sans)", color: "var(--text-secondary)" }}>{item.selectionName}</td>
                          <td style={{ padding: "0 var(--pad-cell-x)", height: 44, textAlign: "right" }} onClick={(e) => e.stopPropagation()}>
                            <IconButton size="sm" variant="ghost" title="Remove"><Ico n="Trash2" s={14} /></IconButton>
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              )}
            </Card>

            {draft.breakContentMode === "Override" && selectedBreakItem && (
              <Card padded={false} title="Break content item">
                <Row label="Placement" first>
                  <Select value={selectedBreakItem.placement} options={Object.entries(PLACEMENT_LABEL).map(([value, label]) => ({ value, label }))} onChange={() => {}} />
                </Row>
                {selectedBreakItem.collectionType === "Playlist" ? (
                  <React.Fragment>
                    <Row label="Playlist group">
                      <Select value="retro" options={[{ value: "retro", label: "Retro Bumpers" }, { value: "news", label: "News Break" }]} onChange={() => {}} />
                    </Row>
                    <Row label="Playlist">
                      <Select value="loop1" options={[{ value: "loop1", label: "Bumper Playlist — Retro" }, { value: "loop2", label: "Late Night Loop" }]} onChange={() => {}} />
                    </Row>
                  </React.Fragment>
                ) : (
                  <Row label="Selection">
                    <Badge tone="accent">{selectedBreakItem.selectionName}</Badge>
                  </Row>
                )}
              </Card>
            )}

            <Card padded={false} title="Default filler">
              <Row label="Default filler mode" first>
                <Select value={draft.defaultFillerMode} options={BASIC_MODE_OPTIONS} onChange={(e) => patch({ defaultFillerMode: e.target.value })} />
              </Row>
              {draft.defaultFillerMode === "Override" && (
                <React.Fragment>
                  <Row label="Collection type">
                    <Select value={draft.defaultFillerType} options={FILLER_TYPE_OPTIONS} onChange={(e) => patch({ defaultFillerType: e.target.value })} />
                  </Row>
                  <Row label={FILLER_TYPE_OPTIONS.find((o) => o.value === draft.defaultFillerType)?.label}>
                    <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
                      <Badge tone="accent">{draft.defaultFillerName}</Badge>
                      <Input size="sm" placeholder="Type to search…" value="" onChange={() => {}} />
                    </div>
                  </Row>
                  <Row label="Trim to fit">
                    <Checkbox checked={draft.defaultFillerTrimToFit} onChange={(v) => patch({ defaultFillerTrimToFit: v })} />
                  </Row>
                </React.Fragment>
              )}
            </Card>

            <Card padded={false} title="Dead air fallback">
              <Row label="Dead air fallback mode" first>
                <Select value={draft.deadAirMode} options={BASIC_MODE_OPTIONS} onChange={(e) => patch({ deadAirMode: e.target.value })} />
              </Row>
              {draft.deadAirMode === "Override" && (
                <Row label="Collection">
                  <Badge tone="accent">(none)</Badge>
                </Row>
              )}
            </Card>
          </div>
        </div>
      );
    }

    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 }}>
          <Badge tone="neutral">{DECOS.length} decos</Badge>
          <span style={{ flex: 1 }} />
          <Button size="sm" startIcon={<Ico n="FolderPlus" s={14} />}>New group</Button>
        </div>

        <div style={{ flex: 1, overflow: "auto", padding: "16px 20px", display: "flex", flexDirection: "column", gap: 16 }}>
          {GROUPS.map((g) => {
            const groupDecos = DECOS.filter((d) => d.groupId === g.id);
            return (
              <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 deco</Button>
                    <IconButton size="sm" variant="ghost" title="Delete group"><Ico n="Trash2" s={14} /></IconButton>
                  </div>
                }
              >
                {groupDecos.length === 0 ? (
                  <EmptyNote>No decos in this group.</EmptyNote>
                ) : (
                  groupDecos.map((d, i) => (
                    <FlushRow key={d.id} first={i === 0}>
                      <Ico n="Palette" s={15} color="var(--ctv-accent)" />
                      <button
                        type="button"
                        onClick={openEditor}
                        style={{ flex: 1, textAlign: "left", background: "none", border: "none", cursor: "pointer", padding: 0, font: "var(--weight-medium) var(--text-sm)/1 var(--font-sans)", color: "var(--text-primary)" }}
                      >
                        {d.name}
                      </button>
                      <IconButton size="sm" variant="ghost" title="Delete deco"><Ico n="Trash2" s={14} /></IconButton>
                    </FlushRow>
                  ))
                )}
              </Card>
            );
          })}
        </div>
      </div>
    );
  }

  window.CTVDecos = Decos;
})();
