/* ========================================================================
   primitives.jsx — small reusable bits shared across screens
   ====================================================================== */

const AppIco = ({ size = 40, bg = "#EFFF00", color = "#1A1813", letter = "R" }) => (
  <div className="app-ico" style={{ width: size, height: size, background: bg, color, fontSize: size * 0.42 }}>
    {letter}
  </div>
);

const Pill = ({ tone = "dark", children, className = "" }) => (
  <span className={"pill pill-" + tone + " " + className}>
    <span className="dot" />
    {children}
  </span>
);

const Meter = ({ v = 50, tone = "yellow" }) => (
  <div className="meter">
    <span style={{ width: v + "%", background: tone === "yellow" ? "#EFFF00" : tone === "green" ? "#4ADE80" : tone === "amber" ? "#FFB23F" : "#4DA8FF" }} />
  </div>
);

const SyncChip = ({ state = "sync" }) => {
  const map = {
    sync:  { l: "Synced · Supabase" },
    save:  { l: "Saving…" },
    local: { l: "Local fallback" },
    fail:  { l: "Save failed" },
  };
  return (
    <div className={"sync-chip " + state}>
      <span className="d" />
      <span>{map[state].l}</span>
    </div>
  );
};

const BoltMini = ({ size = 14, color = "currentColor" }) => (
  <svg viewBox="0 0 32 32" width={size} height={size} aria-hidden="true">
    <path d="M20.2 2 L7 17.4 L13.4 17.4 L11.6 30 L25.6 13.2 L18.9 13.2 L20.2 2 Z" fill={color} />
  </svg>
);

const RingScore = ({ score = 87, size = 90, label = "READINESS" }) => {
  const r = (size - 12) / 2;
  const c = 2 * Math.PI * r;
  const off = c - (score / 100) * c;
  return (
    <div className="ring-wrap" style={{ width: size, height: size }}>
      <svg width={size} height={size}>
        <circle cx={size/2} cy={size/2} r={r} fill="none" stroke="#3A372F" strokeWidth="4" />
        <circle cx={size/2} cy={size/2} r={r} fill="none" stroke="#EFFF00"
          strokeWidth="4" strokeLinecap="square" strokeDasharray={c} strokeDashoffset={off}
          transform={`rotate(-90 ${size/2} ${size/2})`}
          style={{ filter: "drop-shadow(0 0 6px rgba(239,255,0,0.5))" }}
        />
      </svg>
      <div className="ring-num">
        <div className="n">{score}</div>
        <div className="l">{label}</div>
      </div>
    </div>
  );
};

/* Mini phone mockup used inside dashboard screens */
const MiniPhone = ({ children, w = 130 }) => (
  <div style={{
    width: w, aspectRatio: "9/19",
    background: "#201E18", border: "1px solid #3A372F",
    borderRadius: 14, overflow: "hidden",
    position: "relative",
  }}>{children}</div>
);

/* Diagonal yellow ribbon */
const Ribbon = ({ children, top = 12, right = -8, rotate = -8 }) => (
  <div style={{
    position: "absolute", top, right,
    transform: `rotate(${rotate}deg)`,
    background: "#EFFF00", color: "#1A1813",
    padding: "4px 14px",
    fontFamily: "'JetBrains Mono', monospace",
    fontSize: 10, fontWeight: 800,
    letterSpacing: "0.18em",
    boxShadow: "0 4px 12px rgba(239,255,0,0.3)",
    zIndex: 5,
  }}>{children}</div>
);

/* Sidebar nav — Projects-based navigation */
const SidebarNav = ({ active = "dashboard", compact = false }) => {
  const [autoCompact, setAutoCompact] = React.useState(() => window.innerWidth <= 768);
  React.useEffect(() => {
    const onResize = () => setAutoCompact(window.innerWidth <= 768);
    window.addEventListener("resize", onResize);
    return () => window.removeEventListener("resize", onResize);
  }, []);
  const navCompact = compact || autoCompact;

  const readProjects = () => {
    try {
      const list = JSON.parse(localStorage.getItem("boltkit.projectsList.v1") || "null");
      if (Array.isArray(list) && list.length) return list;
      const existing = JSON.parse(localStorage.getItem("boltkit.currentProject.v1") || "null");
      if (existing?.id || existing?.name) {
        const m = [{ ...existing, id: existing.id || `project-migrate-${Date.now()}` }];
        localStorage.setItem("boltkit.projectsList.v1", JSON.stringify(m));
        return m;
      }
      return [];
    } catch { return []; }
  };

  // Defensive: activeProjectId has occasionally been written JSON-encoded
  // (e.g. "\"project-123\""), which produces divergent quoted storage-key
  // suffixes. Strip any accidental wrapping quotes so the id is always raw.
  const normId = (v) => {
    let s = v == null ? "" : String(v);
    let guard = 0;
    while (s.length > 1 && s[0] === '"' && s[s.length - 1] === '"' && guard++ < 3) {
      try { s = JSON.parse(s); } catch { break; }
    }
    return s;
  };

  const readActiveId = (projs) => {
    try {
      const saved = normId(localStorage.getItem("boltkit.activeProjectId.v1"));
      if (saved) return saved;
      return projs?.length ? projs[0].id : null;
    } catch { return null; }
  };

  const [projects, setProjects] = React.useState(readProjects);
  const [activeId, setActiveId]   = React.useState(() => readActiveId(readProjects()));
  const [expandId, setExpandId]   = React.useState(() => readActiveId(readProjects()));

  // Keep in sync when other tabs or same-tab saves change the list
  React.useEffect(() => {
    const poll = () => {
      const list = readProjects();
      setProjects(list);
      const aid = localStorage.getItem("boltkit.activeProjectId.v1") || (list[0]?.id ?? null);
      setActiveId(aid);
      // Do NOT reset expandId here — let the user's explicit collapse/expand stand
    };
    const timer = setInterval(poll, 1200);
    return () => clearInterval(timer);
  }, []);

  const go = (id) => {
    if (window.BoltKitGo) window.BoltKitGo(id);
    else window.location.hash = id;
  };

  const createProject = () => {
    // ── Save outgoing project's drafts to its project-scoped key ──────────────
    // Without this the new project inherits the previous project's draft grid
    // (the generic boltkit.igPosts.v2 bucket), which then bleeds across projects.
    const outgoingId = normId(localStorage.getItem("boltkit.activeProjectId.v1"));
    if (outgoingId) {
      const igDrafts = localStorage.getItem("boltkit.igPosts.v2");
      if (igDrafts && igDrafts !== "[]") localStorage.setItem(`boltkit.igPosts.v2.${outgoingId}`, igDrafts);
      const fbDrafts = localStorage.getItem("boltkit.fbDraftPosts.v1");
      if (fbDrafts && fbDrafts !== "[]") localStorage.setItem(`boltkit.fbDraftPosts.v1.${outgoingId}`, fbDrafts);
    }
    // ── New project starts with empty draft grids ─────────────────────────────
    localStorage.setItem("boltkit.igPosts.v2", "[]");
    localStorage.setItem("boltkit.fbDraftPosts.v1", "[]");
    localStorage.removeItem("boltkit.scheduledPosts.v1");
    localStorage.removeItem("boltkit.fbPosts.v1");

    const id = `project-${Date.now()}`;
    const newProj = { id, name: "New Project", url: "", description: "", target_audience: "", tone_of_voice: "", feature_notes: "", brandRules: [], createdAt: new Date().toISOString() };
    const newList = [...projects, newProj];
    localStorage.setItem("boltkit.projectsList.v1", JSON.stringify(newList));
    localStorage.setItem("boltkit.activeProjectId.v1", id);
    localStorage.setItem("boltkit.currentProject.v1", JSON.stringify(newProj));
    setProjects(newList);
    setActiveId(id);
    setExpandId(id);
    window.dispatchEvent(new CustomEvent("boltkit:project-switched", { detail: newProj }));
    go("project-about");
  };

  const switchProject = (proj) => {
    // ── Save outgoing project's draft posts to a project-scoped key ──────────
    const outgoingId = normId(localStorage.getItem("boltkit.activeProjectId.v1"));
    if (outgoingId && outgoingId !== proj.id) {
      const igDrafts = localStorage.getItem("boltkit.igPosts.v2");
      if (igDrafts && igDrafts !== "[]") localStorage.setItem(`boltkit.igPosts.v2.${outgoingId}`, igDrafts);
      const fbDrafts = localStorage.getItem("boltkit.fbDraftPosts.v1");
      if (fbDrafts && fbDrafts !== "[]") localStorage.setItem(`boltkit.fbDraftPosts.v1.${outgoingId}`, fbDrafts);
    }
    // ── Restore incoming project's drafts (empty if none saved yet) ───────────
    const igSaved = localStorage.getItem(`boltkit.igPosts.v2.${proj.id}`);
    localStorage.setItem("boltkit.igPosts.v2", igSaved || "[]");
    const fbSaved = localStorage.getItem(`boltkit.fbDraftPosts.v1.${proj.id}`);
    localStorage.setItem("boltkit.fbDraftPosts.v1", fbSaved || "[]");
    // ── Clear scheduled-post cache so Live Feed reloads from Supabase ─────────
    localStorage.removeItem("boltkit.scheduledPosts.v1");
    localStorage.removeItem("boltkit.fbPosts.v1");
    // ── Switch ────────────────────────────────────────────────────────────────
    localStorage.setItem("boltkit.activeProjectId.v1", proj.id);
    localStorage.setItem("boltkit.currentProject.v1", JSON.stringify(proj));
    setActiveId(proj.id);
    setExpandId(proj.id);
    window.dispatchEvent(new CustomEvent("boltkit:project-switched", { detail: proj }));
    go("project-about");
  };

  // Which sub-item is active
  const isAboutActive  = ["project-about", "wizard", "wizard-assets", "wizard-analysis", "importer", "assets", "brand"].includes(active);
  const isGenActive     = ["ig-generate", "generate"].includes(active);
  const isCalActive     = ["ig-calendar", "calendar"].includes(active);
  const isConnActive    = ["ig-connect", "connect-socials", "instagram", "instagram-scheduler"].includes(active);
  const isPublishActive = ["publish", "live-feed"].includes(active);

  const igSubItems = [
    { id: "ig-generate", l: "Generate Posts", ico: "sparkle",  isActive: isGenActive     },
    { id: "ig-calendar", l: "Calendar",       ico: "calendar", isActive: isCalActive     },
    { id: "ig-connect",  l: "Connect",        ico: "insta",    isActive: isConnActive    },
    { id: "publish",     l: "Live Feed",      ico: "zap",      isActive: isPublishActive },
  ];

  const isFbGenActive  = active === "fb-generate";
  const isFbCalActive  = active === "fb-calendar";
  const isFbConnActive = active === "fb-connect";
  const isFbLiveActive = active === "fb-live";
  const fbSubItems = [
    { id: "fb-generate", l: "Generate Posts", ico: "sparkle",  isActive: isFbGenActive  },
    { id: "fb-calendar", l: "Calendar",       ico: "calendar", isActive: isFbCalActive  },
    { id: "fb-connect",  l: "Connect Page",   ico: "link",     isActive: isFbConnActive },
    { id: "fb-live",     l: "Live Feed",      ico: "zap",      isActive: isFbLiveActive },
  ];

  const sess = (() => { try { return JSON.parse(localStorage.getItem("boltkit.session.v1") || "null"); } catch { return null; } })();
  const userName = sess?.user?.name || "Sam";
  const initials = userName.split(" ").map(n => n[0]).join("").slice(0, 2).toUpperCase();

  const subBtn = (key, label, icon, isAct, onClick) => (
    <button key={key} data-bk-bound="true" onClick={onClick} style={{ width: "100%", display: "flex", alignItems: "center", gap: 8, padding: "7px 10px 7px 12px", borderRadius: 4, fontSize: 11.5, fontWeight: isAct ? 700 : 500, color: isAct ? "#1A1813" : "#A8A8A5", background: isAct ? "#EFFF00" : "transparent", cursor: "pointer", marginBottom: 2 }}>
      <Icon name={icon} size={12} stroke={2} />
      <span>{label}</span>
    </button>
  );

  return (
    <div style={{ width: navCompact ? 60 : 240, background: "#1A1813", borderRight: "1px solid #34312A", display: "flex", flexDirection: "column", height: "100%", flex: "none" }}>

      {/* Logo */}
      <button onClick={() => go("dashboard")} style={{ width: "100%", textAlign: "left", padding: navCompact ? "14px 0" : "14px 14px 12px", borderBottom: "1px solid #34312A", position: "relative", display: "flex", alignItems: "center", gap: 10, background: "transparent", color: "inherit", cursor: "pointer", justifyContent: navCompact ? "center" : "flex-start" }} title="Dashboard">
        <div style={{ width: 30, height: 30, borderRadius: 6, background: "#EFFF00", display: "grid", placeItems: "center", flex: "none" }}>
          <BoltMini size={18} color="#1A1813" />
        </div>
        {!navCompact && (
          <div style={{ lineHeight: 1 }}>
            <div style={{ fontFamily: "'Anton', Impact, sans-serif", fontSize: 18, letterSpacing: "0.02em", color: "#FFF" }}>BOLTKIT</div>
            <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 8.5, letterSpacing: "0.18em", color: "#5C5C5C", fontWeight: 700, marginTop: 3 }}>CONTENT OS</div>
          </div>
        )}
        <div style={{ position: "absolute", left: 0, right: 0, bottom: 0, height: 2, background: "repeating-linear-gradient(135deg, #EFFF00 0 8px, #1A1813 8px 16px)" }} />
      </button>

      {/* Dashboard top-level link */}
      <button data-bk-bound="true" onClick={() => go("dashboard")} style={{ width: "100%", display: "flex", alignItems: "center", gap: 8, padding: navCompact ? "9px 0" : "8px 12px", justifyContent: navCompact ? "center" : "flex-start", fontSize: 12, fontWeight: active === "dashboard" ? 700 : 500, color: active === "dashboard" ? "#EFFF00" : "#8A8A8A", background: active === "dashboard" ? "rgba(239,255,0,0.07)" : "transparent", borderLeft: active === "dashboard" ? "2px solid #EFFF00" : "2px solid transparent", cursor: "pointer", marginTop: 4 }} title="Dashboard">
        <Icon name="grid" size={14} stroke={2} color={active === "dashboard" ? "#EFFF00" : "#8A8A8A"} />
        {!navCompact && <span>Dashboard</span>}
      </button>

      {/* Projects */}
      <div style={{ flex: 1, overflowY: "auto", padding: "8px 0" }}>
        {!navCompact && (
          <div style={{ padding: "6px 14px 4px", fontFamily: "'JetBrains Mono', monospace", fontSize: 9, fontWeight: 800, letterSpacing: "0.18em", color: "#5C5C5C", textTransform: "uppercase" }}>PROJECTS</div>
        )}

        {projects.length === 0 && !navCompact && (
          <div style={{ padding: "8px 14px 4px", fontSize: 11, color: "#5C5C5C", lineHeight: 1.4 }}>No projects yet.</div>
        )}

        {projects.map(proj => {
          const isActive   = proj.id === activeId;
          const isExpanded = proj.id === expandId;
          const letter     = (proj.name || "P")[0].toUpperCase();

          return (
            <div key={proj.id}>
              <button
                data-bk-bound="true"
                onClick={() => {
                  if (!isActive) { switchProject(proj); }
                  else { setExpandId(isExpanded ? null : proj.id); }
                }}
                style={{ width: "100%", display: "flex", alignItems: "center", gap: 8, padding: navCompact ? "9px 0" : "8px 12px", justifyContent: navCompact ? "center" : "flex-start", fontSize: 12, fontWeight: 700, color: isActive ? "#FFF" : "#B0B0AD", background: isActive ? "rgba(239,255,0,0.07)" : "transparent", borderLeft: isActive ? "2px solid #EFFF00" : "2px solid transparent", cursor: "pointer" }}
                title={proj.name || "Unnamed Project"}
              >
                <div style={{ width: 22, height: 22, borderRadius: 4, flex: "none", background: isActive ? "#EFFF00" : "#2C2A23", color: isActive ? "#1A1813" : "#8A8A8A", display: "grid", placeItems: "center", fontFamily: "'Anton', Impact, sans-serif", fontSize: 11 }}>{letter}</div>
                {!navCompact && (
                  <>
                    <span style={{ flex: 1, textAlign: "left", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{proj.name || "Unnamed Project"}</span>
                    <Icon name={isExpanded ? "chevron_down" : "chevron_right"} size={12} stroke={2} color="#5C5C5C" />
                  </>
                )}
              </button>

              {/* Sub-nav */}
              {isExpanded && !navCompact && (
                <div style={{ paddingLeft: 18, paddingRight: 8, paddingBottom: 6 }}>
                  {subBtn("about", "About project", "info", isAboutActive, () => go("project-about"))}
                  <div style={{ padding: "6px 0 4px 12px", fontFamily: "'JetBrains Mono', monospace", fontSize: 8.5, fontWeight: 800, letterSpacing: "0.16em", color: "#5C5C5C", textTransform: "uppercase" }}>INSTAGRAM</div>
                  {igSubItems.map(it => subBtn(it.id, it.l, it.ico, it.isActive, () => go(it.id)))}
                  <div style={{ padding: "6px 0 4px 12px", fontFamily: "'JetBrains Mono', monospace", fontSize: 8.5, fontWeight: 800, letterSpacing: "0.16em", color: "#5C5C5C", textTransform: "uppercase" }}>FACEBOOK</div>
                  {fbSubItems.map(it => subBtn(it.id, it.l, it.ico, it.isActive, () => go(it.id)))}
                </div>
              )}
            </div>
          );
        })}

        {/* New project */}
        <button data-bk-bound="true" onClick={createProject} style={{ width: "100%", display: "flex", alignItems: "center", gap: 8, padding: navCompact ? "9px 0" : "8px 12px", justifyContent: navCompact ? "center" : "flex-start", fontSize: 11.5, fontWeight: 500, color: "#5C5C5C", background: "transparent", cursor: "pointer", marginTop: 4 }} title="New Project">
          <div style={{ width: 22, height: 22, borderRadius: 4, background: "#26241E", border: "1px dashed #3A372F", display: "grid", placeItems: "center", flex: "none" }}>
            <Icon name="plus" size={12} stroke={2} color="#5C5C5C" />
          </div>
          {!navCompact && <span>New project</span>}
        </button>

        <div style={{ height: 1, background: "#34312A", margin: "8px 8px" }} />

        {/* Tester Guide */}
        <button onClick={() => go("test-guide")} style={{ width: "100%", display: "flex", alignItems: "center", gap: 8, padding: navCompact ? "9px 0" : "8px 12px", justifyContent: navCompact ? "center" : "flex-start", fontSize: 11.5, fontWeight: 500, color: active === "test-guide" ? "#EFFF00" : "#5C5C5C", background: "transparent", borderRadius: 4, cursor: "pointer" }} title="Tester Guide">
          <Icon name="clipboard" size={14} stroke={2} />
          {!navCompact && <span>Tester Guide</span>}
        </button>

        {/* Settings */}
        <button onClick={() => go("settings")} style={{ width: "100%", display: "flex", alignItems: "center", gap: 8, padding: navCompact ? "9px 0" : "8px 12px", justifyContent: navCompact ? "center" : "flex-start", fontSize: 11.5, fontWeight: 500, color: active === "settings" ? "#1A1813" : "#8A8A8A", background: active === "settings" ? "#EFFF00" : "transparent", borderRadius: 4, cursor: "pointer" }} title="Settings">
          <Icon name="settings" size={14} stroke={2} />
          {!navCompact && <span>Settings</span>}
        </button>
      </div>

      {/* User card */}
      {!navCompact && (
        <div style={{ padding: 10, borderTop: "1px solid #34312A" }}>
          <button onClick={() => go("settings")} style={{ width: "100%", background: "#26241E", border: "1px solid #34312A", borderRadius: 5, padding: 9, display: "flex", alignItems: "center", gap: 9, position: "relative", overflow: "hidden", textAlign: "left", cursor: "pointer" }}>
            <div style={{ position: "absolute", left: 0, top: 0, bottom: 0, width: 3, background: "#EFFF00" }} />
            <div style={{ width: 26, height: 26, background: "#EFFF00", color: "#1A1813", display: "grid", placeItems: "center", borderRadius: 4, fontFamily: "'Anton', Impact, sans-serif", fontSize: 12, flex: "none" }}>{initials}</div>
            <div style={{ minWidth: 0 }}>
              <div style={{ color: "#FFF", fontSize: 11, fontWeight: 700, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{userName}</div>
              <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 8.5, letterSpacing: "0.12em", color: "#5C5C5C", textTransform: "uppercase", fontWeight: 700, marginTop: 1 }}>{projects.length} Project{projects.length !== 1 ? "s" : ""}</div>
            </div>
          </button>
        </div>
      )}
    </div>
  );
};

/* Top bar (reusable) */
const TopBar = ({ showSync = false }) => {
  const proj = typeof currentProject === "function" ? currentProject() : {};
  const projName = proj.name || proj.url || "My Workspace";
  const sess = (() => { try { return JSON.parse(localStorage.getItem("boltkit.session.v1") || "null"); } catch { return null; } })();
  const name = sess?.user?.name || "Sam";
  const initials = name.split(" ").map(n => n[0]).join("").slice(0, 2).toUpperCase();

  const projId = proj.id || null;
  const [igStatus, setIgStatus] = React.useState(null);
  const [savedAt, setSavedAt] = React.useState(null);

  React.useEffect(() => {
    let cancelled = false;
    // Fetch IG status scoped to the active project so the chip reflects the
    // account actually connected to this project (not a stale global value).
    const statusUrl = projId ? `/api/meta/status?projectId=${encodeURIComponent(projId)}` : "/api/meta/status";
    fetch(statusUrl).then(r => r.json()).then(d => {
      if (cancelled) return;
      setIgStatus({ connected: Boolean(d.accounts?.[0]), username: d.accounts?.[0]?.username || null });
    }).catch(() => {});
    // Listen for live connect events
    const onConnected = (e) => {
      const acc = e.detail || {};
      setIgStatus({ connected: true, username: acc.username || null });
    };
    // Listen for save events dispatched by screens
    const onSaved = () => setSavedAt(new Date());
    window.addEventListener("boltkit:instagram-connected", onConnected);
    window.addEventListener("boltkit:saved", onSaved);
    return () => {
      cancelled = true;
      window.removeEventListener("boltkit:instagram-connected", onConnected);
      window.removeEventListener("boltkit:saved", onSaved);
    };
  }, [projId]);

  const igChip = igStatus?.connected ? (
    <button
      onClick={() => window.BoltKitGo?.("ig-connect")}
      style={{ display: "flex", alignItems: "center", gap: 5, background: "#0D1F0D", border: "1px solid #1A3D1A", borderRadius: 5, padding: "4px 9px", cursor: "pointer" }}
    >
      <span style={{ width: 6, height: 6, borderRadius: "50%", background: "#4ADE80", display: "inline-block", flexShrink: 0 }} />
      <span style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 9, color: "#4ADE80", letterSpacing: "0.1em", fontWeight: 700 }}>
        IG {igStatus.username ? `@${igStatus.username}` : "CONNECTED"}
      </span>
    </button>
  ) : igStatus ? (
    <button
      onClick={() => window.BoltKitConnectInstagram?.()}
      style={{ display: "flex", alignItems: "center", gap: 5, background: "#1F0D0D", border: "1px solid #3D1A1A", borderRadius: 5, padding: "4px 9px", cursor: "pointer" }}
    >
      <span style={{ width: 6, height: 6, borderRadius: "50%", background: "#FF4D5E", display: "inline-block", flexShrink: 0 }} />
      <span style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 9, color: "#FF4D5E", letterSpacing: "0.1em", fontWeight: 700 }}>CONNECT IG</span>
    </button>
  ) : null;

  const savedChip = savedAt ? (
    <div style={{ display: "flex", alignItems: "center", gap: 5, padding: "4px 9px" }}>
      <span style={{ width: 6, height: 6, borderRadius: "50%", background: "#4ADE80", display: "inline-block" }} />
      <span style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 9, color: "#4ADE80", letterSpacing: "0.1em" }}>SAVED</span>
    </div>
  ) : (
    <div style={{ display: "flex", alignItems: "center", gap: 5, padding: "4px 9px" }}>
      <span style={{ width: 6, height: 6, borderRadius: "50%", background: "#3A372F", display: "inline-block" }} />
      <span style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 9, color: "#5C5C5C", letterSpacing: "0.1em" }}>AUTO-SAVE ON</span>
    </div>
  );

  return (
    <div className="bk-topbar" style={{
      height: 52, background: "rgba(5,5,5,0.9)",
      borderBottom: "1px solid #3A372F",
      display: "flex", alignItems: "center", gap: 8,
      padding: "0 16px", flex: "none",
    }}>
      <button className="bk-topbar-project" onClick={() => window.BoltKitGo?.("wizard")} style={{ display: "flex", alignItems: "center", gap: 8, background: "#26241E", border: "1px solid #3A372F", padding: "6px 10px", borderRadius: 4, fontSize: 12, fontWeight: 700, color: "#F4F4F0", cursor: "pointer", maxWidth: 220 }}>
        <div style={{ width: 22, height: 22, borderRadius: 4, background: "#EFFF00", flex: "none" }} />
        <span style={{ whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{projName}</span>
        <Icon name="chevron_down" size={11} stroke={2} />
      </button>
      {/* bk-topbar-search: hidden on mobile, future global search entry point */}
      <input className="bk-topbar-search" placeholder="Search…" style={{ display: "none" }} readOnly tabIndex={-1} aria-hidden="true" />
      <span style={{ flex: 1 }} />
      {savedChip}
      {igChip}
      <button className="bk-topbar-quick" onClick={() => window.dispatchEvent(new CustomEvent("boltkit:generate", { detail: { packType: "instagram-pack" } }))} style={{ background: "#EFFF00", color: "#1A1813", border: 0, padding: "7px 12px", fontFamily: "'JetBrains Mono', monospace", fontSize: 10.5, fontWeight: 800, letterSpacing: "0.14em", textTransform: "uppercase", display: "inline-flex", alignItems: "center", gap: 6, cursor: "pointer" }}>
        <BoltMini size={12} color="#1A1813" />
        Quick Generate
      </button>
      <div className="bk-topbar-avatar" onClick={() => window.BoltKitGo?.("settings")} style={{ width: 28, height: 28, background: "#EFFF00", color: "#1A1813", display: "grid", placeItems: "center", borderRadius: 999, fontFamily: "'Anton', Impact, sans-serif", fontSize: 13, cursor: "pointer", flex: "none" }}>{initials}</div>
    </div>
  );
};

Object.assign(window, { AppIco, Pill, Meter, SyncChip, BoltMini, RingScore, MiniPhone, Ribbon, SidebarNav, TopBar });
