/* QueueView (M7) — scheduled posts by time + due-date reminders.
   Auto-publish jobs are visible here with their live controls. */
(function () {
  const D = window.CROPR_DATA;
  const S = window.CroprStore;

  const dayKey = (iso) => { const d = new Date(iso); return d.toDateString(); };
  const dayLabel = (iso) => {
    const d = new Date(iso); const t = new Date(); const tm = new Date(Date.now() + 864e5);
    if (d.toDateString() === t.toDateString()) return "Today";
    if (d.toDateString() === tm.toDateString()) return "Tomorrow";
    return d.toLocaleDateString("en-GB", { weekday: "long", day: "2-digit", month: "short" });
  };
  const timeLabel = (iso) => new Date(iso).toLocaleTimeString("en-GB", { hour: "2-digit", minute: "2-digit" });

  function Stat({ label, value, color }) {
    return (
      <div style={{ background: "var(--surface)", border: "1px solid var(--border)", borderRadius: 14, padding: "14px 16px", boxShadow: "var(--shadow-sm)", minWidth: 130 }}>
        <div style={{ fontSize: 11, color: "var(--fg3)", fontWeight: 600, textTransform: "uppercase", letterSpacing: ".04em" }}>{label}</div>
        <div style={{ fontSize: 24, fontWeight: 700, color: color || "var(--fg1)", fontVariantNumeric: "tabular-nums" }}>{value}</div>
      </div>
    );
  }

  function ChannelDots({ channels }) {
    return <div style={{ display: "flex", marginLeft: 2 }}>{(channels || []).map((ch, i) => { const m = D.CHANNELS[ch]; if (!m) return null; return <span key={ch} style={{ marginLeft: i ? -6 : 0, border: "2px solid var(--surface)", borderRadius: 999 }}><Avatar color={m.avatar} initials={m.initials} src={m.icon} size={22} /></span>; })}</div>;
  }

  function QueueRow({ post, onOpen, onToast }) {
    return (
      <div style={{ display: "flex", gap: 16, alignItems: "flex-start", padding: "16px 18px", border: "1px solid var(--border)", borderRadius: 14, background: "var(--surface)", boxShadow: "var(--shadow-sm)" }}>
        <div style={{ textAlign: "center", flex: "none", width: 58 }}>
          <div style={{ fontSize: 17, fontWeight: 700, fontVariantNumeric: "tabular-nums" }}>{timeLabel(post.scheduleAt)}</div>
          <div style={{ fontSize: 10.5, color: "var(--fg3)" }}>Vienna</div>
        </div>
        <div style={{ width: 1, alignSelf: "stretch", background: "var(--border)" }} />
        <div style={{ minWidth: 0, flex: 1 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 6 }}>
            <HoverImage src={postThumb(post)} size={40} radius={9} label={post.title} />
            <span onClick={() => onOpen(post.id)} style={{ fontSize: 14.5, fontWeight: 700, cursor: "pointer" }}>{post.title}</span>
            <ChannelDots channels={post.channels} />
          </div>
          <div style={{ display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap" }}>
            <Badge color="var(--fg3)">{D.label(D.SERIES, post.series)}</Badge>
            {post.campaign && <Badge color="var(--fg3)">{post.campaign}</Badge>}
          </div>
          <div style={{ marginTop: 12 }}><ScheduleControls post={post} onToast={onToast} /></div>
        </div>
        <Button size="sm" variant="ghost" icon="pen-line" onClick={() => onOpen(post.id)}>Open</Button>
      </div>
    );
  }

  function QueueView({ posts, onOpen, onToast }) {
    const queued = posts.filter((p) => ["queued", "paused", "publishing"].includes(p.scheduleState) && p.scheduleAt)
      .sort((a, b) => new Date(a.scheduleAt) - new Date(b.scheduleAt));
    const publishedRecently = posts.filter((p) => p.scheduleState === "published");
    const reminders = posts.filter((p) => p.dueDate && !["published", "amplify", "tracked"].includes(p.status))
      .sort((a, b) => new Date(a.dueDate) - new Date(b.dueDate));

    // group queued by day
    const groups = [];
    queued.forEach((p) => { const k = dayKey(p.scheduleAt); let g = groups.find((x) => x.k === k); if (!g) { g = { k, iso: p.scheduleAt, items: [] }; groups.push(g); } g.items.push(p); });

    return (
      <div style={{ maxWidth: "var(--page-w)", margin: "0 auto" }}>
        <div style={{ display: "flex", gap: 12, marginBottom: 24, flexWrap: "wrap" }}>
          <Stat label="Queued" value={queued.filter((p) => p.scheduleState === "queued").length} color="#0EA5B7" />
          <Stat label="Paused" value={queued.filter((p) => p.scheduleState === "paused").length} color="#B25E09" />
          <Stat label="Published" value={publishedRecently.length} color="#0E8A50" />
        </div>

        {groups.length === 0 && (
          <Card pad={40} style={{ textAlign: "center" }}>
            <Icon name="calendar-clock" size={30} color="var(--fg4)" />
            <div style={{ fontSize: 15, fontWeight: 700, marginTop: 10 }}>Nothing queued</div>
            <div style={{ fontSize: 13, color: "var(--fg3)", marginTop: 4 }}>Approve a post and schedule it to arm auto-publish.</div>
          </Card>
        )}

        {groups.map((g) => (
          <div key={g.k} style={{ marginBottom: 22 }}>
            <div style={{ fontSize: 12, fontWeight: 700, color: "var(--fg3)", textTransform: "uppercase", letterSpacing: ".05em", margin: "0 0 10px 2px" }}>{dayLabel(g.iso)}</div>
            <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
              {g.items.map((p) => <QueueRow key={p.id} post={p} onOpen={onOpen} onToast={onToast} />)}
            </div>
          </div>
        ))}

        {reminders.length > 0 && (
          <div style={{ marginTop: 10 }}>
            <SectionTitle icon="bell">Due-date reminders</SectionTitle>
            <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
              {reminders.map((p) => {
                const overdue = new Date(p.dueDate) < new Date();
                return (
                  <div key={p.id} onClick={() => onOpen(p.id)} style={{ display: "flex", alignItems: "center", gap: 12, padding: "11px 14px", borderRadius: 12, border: "1px solid var(--border)", background: "var(--surface)", cursor: "pointer" }}>
                    <Icon name={overdue ? "alert-triangle" : "clock"} size={17} color={overdue ? "#F04438" : "#F79009"} />
                    <span style={{ fontSize: 13.5, fontWeight: 600, flex: 1 }}>{p.title}</span>
                    <StatusBadge status={p.status} />
                    <Badge color={overdue ? "#C6362B" : "#B25E09"} bg={overdue ? "var(--danger-bg)" : "var(--warning-bg)"}>{overdue ? "Overdue" : "Due"} {new Date(p.dueDate).toLocaleDateString("en-GB", { day: "2-digit", month: "short" })}</Badge>
                  </div>
                );
              })}
            </div>
          </div>
        )}
      </div>
    );
  }
  window.QueueView = QueueView;
})();
