/* ========================================================================
   screens-dashboard.jsx — MVP Command Centre
   ======================================================================== */

const DashboardScreen = () => {
  const getCount = (key) => {
    try { const a = JSON.parse(localStorage.getItem(key) || "[]"); return Array.isArray(a) ? a.length : 0; } catch { return 0; }
  };
  const getScheduledCount = (key) => {
    try {
      const a = JSON.parse(localStorage.getItem(key) || "[]");
      if (!Array.isArray(a)) return 0;
      return a.filter(p => p.date && String(p.date).match(/\d{4}-\d{2}-\d{2}/) && !["posted","published","sent"].includes(String(p.status||"").toLowerCase())).length;
    } catch { return 0; }
  };
  const getNextPost = () => {
    try {
      const ig = JSON.parse(localStorage.getItem("boltkit.scheduledPosts.v1") || "[]");
      const fb = JSON.parse(localStorage.getItem("boltkit.fbPosts.v1") || "[]");
      const all = [...(Array.isArray(ig)?ig:[]), ...(Array.isArray(fb)?fb:[])];
      const now = new Date();
      const upcoming = all
        .filter(p => p.date && String(p.date).match(/\d{4}-\d{2}-\d{2}/) && !["posted","published","sent"].includes(String(p.status||"").toLowerCase()))
        .map(p => ({ ...p, _at: new Date(`${p.date}T${p.time||"09:00"}:00`) }))
        .filter(p => p._at >= now)
        .sort((a,b) => a._at - b._at);
      return upcoming[0] || null;
    } catch { return null; }
  };

  const proj = typeof currentProject === "function" ? currentProject() : {};
  const hasProject = Boolean(proj?.name || proj?.url);

  const [counts, setCounts] = React.useState(() => ({
    igScheduled: getScheduledCount("boltkit.scheduledPosts.v1"),
    fbScheduled: getScheduledCount("boltkit.fbPosts.v1"),
    igDrafts: getCount("boltkit.igPosts.v2"),
    fbDrafts: getCount("boltkit.fbDraftPosts.v1"),
    nextPost: getNextPost(),
  }));
  const [project, setProject] = React.useState(proj);

  React.useEffect(() => {
    const refresh = () => setCounts({
      igScheduled: getScheduledCount("boltkit.scheduledPosts.v1"),
      fbScheduled: getScheduledCount("boltkit.fbPosts.v1"),
      igDrafts: getCount("boltkit.igPosts.v2"),
      fbDrafts: getCount("boltkit.fbDraftPosts.v1"),
      nextPost: getNextPost(),
    });
    window.addEventListener("boltkit:saved", refresh);
    const t = setInterval(refresh, 8000);
    return () => { clearInterval(t); window.removeEventListener("boltkit:saved", refresh); };
  }, []);

  React.useEffect(() => {
    const reload = () => setProject(typeof currentProject === "function" ? currentProject() : {});
    window.addEventListener("boltkit:project-switched", reload);
    return () => window.removeEventListener("boltkit:project-switched", reload);
  }, []);

  const go = (r) => window.BoltKitGo ? window.BoltKitGo(r) : (window.location.hash = r);

  const totalScheduled = counts.igScheduled + counts.fbScheduled;
  const totalDrafts = counts.igDrafts + counts.fbDrafts;

  // Format next post time
  const nextLabel = counts.nextPost ? (() => {
    const d = counts.nextPost._at;
    const diff = Math.round((d - new Date()) / 60000);
    if (diff < 60) return `in ${diff}m`;
    if (diff < 1440) return `in ${Math.floor(diff/60)}h`;
    return d.toLocaleDateString("en-GB", { weekday: "short", day: "numeric", month: "short" }) + " · " + (counts.nextPost.time || "09:00");
  })() : null;

  const StatChip = ({ label, value, tone, onClick }) => (
    <button
      data-bk-bound="true"
      onClick={onClick}
      style={{
        background: tone === "yellow" ? "rgba(239,255,0,0.07)" : tone === "green" ? "rgba(74,222,128,0.07)" : "#26241E",
        border: `1px solid ${tone === "yellow" ? "rgba(239,255,0,0.25)" : tone === "green" ? "rgba(74,222,128,0.25)" : "#3A372F"}`,
        borderRadius: 8, padding: "14px 18px", textAlign: "left", cursor: "pointer",
        display: "flex", flexDirection: "column", gap: 4, flex: 1, minWidth: 100,
      }}
    >
      <div style={{ fontFamily: "'Anton', Impact, sans-serif", fontSize: 32, lineHeight: 1, color: tone === "yellow" ? "#EFFF00" : tone === "green" ? "#4ADE80" : "#FFF" }}>{value}</div>
      <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 9, letterSpacing: "0.14em", fontWeight: 700, color: tone === "yellow" ? "#EFFF00" : tone === "green" ? "#4ADE80" : "#5C5C5C", textTransform: "uppercase" }}>{label}</div>
    </button>
  );

  return (
    <div style={{ height: "100%", display: "flex", background: "#1A1813" }}>
      <SidebarNav active="dashboard" />
      <div style={{ flex: 1, display: "flex", flexDirection: "column", overflow: "hidden" }}>
        <TopBar />
        <div style={{ flex: 1, overflowY: "auto", padding: "32px 40px 56px" }}>

          {/* Header */}
          <div style={{ marginBottom: 32 }}>
            <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 10, letterSpacing: "0.22em", color: "#EFFF00", fontWeight: 800, marginBottom: 8, textTransform: "uppercase", display: "flex", alignItems: "center", gap: 8 }}>
              <span style={{ width: 18, height: 1, background: "#EFFF00" }} />
              {hasProject ? (project.name || "MY PROJECT") : "DASHBOARD"}
            </div>
            <h1 style={{ fontFamily: "'Anton', Impact, sans-serif", fontSize: 48, lineHeight: 1, margin: "0 0 10px", color: "#FFF", textTransform: "uppercase" }}>
              {hasProject ? "WHAT ARE WE\nMAKING?" : "LET'S GET\nSTARTED."}
            </h1>
            {hasProject && (
              <p style={{ color: "#8A8A8A", margin: 0, fontSize: 13, maxWidth: 480, lineHeight: 1.55 }}>
                {project.description || project.url || "Generate images, let AI write the captions, then auto-schedule into the calendar."}
              </p>
            )}
          </div>

          {!hasProject ? (
            /* ── No project yet ─────────────────────────────────────────── */
            <div style={{ background: "#26241E", border: "1px solid #3A372F", borderRadius: 12, padding: "40px 32px", textAlign: "center", maxWidth: 480 }}>
              <div style={{ width: 48, height: 48, background: "rgba(239,255,0,0.08)", border: "1px solid rgba(239,255,0,0.2)", borderRadius: 10, display: "grid", placeItems: "center", margin: "0 auto 20px" }}>
                <Icon name="plus" size={22} stroke={2} color="#EFFF00" />
              </div>
              <div style={{ fontFamily: "'Anton', Impact, sans-serif", fontSize: 24, color: "#FFF", textTransform: "uppercase", marginBottom: 8 }}>Create your first project</div>
              <p style={{ color: "#8A8A8A", fontSize: 13, lineHeight: 1.55, marginBottom: 24 }}>
                Add a project name, description, target audience and tone of voice. Then generate images and auto-schedule them into the calendar.
              </p>
              <button data-bk-bound="true" className="btn btn-primary" style={{ width: "100%", justifyContent: "center" }} onClick={() => go("project-about")}>
                <Icon name="plus" size={13} stroke={2} /> Create project
              </button>
            </div>
          ) : (
            <>
              {/* ── Stats row ────────────────────────────────────────────── */}
              <div style={{ display: "flex", gap: 10, flexWrap: "wrap", marginBottom: 28 }}>
                <StatChip label="IG Scheduled" value={counts.igScheduled} tone={counts.igScheduled ? "yellow" : null} onClick={() => go("ig-calendar")} />
                <StatChip label="FB Scheduled" value={counts.fbScheduled} tone={counts.fbScheduled ? "yellow" : null} onClick={() => go("fb-calendar")} />
                <StatChip label="IG Drafts" value={counts.igDrafts} tone={null} onClick={() => go("ig-generate")} />
                <StatChip label="FB Drafts" value={counts.fbDrafts} tone={null} onClick={() => go("fb-generate")} />
              </div>

              {/* ── Next post ────────────────────────────────────────────── */}
              {nextLabel && (
                <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "12px 16px", background: "rgba(239,255,0,0.05)", border: "1px solid rgba(239,255,0,0.18)", borderRadius: 8, marginBottom: 28 }}>
                  <span style={{ width: 8, height: 8, borderRadius: "50%", background: "#EFFF00", display: "inline-block", animation: "pub-breathe 2s ease-in-out infinite", flex: "none" }} />
                  <span style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 10.5, fontWeight: 700, letterSpacing: "0.12em", color: "#EFFF00" }}>
                    NEXT POST {nextLabel.toUpperCase()} · {counts.nextPost.title || counts.nextPost.caption?.slice(0,40) || "Untitled"}
                  </span>
                  <button data-bk-bound="true" onClick={() => go("ig-calendar")} style={{ marginLeft: "auto", background: "none", border: "1px solid rgba(239,255,0,0.3)", color: "#EFFF00", borderRadius: 4, padding: "3px 10px", fontSize: 10, fontFamily: "'JetBrains Mono', monospace", fontWeight: 700, cursor: "pointer", letterSpacing: "0.1em", flex: "none" }}>VIEW →</button>
                </div>
              )}

              {/* ── Primary actions ──────────────────────────────────────── */}
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, maxWidth: 640, marginBottom: 36 }}>
                <button
                  data-bk-bound="true"
                  onClick={() => go("ig-generate")}
                  style={{ background: "#EFFF00", border: "none", borderRadius: 10, padding: "24px 22px", textAlign: "left", cursor: "pointer", display: "flex", flexDirection: "column", gap: 14 }}
                >
                  <div style={{ width: 36, height: 36, borderRadius: 6, background: "rgba(0,0,0,0.12)", display: "grid", placeItems: "center", flex: "none" }}>
                    <Icon name="sparkle" size={18} stroke={2} color="#1A1813" />
                  </div>
                  <div>
                    <div style={{ fontFamily: "'Anton', Impact, sans-serif", fontSize: 20, color: "#1A1813", textTransform: "uppercase", lineHeight: 1.1, marginBottom: 5 }}>Generate Images</div>
                    <div style={{ fontSize: 12, color: "rgba(26,24,19,0.6)", lineHeight: 1.45 }}>Upload images or generate with AI. AI writes captions, hashtags, and CTA for each.</div>
                  </div>
                  <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 10, fontWeight: 800, letterSpacing: "0.1em", color: "#1A1813", textTransform: "uppercase" }}>Start here →</div>
                </button>

                <button
                  data-bk-bound="true"
                  onClick={() => go("ig-calendar")}
                  style={{ background: "#26241E", border: "1px solid #3A372F", borderRadius: 10, padding: "24px 22px", textAlign: "left", cursor: "pointer", display: "flex", flexDirection: "column", gap: 14 }}
                >
                  <div style={{ width: 36, height: 36, borderRadius: 6, background: "rgba(239,255,0,0.08)", display: "grid", placeItems: "center", flex: "none" }}>
                    <Icon name="calendar" size={18} stroke={2} color="#EFFF00" />
                  </div>
                  <div>
                    <div style={{ fontFamily: "'Anton', Impact, sans-serif", fontSize: 20, color: "#FFF", textTransform: "uppercase", lineHeight: 1.1, marginBottom: 5 }}>
                      {totalScheduled > 0 ? `${totalScheduled} Scheduled` : "View Calendar"}
                    </div>
                    <div style={{ fontSize: 12, color: "#8A8A8A", lineHeight: 1.45 }}>
                      {totalScheduled > 0 ? `${counts.igScheduled} Instagram · ${counts.fbScheduled} Facebook. Auto-posting when connected.` : "Schedule your approved posts and watch them go live automatically."}
                    </div>
                  </div>
                  <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 10, fontWeight: 800, letterSpacing: "0.1em", color: "#EFFF00", textTransform: "uppercase" }}>Open calendar →</div>
                </button>
              </div>

              {/* ── Quick actions ─────────────────────────────────────────── */}
              <div style={{ borderTop: "1px solid #34312A", paddingTop: 24 }}>
                <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 9.5, letterSpacing: "0.18em", color: "#5C5C5C", fontWeight: 800, marginBottom: 12, textTransform: "uppercase" }}>Quick actions</div>
                <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
                  <button className="btn btn-secondary btn-sm" data-bk-bound="true" onClick={() => go("ig-generate")}><Icon name="sparkle" size={11} stroke={2} /> IG Generate</button>
                  <button className="btn btn-secondary btn-sm" data-bk-bound="true" onClick={() => go("fb-generate")}><Icon name="sparkle" size={11} stroke={2} /> FB Generate</button>
                  <button className="btn btn-secondary btn-sm" data-bk-bound="true" onClick={() => go("ig-calendar")}><Icon name="calendar" size={11} stroke={2} /> IG Calendar</button>
                  <button className="btn btn-secondary btn-sm" data-bk-bound="true" onClick={() => go("fb-calendar")}><Icon name="calendar" size={11} stroke={2} /> FB Calendar</button>
                  <button className="btn btn-secondary btn-sm" data-bk-bound="true" onClick={() => go("ig-connect")}><Icon name="insta" size={11} stroke={2} /> Connect IG</button>
                  <button className="btn btn-secondary btn-sm" data-bk-bound="true" onClick={() => go("project-about")}><Icon name="edit" size={11} stroke={2} /> Edit project</button>
                </div>
              </div>

              {/* ── Flow guide ────────────────────────────────────────────── */}
              <div style={{ marginTop: 32, display: "flex", gap: 0, alignItems: "center", flexWrap: "wrap" }}>
                {[
                  { n: "1", l: "Generate", s: "Upload images, AI writes captions", r: "ig-generate" },
                  { n: "2", l: "Approve", s: "Review posts, edit captions", r: "ig-generate" },
                  { n: "3", l: "Schedule", s: "Auto-schedule 5/day or custom", r: "ig-calendar" },
                  { n: "4", l: "Auto-post", s: "Posts go live when IG connected", r: "ig-connect" },
                ].map((step, i, arr) => (
                  <React.Fragment key={step.n}>
                    <button
                      data-bk-bound="true"
                      onClick={() => go(step.r)}
                      style={{ display: "flex", alignItems: "center", gap: 10, padding: "10px 14px", background: "#26241E", border: "1px solid #3A372F", borderRadius: 8, cursor: "pointer", textAlign: "left" }}
                    >
                      <div style={{ width: 22, height: 22, borderRadius: "50%", background: "#EFFF00", color: "#1A1813", display: "grid", placeItems: "center", fontFamily: "'Anton', Impact, sans-serif", fontSize: 11, flex: "none" }}>{step.n}</div>
                      <div>
                        <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 10, fontWeight: 700, color: "#FFF", letterSpacing: "0.06em" }}>{step.l}</div>
                        <div style={{ fontSize: 10.5, color: "#5C5C5C", marginTop: 1 }}>{step.s}</div>
                      </div>
                    </button>
                    {i < arr.length - 1 && <Icon name="chevron_right" size={14} stroke={2} color="#3A372F" style={{ flex: "none", margin: "0 2px" }} />}
                  </React.Fragment>
                ))}
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  );
};

/* ── ProjectDetailScreen — kept for route compat ─────────────────────────── */
const ProjectDetailScreen = () => {
  const p = typeof currentProject === "function" ? currentProject() : {};
  return (
    <div style={{ height: "100%", display: "flex", background: "#1A1813" }}>
      <SidebarNav active="wizard" />
      <div style={{ flex: 1, display: "flex", flexDirection: "column", overflow: "hidden" }}>
        <TopBar />
        <div style={{ flex: 1, overflowY: "auto", padding: "36px 40px 48px" }}>
          <h1 style={{ fontFamily: "'Anton', Impact, sans-serif", fontSize: 38, color: "#FFF", margin: "0 0 12px", textTransform: "uppercase" }}>{p.name || "My Project"}</h1>
          <div style={{ display: "flex", gap: 10 }}>
            <button className="btn btn-secondary" onClick={() => window.BoltKitGo?.("project-about")}><Icon name="edit" size={12} stroke={2} /> Edit project</button>
            <button className="btn btn-primary" onClick={() => window.BoltKitGo?.("ig-generate")}><BoltMini size={12} color="#1A1813" /> Generate posts</button>
          </div>
        </div>
      </div>
    </div>
  );
};

/* Discard unused legacy components */
const _BeginnerHelpPanel = () => null;
const _FirstRunChecklist = () => null;

Object.assign(window, { DashboardScreen, ProjectDetailScreen });
