// Templates screen — a group'd list of daily/weekly block templates (list view) with a detail
// editor view (name + block-group/block/start-time picker + a time-ordered items table).
(function () {
  const NS = window.ChicoryTVDesignSystem_eb3b61;
  const { Button, IconButton, Badge, Card, Input, Select } = NS;
  const Ico = window.Ico;
  const mono = { fontFamily: "var(--font-mono)", fontVariantNumeric: "tabular-nums" };

  const GROUPS = [
    {
      id: 1,
      name: "Weekday Rotation",
      templates: [
        { id: 101, name: "Weekday Daytime" },
        { id: 102, name: "Weekday Primetime" },
        { id: 103, name: "Weekday Overnight" },
      ],
    },
    {
      id: 2,
      name: "Weekend Rotation",
      templates: [
        { id: 201, name: "Saturday Marathon" },
        { id: 202, name: "Sunday Wind-down" },
      ],
    },
    {
      id: 3,
      name: "Holiday",
      templates: [{ id: 301, name: "Christmas Eve Block" }],
    },
    { id: 4, name: "Seasonal Specials", templates: [] },
  ];

  const TEMPLATE_ITEMS = [
    { start: "00:00", end: "02:00", block: "Overnight Cartoons" },
    { start: "02:00", end: "06:00", block: "Late Night Sitcoms" },
    { start: "06:00", end: "09:00", block: "Morning News Loop" },
    { start: "09:00", end: "12:00", block: "Daytime Talk" },
    { start: "12:00", end: "15:00", block: "Afternoon Movie" },
    { start: "15:00", end: "18:00", block: "80s Block" },
    { start: "18:00", end: "20:00", block: "Evening News" },
    { start: "20:00", end: "24:00", block: "Primetime Drama" },
  ];

  const GROUP_OPTIONS = [
    { label: "Select a block group…", value: "" },
    { label: "Cartoons", value: "cartoons" },
    { label: "News", value: "news" },
    { label: "Drama", value: "drama" },
  ];
  const BLOCK_OPTIONS = [
    { label: "Select a block…", value: "" },
    { label: "Tom & Jerry Marathon", value: "tj" },
    { label: "World Tonight", value: "wt" },
    { label: "80s Synthpop Hour", value: "synth" },
  ];
  const START_OPTIONS = ["00:00", "00:05", "00:10", "06:00", "12:00", "18:00", "20:00"].map((t) => ({
    label: t,
    value: t,
  }));

  const rowFlush = {
    display: "flex",
    alignItems: "center",
    gap: 10,
    padding: "0 16px",
    height: 44,
    borderTop: "1px solid var(--border-hairline)",
  };

  function ListView({ onOpen }) {
    const totalTemplates = GROUPS.reduce((n, g) => n + g.templates.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",
          }}
        >
          <Badge tone="neutral">{totalTemplates} templates</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",
          }}
        >
          <Input leadingIcon={<Ico n="Search" s={14} />} placeholder="Search for templates…" value="" fullWidth />
        </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 template
                  </Button>
                  <IconButton size="sm" variant="ghost" title="Delete group">
                    <Ico n="Trash2" s={14} />
                  </IconButton>
                </div>
              }
            >
              {g.templates.length === 0 ? (
                <div style={{ padding: "18px 16px", font: "var(--text-sm)/1.4 var(--font-sans)", color: "var(--text-faint)" }}>
                  No templates in this group.
                </div>
              ) : (
                g.templates.map((t, i) => (
                  <div key={t.id} style={i === 0 ? { ...rowFlush, borderTop: "none" } : rowFlush}>
                    <button
                      type="button"
                      onClick={() => onOpen(g, t)}
                      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(--ctv-accent)",
                      }}
                    >
                      {t.name}
                    </button>
                    <IconButton size="sm" variant="ghost" title="Copy template">
                      <Ico n="Copy" s={14} />
                    </IconButton>
                    <IconButton size="sm" variant="ghost" title="Delete template">
                      <Ico n="Trash2" s={14} />
                    </IconButton>
                  </div>
                ))
              )}
            </Card>
          ))}
        </div>
      </div>
    );
  }

  function EditorView({ group, template, onBack }) {
    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",
          }}
        >
          <Button size="sm" variant="ghost" startIcon={<Ico n="ArrowLeft" s={14} />} onClick={onBack}>
            All templates
          </Button>
          <span style={{ font: "var(--text-sm)/1 var(--font-sans)", color: "var(--text-secondary)" }}>
            {group.name} / Edit template
          </span>
          <span style={{ flex: 1 }} />
          <Button size="sm" startIcon={<Ico n="Check" s={14} />}>
            Save template
          </Button>
        </div>

        <div style={{ flex: 1, overflow: "auto", padding: "16px 20px", display: "flex", flexDirection: "column", gap: 16 }}>
          <Card padded={false} title="Template">
            <div style={{ ...rowFlush, borderTop: "none", height: 52 }}>
              <div style={{ width: 220, font: "var(--text-sm)/1 var(--font-sans)", color: "var(--text-secondary)" }}>
                Template group
              </div>
              <div style={{ flex: "0 0 360px" }}>
                <Input disabled size="sm" value={group.name} fullWidth />
              </div>
            </div>
            <div style={{ ...rowFlush, height: 52 }}>
              <div style={{ width: 220, font: "var(--text-sm)/1 var(--font-sans)", color: "var(--text-secondary)" }}>
                Template name
              </div>
              <div style={{ flex: "0 0 360px" }}>
                <Input size="sm" value={template.name} fullWidth />
              </div>
            </div>
          </Card>

          <Card padded={false} title="Add content">
            <div style={{ display: "flex", gap: 12, padding: 16, flexWrap: "wrap", alignItems: "flex-end" }}>
              <div style={{ minWidth: 200 }}>
                <Select label="Block group" value="" options={GROUP_OPTIONS} />
              </div>
              <div style={{ minWidth: 200 }}>
                <Select label="Block" value="" options={BLOCK_OPTIONS} />
              </div>
              <div style={{ minWidth: 140 }}>
                <Select label="Start time" value="00:00" options={START_OPTIONS} />
              </div>
              <Button size="sm" startIcon={<Ico n="Plus" s={14} />}>
                Add
              </Button>
            </div>
          </Card>

          <Card padded={false} title="Template items">
            <table style={{ width: "100%", borderCollapse: "collapse" }}>
              <thead>
                <tr>
                  <th
                    style={{
                      textAlign: "left",
                      padding: "0 16px",
                      height: 32,
                      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)",
                    }}
                  >
                    Time
                  </th>
                  <th
                    style={{
                      textAlign: "left",
                      padding: "0 16px",
                      height: 32,
                      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)",
                    }}
                  >
                    Block
                  </th>
                  <th
                    style={{
                      width: 50,
                      borderBottom: "1px solid var(--border-hairline)",
                    }}
                  />
                </tr>
              </thead>
              <tbody>
                {TEMPLATE_ITEMS.map((it, i) => (
                  <tr key={i} style={{ borderTop: "1px solid var(--border-hairline)" }}>
                    <td style={{ ...mono, padding: "0 16px", height: 44, font: "var(--text-sm)/1 var(--font-mono)", color: "var(--text-primary)" }}>
                      {it.start}-{it.end}
                    </td>
                    <td style={{ padding: "0 16px", height: 44, font: "var(--text-sm)/1 var(--font-sans)", color: "var(--text-primary)" }}>
                      {it.block}
                    </td>
                    <td style={{ padding: "0 16px", textAlign: "right" }}>
                      <IconButton size="sm" variant="ghost" title="Remove">
                        <Ico n="Trash2" s={14} />
                      </IconButton>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </Card>
        </div>
      </div>
    );
  }

  function Templates() {
    const [open, setOpen] = React.useState(null); // { group, template } | null

    if (open) {
      return <EditorView group={open.group} template={open.template} onBack={() => setOpen(null)} />;
    }
    return <ListView onOpen={(group, template) => setOpen({ group, template })} />;
  }

  window.CTVTemplates = Templates;
})();
