// Published & Live — see everything that's gone out and what's queued.
// Phase 1 (local): published/scheduled/failed feed with per-channel delivery
// status and timestamps. Phase 2 (needs OAuth): pull real live posts + metrics
// and permalinks back from each platform.

const PUB_STATUS = {
  published: { label: "Live", cls: "ok" },
  scheduled: { label: "Scheduled", cls: "info" },
  needs_approval: { label: "In approval", cls: "warn" },
  changes_requested: { label: "Changes requested", cls: "warn" },
  failed: { label: "Failed", cls: "danger" },
  blocked: { label: "Blocked", cls: "danger" },
  rejected: { label: "Rejected", cls: "danger" },
  draft: { label: "Draft", cls: "muted" }
};

function PublishedPage() {
  const hub = window.useClearCast();
  const data = hub.data || {};
  const posts = data.posts || [];
  const [tab, setTab] = React.useState("live");

  const counts = {
    live: posts.filter((p) => p.status === "published").length,
    scheduled: posts.filter((p) => p.status === "scheduled").length,
    attention: posts.filter((p) => ["failed", "blocked"].includes(p.status)).length,
    all: posts.length
  };
  const filtered = posts.filter((p) => {
    if (tab === "live") return p.status === "published";
    if (tab === "scheduled") return p.status === "scheduled";
    if (tab === "attention") return ["failed", "blocked"].includes(p.status);
    return true;
  }).sort((a, b) => (b.updatedAt || b.createdAt || "").localeCompare(a.updatedAt || a.createdAt || ""));

  const retry = async (post) => { try { await hub.actions.publishPost(post.id, true); } catch (e) { /* toast handled */ } };

  return (
    <div className="page published-page">
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 12, marginBottom: 16 }}>
        {[
          ["Live posts", counts.live, "var(--accent-2)"],
          ["Scheduled", counts.scheduled, "var(--text)"],
          ["Needs attention", counts.attention, counts.attention ? "var(--danger)" : "var(--text)"],
          ["Total", counts.all, "var(--text)"]
        ].map(([label, value, color]) => (
          <div key={label} className="card" style={{ padding: 14 }}>
            <div className="muted" style={{ fontSize: 11.5 }}>{label}</div>
            <div style={{ fontSize: 22, fontWeight: 750, color, marginTop: 2 }}>{value}</div>
          </div>
        ))}
      </div>

      <div className="tabs" style={{ marginBottom: 14 }}>
        {[["live", "Live"], ["scheduled", "Scheduled"], ["attention", "Needs attention"], ["all", "All"]].map(([id, label]) => (
          <button key={id} className={`tab ${tab === id ? "active" : ""}`} onClick={() => setTab(id)}>{label} {counts[id] ? counts[id] : ""}</button>
        ))}
      </div>

      <div style={{ display: "grid", gap: 10 }}>
        {filtered.map((post) => {
          const status = PUB_STATUS[post.status] || PUB_STATUS.draft;
          const lastAttempt = (post.publishAttempts || [])[0];
          return (
            <div key={post.id} className="card published-row" style={{ padding: 14 }}>
              <div className="published-platforms">
                {(post.platforms || []).map((id) => <PlatformIcon key={id} id={id} size={20} />)}
              </div>
              <div className="published-body">
                <div className="published-caption">{post.caption || "Untitled post"}</div>
                <div className="published-meta muted">
                  <span>{post.date} · {post.time}</span>
                  {post.status === "published" && lastAttempt && <span>· delivered {new Date(lastAttempt.finishedAt).toLocaleDateString()}</span>}
                  {post.lastPublishError && post.status !== "published" && <span style={{ color: "var(--danger)" }}>· {post.lastPublishError}</span>}
                </div>
              </div>
              <div className="published-right">
                <span className={`pill ${status.cls}`} style={{ padding: "3px 9px", fontSize: 11 }}>{status.label}</span>
                {post.status === "published" && (
                  <span className="muted" style={{ fontSize: 10.5 }}>Permalinks after OAuth</span>
                )}
                {["failed", "blocked"].includes(post.status) && (
                  <button className="btn btn-sm" onClick={() => retry(post)}>Retry</button>
                )}
                {post.status === "scheduled" && (
                  <button className="btn btn-sm" onClick={() => { sessionStorage.setItem("clearcast-edit-post-id", post.id); window.location.hash = "create"; }}>Edit</button>
                )}
              </div>
            </div>
          );
        })}
        {!filtered.length && (
          <div className="card" style={{ padding: 32, textAlign: "center" }}>
            <div style={{ fontWeight: 650, marginBottom: 4 }}>Nothing here yet</div>
            <div className="muted" style={{ fontSize: 12.5, marginBottom: 14 }}>{tab === "live" ? "Published posts will appear here once you publish." : tab === "scheduled" ? "Scheduled posts will show up here." : "No posts need attention — nice."}</div>
            <button className="btn btn-primary" onClick={() => { window.location.hash = "create"; }}><Icon.Edit width="14" height="14" /> Create a post</button>
          </div>
        )}
      </div>

      <div className="muted" style={{ fontSize: 11.5, marginTop: 14, textAlign: "center" }}>
        Live permalinks and on-platform metrics sync automatically once channels are connected via OAuth.
      </div>
    </div>
  );
}

window.PublishedPage = PublishedPage;
