/* TopBar — page title, rule-engine self-test badge (with hover explainer),
   new-post + reset. */
function RulesBadge() {
  const t = window.CROPR_RULE_TESTS || { passed: 0, total: 0 };
  const green = t.total > 0 && t.passed === t.total;
  const [hover, setHover] = React.useState(false);
  const RULES = [
    "no hashtags — on any channel (X, LinkedIn, Telegram)",
    "standalone posts land in 180–220 characters",
    "threads / series capped at 4–5 parts",
    "exactly one call-to-action, on the final line",
    "proof (media, a metric, or marked) before leaving draft",
    "opener discipline — no ‘gm’, teaser or over-used framings",
  ];
  return (
    <div style={{ position: "relative" }} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}>
      <span style={{ display: "flex", alignItems: "center", gap: 7, height: 36, padding: "0 12px", borderRadius: 999, cursor: "help",
        background: green ? "var(--success-bg)" : "var(--warning-bg)", color: green ? "#0E8A50" : "#B25E09", fontSize: 12.5, fontWeight: 700 }}>
        <Icon name={green ? "shield-check" : "shield-alert"} size={16} color={green ? "#0E8A50" : "#B25E09"} />
        Rules {t.passed}/{t.total}
      </span>
      {hover && (
        <div style={{ position: "absolute", top: 44, right: 0, width: 320, zIndex: 90, background: "var(--surface)", border: "1px solid var(--border)",
          borderRadius: 14, boxShadow: "var(--shadow-lg)", padding: 16, textAlign: "left" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 8 }}>
            <Icon name="shield-check" size={16} color="var(--accent)" />
            <span style={{ fontSize: 13, fontWeight: 700 }}>Content-rule engine self-test</span>
          </div>
          <div style={{ fontSize: 12, color: "var(--fg2)", lineHeight: 1.5, marginBottom: 10 }}>
            <b>{t.passed}/{t.total}</b> unit tests run in your browser on load — one for every rule that gates a post. Green means the rules enforcing all your content are working.
          </div>
          <div style={{ fontSize: 11, fontWeight: 700, color: "var(--fg3)", textTransform: "uppercase", letterSpacing: ".05em", marginBottom: 6 }}>The rules being enforced</div>
          <ul style={{ margin: 0, paddingLeft: 16, fontSize: 12, color: "var(--fg2)", lineHeight: 1.55 }}>
            {RULES.map((r, i) => <li key={i}>{r}</li>)}
          </ul>
        </div>
      )}
    </div>
  );
}

/* User menu — the signed-in user in the header, with Sign out (live mode).
   Offline it keeps the demo "acting as" hint. */
function UserMenu() {
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef(null);
  const live = !!(window.LEAP && window.LEAP.live);
  const authed = live && window.LeapAuth && window.LeapAuth.authenticated();
  const authUser = authed ? (window.LeapAuth.state().user || {}) : null;
  const demoUser = window.CroprStore.getCurrentUser();
  const displayName = (authUser && (authUser.name || authUser.email)) || demoUser;
  const email = authUser && authUser.email;

  React.useEffect(() => {
    if (!open) return;
    const h = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown", h);
    return () => document.removeEventListener("mousedown", h);
  }, [open]);

  const chip = { display: "flex", alignItems: "center", gap: 8, height: 36, padding: "0 10px 0 6px", borderRadius: 999,
    border: "1px solid var(--border-strong)", background: "var(--surface)", cursor: "pointer" };
  const item = { display: "flex", alignItems: "center", gap: 9, width: "100%", padding: "9px 12px", borderRadius: 9,
    background: "transparent", border: "none", cursor: "pointer", fontSize: 13, fontWeight: 600, color: "var(--fg1)", textAlign: "left" };

  return (
    <div ref={ref} style={{ position: "relative" }}>
      <button style={chip} onClick={() => setOpen((o) => !o)} title={live ? "Account" : "Acting as — an admin can switch users in Settings → People"}>
        {window.memberAvatar(demoUser, 24)}
        <span style={{ fontSize: 13, fontWeight: 600, color: "var(--fg1)" }}>{displayName}</span>
        <Icon name="chevron-down" size={14} color="var(--fg3)" />
      </button>
      {open && (
        <div style={{ position: "absolute", top: 44, right: 0, width: 244, zIndex: 90, background: "var(--surface)", border: "1px solid var(--border)", borderRadius: 14, boxShadow: "var(--shadow-lg)", padding: 8 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "8px 10px 10px" }}>
            {window.memberAvatar(demoUser, 34)}
            <div style={{ minWidth: 0 }}>
              <div style={{ fontSize: 13, fontWeight: 700, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{displayName}</div>
              {email && <div style={{ fontSize: 11.5, color: "var(--fg3)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{email}</div>}
            </div>
          </div>
          <div style={{ height: 1, background: "var(--border)", margin: "2px 0 6px" }} />
          {authed ? (
            <button style={item} onClick={() => window.LeapAuth.logout()}
              onMouseEnter={(e) => (e.currentTarget.style.background = "var(--surface-hover, #F3F4F6)")}
              onMouseLeave={(e) => (e.currentTarget.style.background = "transparent")}>
              <Icon name="log-out" size={16} color="var(--fg2)" /> Sign out
            </button>
          ) : (
            <div style={{ fontSize: 12, color: "var(--fg3)", padding: "4px 12px 8px", lineHeight: 1.5 }}>
              {live ? "Signing in…" : "Demo mode — switch users in Settings → People."}
            </div>
          )}
        </div>
      )}
    </div>
  );
}

function TopBar({ title, subtitle, onNew, onReset, onOpen, onSettings }) {
  const today = new Date().toLocaleDateString("en-GB", { weekday: "long", day: "2-digit", month: "short", year: "numeric" });
  const bar = { height: 64, flex: "none", display: "flex", alignItems: "center", justifyContent: "space-between",
    padding: "0 28px", borderBottom: "1px solid var(--border)", background: "var(--surface)" };
  return (
    <header style={bar}>
      <div style={{ display: "flex", flexDirection: "column" }}>
        <span style={{ fontSize: 12, color: "var(--fg3)" }}>{today}</span>
        <h1 style={{ fontSize: 20, fontWeight: 700, letterSpacing: "-.01em" }}>{title}{subtitle && <span style={{ fontWeight: 500, color: "var(--fg3)", fontSize: 15 }}> · {subtitle}</span>}</h1>
      </div>
      <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
        <RulesBadge />
        <UserMenu />
        <NotificationBell onOpen={onOpen} onSettings={onSettings} />
        <Button variant="secondary" icon="rotate-ccw" onClick={onReset} title="Reset demo data" />
      </div>
    </header>
  );
}
window.TopBar = TopBar;
