/* ScheduleControls — the §6A publish state machine surface. Reused in the
   Composer rail and the Queue view. All publishing here is SIMULATED and
   clearly labelled; the controls (pause/resume/cancel/reschedule) and gate
   logic are the real thing, ready to wire to X + LinkedIn APIs. */
(function () {
  const D = window.CROPR_DATA;
  const S = window.CroprStore;

  const toLocal = (iso) => {
    if (!iso) return "";
    const d = new Date(iso); const p = (n) => String(n).padStart(2, "0");
    return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}T${p(d.getHours())}:${p(d.getMinutes())}`;
  };
  const fromLocal = (v) => v ? new Date(v).toISOString() : null;
  const fmt = (iso) => { try { return new Date(iso).toLocaleString("en-GB", { weekday: "short", day: "2-digit", month: "short", hour: "2-digit", minute: "2-digit" }); } catch (e) { return iso; } };

  const stateMeta = {
    queued: { color: "#0EA5B7", label: "Queued", icon: "clock" },
    paused: { color: "#B25E09", label: "Paused", icon: "pause" },
    publishing: { color: "#38BDF8", label: "Publishing…", icon: "loader" },
    published: { color: "#0E8A50", label: "Published", icon: "check-circle" },
    cancelled: { color: "#6E6E7A", label: "Cancelled", icon: "x-circle" },
    failed: { color: "#C6362B", label: "Failed", icon: "alert-octagon" },
  };

  function ScheduleControls({ post, onToast }) {
    const [when, setWhen] = React.useState(toLocal(post.scheduleAt) || defaultTime());
    const st = post.scheduleState;
    const gate = S.canTransition(post, "scheduled");
    const canArm = gate.ok || (post.roles.approver && post.status === "approved"); // needs a time too

    function defaultTime() { const d = new Date(Date.now() + 60 * 60 * 1000); const p = (n) => String(n).padStart(2, "0"); return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}T${p(d.getHours())}:${p(d.getMinutes())}`; }
    const doSchedule = () => { const r = S.schedule(post.id, fromLocal(when)); onToast(r.ok ? "Queued for auto-publish — pausable any time" : r.reason, r.ok ? "ok" : "error"); };
    const doReschedule = () => { S.reschedule(post.id, fromLocal(when)); onToast("Rescheduled"); };

    const picker = (
      <input type="datetime-local" value={when} onChange={(e) => setWhen(e.target.value)}
        style={{ fontFamily: "inherit", fontSize: 13, padding: "8px 10px", borderRadius: 10, border: "1px solid var(--border-strong)", color: "var(--fg1)", background: "var(--surface)", width: "100%", boxSizing: "border-box" }} />
    );

    // Not yet queued
    if (!st || st === "cancelled") {
      const armGate = S.canTransition({ ...post, scheduleAt: fromLocal(when) }, "scheduled");
      return (
        <div>
          <div style={{ fontSize: 12, color: "var(--fg3)", marginBottom: 8, display: "flex", alignItems: "center", gap: 6 }}><Icon name="calendar-clock" size={15} color="var(--fg3)" />Schedule auto-publish · Europe/Vienna</div>
          {picker}
          <div style={{ marginTop: 10 }}>
            <Button variant="primary" icon="send" full disabled={!armGate.ok} onClick={doSchedule}>Schedule & arm auto-publish</Button>
          </div>
          {!armGate.ok && <div style={{ fontSize: 11.5, color: "#B25E09", marginTop: 8, display: "flex", gap: 6 }}><Icon name="lock" size={14} color="#B25E09" />{armGate.reason}</div>}
          {armGate.ok && <div style={{ fontSize: 11, color: "var(--fg3)", marginTop: 8 }}>Fires automatically at the set time. Always pausable / stoppable before it does.</div>}
        </div>
      );
    }

    const m = stateMeta[st] || stateMeta.queued;
    return (
      <div>
        <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 10 }}>
          <Badge color={m.color} bg={m.color + "18"} dot>{m.label}</Badge>
          <span style={{ fontSize: 12.5, color: "var(--fg2)", fontWeight: 600 }}>{fmt(post.scheduleAt)}</span>
        </div>

        {st === "published" && (
          <div style={{ display: "flex", flexDirection: "column", gap: 6, marginBottom: 8 }}>
            {(post.publishResults || []).map((r, i) => {
              const cm = D.CHANNELS[r.channel];
              return (
                <div key={i} style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 12, padding: "6px 9px", background: "var(--bg-subtle)", borderRadius: 9 }}>
                  <Avatar color={cm.avatar} initials={cm.initials} size={18} />
                  <span style={{ fontWeight: 600 }}>{cm.name}</span>
                  {r.error ? <Badge color="#C6362B" bg="var(--danger-bg)">failed</Badge>
                    : <a href={r.url} target="_blank" rel="noreferrer" style={{ fontSize: 12, marginLeft: "auto" }}>view ↗</a>}
                </div>
              );
            })}
            <div style={{ fontSize: 10.5, color: "var(--fg4)", display: "flex", gap: 5, alignItems: "center" }}><Icon name="flask-conical" size={12} color="var(--fg4)" />Simulated — no live post sent. Wire X + LinkedIn APIs (M8) to publish for real.</div>
          </div>
        )}

        {(st === "queued" || st === "paused") && (
          <div>
            <div style={{ marginBottom: 8 }}>{picker}</div>
            <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
              {st === "queued" && <Button size="sm" variant="secondary" icon="pause" onClick={() => { S.pause(post.id); onToast("Paused — job held"); }}>Pause</Button>}
              {st === "paused" && <Button size="sm" variant="primary" icon="play" onClick={() => { S.resume(post.id); onToast("Resumed — re-queued"); }}>Resume</Button>}
              <Button size="sm" variant="secondary" icon="calendar" onClick={doReschedule}>Reschedule</Button>
              <Button size="sm" variant="danger" icon="x" onClick={() => { S.cancel(post.id); onToast("Cancelled — back to Approved"); }}>Cancel</Button>
              <Button size="sm" variant="brand" icon="zap" onClick={() => { const r = S.publishNow(post.id); onToast(r.ok ? "Published now (simulated)" : r.reason, r.ok ? "ok" : "error"); }}>Publish now</Button>
            </div>
          </div>
        )}
      </div>
    );
  }
  window.ScheduleControls = ScheduleControls;
})();
