// Playout Schedules screen — priority-ordered recurrence-rule editors for a single playout:
// "Templates" (block playouts, template + deco template + preview calendar) and "Alternate
// schedules" (classic playouts, schedule + catch-all default row). Master list + detail-edit
// pane, day/month chip pickers, and an optional month preview grid.
(function () {
  const NS = window.ChicoryTVDesignSystem_eb3b61;
  const { Button, IconButton, Badge, Card, Select, Checkbox } = NS;
  const Ico = window.Ico;
  const mono = { fontFamily: "var(--font-mono)", fontVariantNumeric: "tabular-nums" };

  const DAYS_OF_WEEK = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
  const SHORT_DAY = (d) => d.slice(0, 3);
  const MONTHS = Array.from({ length: 12 }, (_, i) => i + 1);
  const MONTH_NAME = (m, style) =>
    ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"][m - 1]
      ? style === "short"
        ? ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"][m - 1]
        : ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"][m - 1]
      : "";
  const DAYS_OF_MONTH = Array.from({ length: 31 }, (_, i) => i + 1);

  // ----- mock data -----

  const TEMPLATE_ITEMS = [
    { id: 1, name: "Weekday / Daytime block", deco: "None", dow: "Mon, Tue, Wed, Thu, Fri", dom: "any", months: "any" },
    { id: 2, name: "Weekend / Cartoon marathon", deco: "Weekend Bug", dow: "Sat, Sun", dom: "any", months: "any" },
    { id: 3, name: "Holiday / Christmas block", deco: "Holiday Overlay", dow: "any", dom: "24-26", months: "Dec" },
    { id: 4, name: "Prime Time / Default", deco: "None", dow: "any", dom: "any", months: "any", isDefault: true },
  ];

  const ALT_ITEMS = [
    { id: 1, name: "Marathon Weekend", dow: "Sat, Sun", dom: "any", months: "any" },
    { id: 2, name: "Holiday Programming", dow: "any", dom: "20-31", months: "Dec" },
    { id: 3, name: "Standard Rotation", dow: "any", dom: "any", months: "any", isDefault: true },
  ];

  const PREVIEW_WEEKS = [
    [null, null, null, 1, 2, 3, 4],
    [5, 6, 7, 8, 9, 10, 11],
    [12, 13, 14, 15, 16, 17, 18],
    [19, 20, 21, 22, 23, 24, 25],
    [26, 27, 28, 29, 30, 31, null],
  ];
  const WEEKEND_DAYS = new Set([1, 2, 8, 9, 15, 16, 22, 23, 29, 30]);
  const HOLIDAY_DAYS = new Set([24, 25, 26]);
  function previewWinner(day) {
    if (day === null) return null;
    if (HOLIDAY_DAYS.has(day)) return "Holiday / Christmas block";
    if (WEEKEND_DAYS.has(day)) return "Weekend / Cartoon marathon";
    return "Weekday / Daytime block";
  }

  const rowLabel = { padding: "0 var(--pad-cell-x)", height: 30, font: "var(--weight-medium) var(--text-2xs)/1 var(--font-sans)", letterSpacing: "0.04em", textTransform: "uppercase", color: "var(--text-disabled)", textAlign: "left", whiteSpace: "nowrap", position: "sticky", top: 0, background: "var(--surface-card)", borderBottom: "1px solid var(--border-hairline)" };
  const td = { padding: "0 var(--pad-cell-x)", height: 46, font: "var(--text-sm)/1.3 var(--font-sans)", color: "var(--text-primary)", verticalAlign: "middle" };

  function Chip({ label, active, onClick }) {
    return (
      <button
        type="button"
        onClick={onClick}
        style={{
          display: "inline-flex", alignItems: "center", justifyContent: "center", minWidth: 30, height: 26, padding: "0 8px",
          borderRadius: "var(--radius-sm)", cursor: "pointer",
          border: active ? "1px solid var(--ctv-accent)" : "1px solid var(--border-control)",
          background: active ? "var(--ctv-accent-soft)" : "var(--ctv-surface-2)",
          color: active ? "var(--ctv-accent)" : "var(--text-secondary)",
          font: `${active ? "var(--weight-semibold)" : "var(--weight-normal)"} var(--text-xs)/1 var(--font-sans)`,
          transition: "background var(--dur-fast), color var(--dur-fast), border-color var(--dur-fast)",
        }}
      >
        {label}
      </button>
    );
  }

  function FieldRow({ label, children }) {
    return (
      <div style={{ display: "flex", alignItems: "flex-start", gap: 16, padding: "12px var(--pad-card)", borderTop: "1px solid var(--border-hairline)" }}>
        <div style={{ width: 160, flex: "0 0 160px", paddingTop: 6, font: "var(--weight-medium) var(--text-sm)/1.3 var(--font-sans)", color: "var(--text-secondary)" }}>{label}</div>
        <div style={{ flex: 1, minWidth: 0 }}>{children}</div>
      </div>
    );
  }

  function RecurrenceEditor({ disabled, disabledNote }) {
    const [limitRange, setLimitRange] = React.useState(false);
    const [dow, setDow] = React.useState(new Set(["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]));
    const [dom, setDom] = React.useState(new Set(DAYS_OF_MONTH));
    const [mo, setMo] = React.useState(new Set(MONTHS));
    const toggleSet = (set, setter, v) => {
      const next = new Set(set);
      next.has(v) ? next.delete(v) : next.add(v);
      setter(next);
    };
    return (
      <React.Fragment>
        {disabled && disabledNote && (
          <div style={{ margin: "12px var(--pad-card) 0", padding: "10px 12px", borderRadius: "var(--radius-sm)", background: "var(--ctv-surface-2)", border: "1px solid var(--border-hairline)", font: "var(--text-xs)/1.4 var(--font-sans)", color: "var(--text-secondary)", display: "flex", gap: 8, alignItems: "flex-start" }}>
            <Ico n="Info" s={14} color="var(--text-disabled)" />
            <span>{disabledNote}</span>
          </div>
        )}

        <FieldRow label="Limit to date range">
          <Checkbox checked={limitRange} disabled={disabled} onChange={() => setLimitRange((v) => !v)} label="Restrict to a start/end day" />
        </FieldRow>

        {limitRange && (
          <React.Fragment>
            <FieldRow label="Start day">
              <div style={{ display: "flex", gap: 8 }}>
                <Select disabled={disabled} value="12" options={MONTHS.map((m) => ({ value: String(m), label: MONTH_NAME(m, "long") }))} />
                <Select disabled={disabled} value="20" options={DAYS_OF_MONTH.map((d) => ({ value: String(d), label: String(d) }))} />
                <Select disabled={disabled} value="" options={[{ value: "", label: "Any" }, { value: "2026", label: "2026" }, { value: "2027", label: "2027" }]} />
              </div>
            </FieldRow>
            <FieldRow label="End day">
              <div style={{ display: "flex", gap: 8 }}>
                <Select disabled={disabled} value="1" options={MONTHS.map((m) => ({ value: String(m), label: MONTH_NAME(m, "long") }))} />
                <Select disabled={disabled} value="2" options={DAYS_OF_MONTH.map((d) => ({ value: String(d), label: String(d) }))} />
                <Select disabled={disabled} value="" options={[{ value: "", label: "Any" }, { value: "2026", label: "2026" }, { value: "2027", label: "2027" }]} />
              </div>
            </FieldRow>
          </React.Fragment>
        )}

        <FieldRow label="Days of the week">
          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
              {DAYS_OF_WEEK.map((d) => (
                <Chip key={d} label={SHORT_DAY(d)} active={dow.has(d)} onClick={() => toggleSet(dow, setDow, d)} />
              ))}
            </div>
            <div style={{ display: "flex", gap: 8 }}>
              <Button size="sm" variant="ghost" disabled={disabled} onClick={() => setDow(new Set(["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]))}>Weekdays</Button>
              <Button size="sm" variant="ghost" disabled={disabled} onClick={() => setDow(new Set(["Saturday", "Sunday"]))}>Weekends</Button>
            </div>
          </div>
        </FieldRow>

        <FieldRow label="Days of the month">
          <div style={{ display: "flex", flexWrap: "wrap", gap: 6, maxWidth: 560 }}>
            {DAYS_OF_MONTH.map((d) => (
              <Chip key={d} label={String(d)} active={dom.has(d)} onClick={() => toggleSet(dom, setDom, d)} />
            ))}
          </div>
        </FieldRow>

        <FieldRow label="Months">
          <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
            {MONTHS.map((m) => (
              <Chip key={m} label={MONTH_NAME(m, "short")} active={mo.has(m)} onClick={() => toggleSet(mo, setMo, m)} />
            ))}
          </div>
        </FieldRow>
      </React.Fragment>
    );
  }

  function ScheduleTable({ mode, items, selected, onSelect }) {
    const primaryLabel = mode === "templates" ? "Template" : "Schedule";
    return (
      <Card padded={false} title={primaryLabel + "s"}>
        <div style={{ overflow: "auto" }}>
          <table style={{ width: "100%", borderCollapse: "collapse" }}>
            <thead>
              <tr>
                <th style={rowLabel}>{primaryLabel}</th>
                <th style={rowLabel}>Days of the week</th>
                <th style={rowLabel}>Days of the month</th>
                <th style={rowLabel}>Months</th>
                <th style={{ ...rowLabel, textAlign: "right" }}></th>
              </tr>
            </thead>
            <tbody>
              {items.map((it, i) => {
                const isSel = selected === it.id;
                return (
                  <tr
                    key={it.id}
                    onClick={() => onSelect(it.id)}
                    style={{
                      cursor: "pointer",
                      borderTop: i === 0 ? "none" : "1px solid var(--border-hairline)",
                      background: isSel ? "var(--ctv-accent-soft)" : "transparent",
                      transition: "background var(--dur-fast)",
                    }}
                  >
                    <td style={td}>
                      <span style={{ font: "var(--weight-medium) var(--text-sm)/1.3 var(--font-sans)" }}>{it.name}</span>
                      {it.isDefault && <React.Fragment>{" "}<Badge tone="accent">Default</Badge></React.Fragment>}
                    </td>
                    <td style={{ ...td, color: "var(--text-secondary)" }}>{it.dow}</td>
                    <td style={{ ...td, color: "var(--text-secondary)" }}>{it.dom}</td>
                    <td style={{ ...td, color: "var(--text-secondary)" }}>{it.months}</td>
                    <td style={{ ...td, width: 130 }}>
                      <div style={{ display: "flex", justifyContent: "flex-end", gap: 4 }} onClick={(e) => e.stopPropagation()}>
                        <IconButton size="sm" title="Move up" variant="ghost" disabled={i === 0}><Ico n="ArrowUp" s={14} /></IconButton>
                        <IconButton size="sm" title="Move down" variant="ghost" disabled={i === items.length - 1}><Ico n="ArrowDown" s={14} /></IconButton>
                        <IconButton size="sm" title="Delete" variant="ghost" disabled={items.length === 1}><Ico n="Trash2" s={14} /></IconButton>
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </Card>
    );
  }

  function PreviewCalendar() {
    return (
      <Card padded={false} title="Preview calendar">
        <div style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 10, padding: "12px 0" }}>
          <IconButton size="sm" variant="ghost" title="Previous month"><Ico n="ArrowLeft" s={14} /></IconButton>
          <span style={{ minWidth: 160, textAlign: "center", font: "var(--weight-medium) var(--text-sm)/1 var(--font-sans)", color: "var(--text-primary)" }}>December 2026</span>
          <IconButton size="sm" variant="ghost" title="Next month"><Ico n="ArrowRight" s={14} /></IconButton>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(7, 1fr)", gap: 4, padding: "0 var(--pad-card) var(--pad-card)" }}>
          {["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"].map((d) => (
            <div key={d} style={{ textAlign: "center", font: "var(--weight-semibold) var(--text-2xs)/1 var(--font-sans)", color: "var(--text-disabled)", padding: "0 0 6px" }}>{d}</div>
          ))}
          {PREVIEW_WEEKS.flat().map((day, idx) => {
            if (day === null) return <div key={"b" + idx} />;
            const winner = previewWinner(day);
            const isHoliday = HOLIDAY_DAYS.has(day);
            const isWeekend = WEEKEND_DAYS.has(day);
            return (
              <div key={day} style={{
                minHeight: 54, borderRadius: "var(--radius-sm)", padding: "4px 6px",
                border: "1px solid var(--border-hairline)",
                background: isHoliday ? "var(--ctv-warn-soft)" : isWeekend ? "var(--ctv-accent-soft)" : "var(--ctv-surface-2)",
              }}>
                <div style={{ ...mono, font: "var(--text-2xs)/1 var(--font-mono)", color: "var(--text-disabled)" }}>{day}</div>
                {winner && <div style={{ marginTop: 4, font: "var(--text-2xs)/1.3 var(--font-sans)", color: "var(--text-secondary)", overflow: "hidden", textOverflow: "ellipsis", display: "-webkit-box", WebkitLineClamp: 2, WebkitBoxOrient: "vertical" }}>{winner}</div>}
              </div>
            );
          })}
        </div>
      </Card>
    );
  }

  function PlayoutScheduleEditors() {
    const [mode, setMode] = React.useState("templates"); // "templates" | "alternates"
    const items = mode === "templates" ? TEMPLATE_ITEMS : ALT_ITEMS;
    const [selected, setSelected] = React.useState(items[0].id);
    const [showPreview, setShowPreview] = React.useState(true);

    React.useEffect(() => { setSelected(items[0].id); }, [mode]); // eslint-disable-line

    const sel = items.find((i) => i.id === selected) || null;
    const isDefaultSelected = sel && sel.isDefault;

    const Segmented = () => (
      <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: "templates", l: "Templates" }, { v: "alternates", l: "Alternate schedules" }].map((o) => {
          const on = o.v === mode;
          return (
            <button key={o.v} type="button" onClick={() => setMode(o.v)}
              style={{ display: "inline-flex", alignItems: "center", 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}
            </button>
          );
        })}
      </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 }}>
          <Button size="sm" variant="ghost" startIcon={<Ico n="ArrowLeft" s={14} />}>All playouts</Button>
          <span style={{ width: 1, height: 18, background: "var(--border-hairline)" }} />
          <span style={{ font: "var(--weight-medium) var(--text-sm)/1 var(--font-sans)", color: "var(--text-primary)" }}>
            Weeknight Movies <span style={{ color: "var(--text-disabled)" }}>/</span> {mode === "templates" ? "Templates" : "Alternate schedules"}
          </span>
          <span style={{ flex: 1 }} />
          <Button size="sm" variant="secondary" startIcon={<Ico n="Plus" s={14} />}>Add</Button>
          <Button size="sm" variant="primary" startIcon={<Ico n="Check" s={14} />}>Save</Button>
        </div>

        <div style={{ flex: 1, overflow: "auto", padding: "16px 20px", display: "flex", flexDirection: "column", gap: 16 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 16 }}>
            <Segmented />
            <span style={{ font: "var(--text-xs)/1.4 var(--font-sans)", color: "var(--text-secondary)" }}>
              {mode === "templates"
                ? "In priority order from top to bottom. Each template optionally applies a deco template."
                : "In priority order from top to bottom. The last entry always matches every day and month as the catch-all default, and its schedule becomes the playout's default schedule."}
            </span>
          </div>

          <ScheduleTable mode={mode} items={items} selected={selected} onSelect={setSelected} />

          {mode === "templates" && (
            <React.Fragment>
              <div>
                <Button size="sm" variant="ghost" startIcon={<Ico n="CalendarDays" s={14} />} onClick={() => setShowPreview((v) => !v)}>
                  {showPreview ? "Hide preview calendar" : "Preview calendar"}
                </Button>
              </div>
              {showPreview && <PreviewCalendar />}
            </React.Fragment>
          )}

          {sel && (
            <Card padded={false} title={mode === "templates" ? "Edit template" : "Edit schedule"}>
              <FieldRow label={mode === "templates" ? "Template" : "Schedule"}>
                <div style={{ maxWidth: 360 }}>
                  <Select
                    value={String(sel.id)}
                    options={items.map((i) => ({ value: String(i.id), label: i.name }))}
                  />
                </div>
              </FieldRow>
              {mode === "templates" && (
                <FieldRow label="Deco template">
                  <div style={{ maxWidth: 360 }}>
                    <Select
                      value={sel.deco}
                      options={[{ value: "None", label: "None" }, { value: "Weekend Bug", label: "Marketing / Weekend Bug" }, { value: "Holiday Overlay", label: "Seasonal / Holiday Overlay" }]}
                    />
                  </div>
                </FieldRow>
              )}
              <RecurrenceEditor
                disabled={mode === "alternates" && isDefaultSelected}
                disabledNote="The default entry always matches every day; reorder it above another entry to scope it."
              />
            </Card>
          )}
        </div>
      </div>
    );
  }

  window.CTVPlayoutScheduleEditors = PlayoutScheduleEditors;
})();
