// SQSEO app top bar: live project switcher (+ create), filters, alerts panel,
// and the account menu. Reads window.LTQ.boot; mutations use window.LTQ.api and
// refresh the shell in place via window.LTQ.reloadBoot (no full page reload).
(function init(){
if(!window.LongtailIQDesignSystem_ae8f12 || !window.LTQ || !window.LTQ.Popover || !window.LTQ.t){return setTimeout(init,30);}
const React = window.React;
const DS = window.LongtailIQDesignSystem_ae8f12;
const { Icon, Avatar } = DS;
const { Popover, MenuItem, Modal, api, toast, reloadBoot, t } = window.LTQ;

const DIVIDER = <div style={{ height: 1, background: "var(--border-subtle)", margin: "5px 4px" }} />;
const SEV_COLOR = { success: "var(--viz-green)", warning: "var(--viz-amber)", error: "var(--viz-red)", info: "var(--text-faint)" };

function relTime(iso){
  if (!iso) return "";
  const s = Math.max(0, (Date.now() - new Date(iso).getTime()) / 1000);
  if (s < 60) return t("time.just_now");
  if (s < 3600) return t("time.m_ago", { n: Math.floor(s / 60) });
  if (s < 86400) return t("time.h_ago", { n: Math.floor(s / 3600) });
  if (s < 604800) return t("time.d_ago", { n: Math.floor(s / 86400) });
  return window.LTQ.fmtDate(iso);
}


// ------------------------------------------------------------ New project modal
function NewProjectModal({ onClose }) {
  const [name, setName] = React.useState("");
  const [site, setSite] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const submit = async (e) => {
    e && e.preventDefault();
    if (!name.trim()) return;
    setBusy(true);
    const r = await api.post("/api/projects", { name: name.trim(), site_url: site.trim() });
    setBusy(false);
    if (r.ok) { await reloadBoot(); toast(t("chrome.project_created"), { tone: "success" }); onClose(); }
    else toast(r.error || t("chrome.project_create_failed"), { tone: "error" });
  };
  const field = { width: "100%", height: 42, padding: "0 12px", borderRadius: 10, background: "var(--surface-card)",
    border: "1px solid var(--border-strong)", fontFamily: "var(--font-sans)", fontSize: 14, color: "var(--text-strong)", outline: "none" };
  return (
    <Modal title={t("chrome.new_project")} sub={t("chrome.new_project_sub")} onClose={onClose}>
      <form onSubmit={submit} style={{ display: "flex", flexDirection: "column", gap: 12 }}>
        <label style={{ fontSize: 12.5, fontWeight: 600, color: "var(--text-body)" }}>{t("chrome.project_name")}
          <input autoFocus value={name} onChange={(e)=>setName(e.target.value)} placeholder="Acme Hair Co." style={{ ...field, marginTop: 6 }} />
        </label>
        <label style={{ fontSize: 12.5, fontWeight: 600, color: "var(--text-body)" }}>{t("chrome.website")} <span style={{ color: "var(--text-faint)", fontWeight: 500 }}>{t("wizard.optional")}</span>
          <input value={site} onChange={(e)=>setSite(e.target.value)} placeholder="acmehairco.com" style={{ ...field, marginTop: 6 }} />
        </label>
        <div style={{ display: "flex", justifyContent: "flex-end", gap: 8, marginTop: 4 }}>
          <button type="button" onClick={onClose} style={{ height: 38, padding: "0 14px", borderRadius: 9, border: "1px solid var(--border-subtle)", background: "var(--paper)", cursor: "pointer", fontFamily: "var(--font-sans)", fontSize: 13, fontWeight: 600, color: "var(--text-body)" }}>{t("chrome.cancel")}</button>
          <button type="submit" disabled={busy || !name.trim()} style={{ height: 38, padding: "0 16px", borderRadius: 9, border: "none", background: "var(--ink-900)", color: "#fff", cursor: name.trim()?"pointer":"default", opacity: name.trim()?1:0.6, fontFamily: "var(--font-sans)", fontSize: 13, fontWeight: 600, display: "inline-flex", alignItems: "center", gap: 7 }}>
            {busy ? <span className="lt-spin" style={{ width: 14, height: 14, border: "2px solid rgba(255,255,255,0.4)", borderTopColor: "#fff", borderRadius: 999 }} /> : <Icon name="plus" size={15} />} {t("chrome.create_project")}
          </button>
        </div>
      </form>
    </Modal>
  );
}
window.LTQ.NewProjectModal = NewProjectModal; // reused by the Settings screen

// --------------------------------------------------------------- ProjectSwitcher
function ProjectSwitcher() {
  const boot = window.LTQ.boot || {};
  const projects = boot.projects || [];
  const active = boot.project || null;
  const [adding, setAdding] = React.useState(false);
  const [hover, setHover] = React.useState(false);
  const label = active ? active.name : projects.length ? projects[0].name : t("chrome.no_project");

  const switchTo = async (p, close) => {
    close();
    if (active && p.id === active.id) return;
    const r = await api.post("/api/project/switch", { projectId: p.id });
    if (r.ok) { await reloadBoot(); toast(t("chrome.switched_to", { name: p.name })); }
    else toast(r.error || t("chrome.project_switch_failed"), { tone: "error" });
  };

  return (
    <>
      <Popover align="left" width={280}
        trigger={(open, toggle) => (
          <button onClick={toggle} onMouseEnter={()=>setHover(true)} onMouseLeave={()=>setHover(false)}
            style={{ display: "inline-flex", alignItems: "center", gap: 7, height: 32, padding: "0 11px",
              background: hover || open ? "var(--ink-50)" : "var(--paper)", border: "1px solid var(--border-subtle)",
              borderRadius: 8, cursor: "pointer", fontFamily: "var(--font-sans)", fontSize: 12.5, fontWeight: 600,
              color: "var(--text-strong)", maxWidth: 240, transition: "background var(--dur-fast)" }}>
            <Icon name="folder" size={14} style={{ color: "var(--text-faint)", flex: "none" }} />
            <span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{label}</span>
            <Icon name="chevron-down" size={13} style={{ color: "var(--text-faint)", flex: "none" }} />
          </button>
        )}>
        {(close) => (
          <>
            <div style={{ fontSize: 11, fontWeight: 600, color: "var(--text-faint)", letterSpacing: "0.02em", padding: "4px 9px 6px" }}>{t("chrome.projects")}</div>
            {projects.map((p) => (
              <MenuItem key={p.id} icon="globe" label={p.name} sub={p.label || p.site_url || null}
                active={active && p.id === active.id}
                trailing={active && p.id === active.id ? <Icon name="check" size={15} style={{ color: "var(--accent-500)", flex: "none" }} /> : null}
                onClick={() => switchTo(p, close)} />
            ))}
            {DIVIDER}
            <MenuItem icon="plus" label={t("chrome.new_project")} onClick={() => { close(); setAdding(true); }} />
          </>
        )}
      </Popover>
      {adding && <NewProjectModal onClose={() => setAdding(false)} />}
    </>
  );
}

// --------------------------------------------------------------------- Alerts
function AlertsBell() {
  const boot = window.LTQ.boot || {};
  const unread = (boot.counts && boot.counts.alertsUnread) || 0;
  const [items, setItems] = React.useState(null); // null = loading, "error" = failed
  const load = async () => { const r = await api.get("/api/alerts"); setItems(r.ok ? r.data.alerts || [] : "error"); };
  const markRead = async () => { await api.post("/api/alerts/read", {}); await load(); await reloadBoot(); toast(t("chrome.all_caught_up")); };
  return (
    <Popover align="right" width={360}
      trigger={(open, toggle) => (
        <button onClick={() => { if (!open) load(); toggle(); }} aria-label={t("chrome.notifications")}
          style={{ position: "relative", width: 32, height: 32, display: "grid", placeItems: "center", border: "1px solid var(--border-subtle)", background: open ? "var(--ink-50)" : "var(--paper)", borderRadius: 8, cursor: "pointer", color: "var(--text-muted)" }}>
          <Icon name="bell" size={15} />
          {unread > 0 && (
            <span style={{ position: "absolute", top: -5, right: -5, minWidth: 16, height: 16, padding: "0 4px", borderRadius: 999,
              background: "var(--accent-500)", color: "#fff", fontFamily: "var(--font-mono)", fontSize: 9.5, fontWeight: 700, display: "grid", placeItems: "center", border: "2px solid var(--paper)" }}>{unread > 9 ? "9+" : unread}</span>
          )}
        </button>
      )}>
      {() => (
        <div style={{ width: 348 }}>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "4px 8px 8px" }}>
            <span style={{ fontSize: 13, fontWeight: 700, color: "var(--text-strong)" }}>{t("chrome.notifications")}</span>
            {unread > 0 && <button onClick={markRead} style={{ border: "none", background: "transparent", cursor: "pointer", fontSize: 12, fontWeight: 600, color: "var(--accent-600)" }}>{t("chrome.mark_all_read")}</button>}
          </div>
          <div className="lt-scroll" style={{ maxHeight: 360, overflowY: "auto" }}>
            {items === null && <div style={{ padding: "20px 12px", textAlign: "center", fontSize: 13, color: "var(--text-faint)" }}>{t("chrome.loading")}</div>}
            {items === "error" && (
              <div style={{ padding: "20px 12px", textAlign: "center", fontSize: 13, color: "var(--text-faint)" }}>
                {t("chrome.load_failed")}{" "}
                <button onClick={() => { setItems(null); load(); }} style={{ border: "none", background: "transparent", cursor: "pointer", fontSize: 13, fontWeight: 600, color: "var(--accent-600)" }}>{t("chrome.retry")}</button>
              </div>
            )}
            {Array.isArray(items) && items.length === 0 && (
              <div style={{ padding: "26px 16px", textAlign: "center", color: "var(--text-faint)" }}>
                <Icon name="check-circle" size={22} style={{ color: "var(--viz-green)" }} />
                <div style={{ fontSize: 13, marginTop: 6 }}>{t("chrome.caught_up_empty")}</div>
              </div>
            )}
            {Array.isArray(items) && items.map((a) => (
              <div key={a.id} style={{ display: "flex", gap: 10, padding: "10px 9px", borderRadius: 9, background: a.read_at ? "transparent" : "var(--ink-50)" }}>
                <span style={{ marginTop: 5, width: 7, height: 7, borderRadius: 999, flex: "none", background: SEV_COLOR[a.severity] || SEV_COLOR.info }} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 600, color: "var(--text-strong)" }}>{a.title}</div>
                  {a.body && <div style={{ fontSize: 12, color: "var(--text-muted)", lineHeight: 1.45, marginTop: 2 }}>{a.body}</div>}
                  <div style={{ fontSize: 11, color: "var(--text-faint)", marginTop: 3 }}>{relTime(a.created_at)}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}
    </Popover>
  );
}

// ----------------------------------------------------------------- Account menu
function AccountMenu({ onNavigate }) {
  const boot = window.LTQ.boot || {};
  const user = boot.user || {};
  const signOut = async () => { await api.post("/api/auth/logout"); window.location.href = "/app/login.html"; };
  return (
    <Popover align="right" width={232}
      trigger={(open, toggle) => (
        <button onClick={toggle} aria-label={t("chrome.account")} style={{ border: "none", background: "transparent", cursor: "pointer", padding: 0, borderRadius: 999, marginLeft: 4, outline: open ? "2px solid var(--accent-300)" : "none", outlineOffset: 2 }}>
          <Avatar name={user.name || t("chrome.you")} size={32} />
        </button>
      )}>
      {(close) => (
        <>
          <div style={{ padding: "6px 9px 8px" }}>
            <div style={{ fontSize: 13.5, fontWeight: 700, color: "var(--text-strong)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{user.name || t("chrome.you")}</div>
            <div style={{ fontSize: 12, color: "var(--text-faint)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{user.email || ""}</div>
          </div>
          {DIVIDER}
          <MenuItem icon="settings" label={t("nav.settings")} onClick={() => { close(); onNavigate && onNavigate("settings"); }} />
          <MenuItem icon="life-buoy" label={t("chrome.help_docs")} onClick={() => { close(); window.open("/help", "_blank"); }} />
          {DIVIDER}
          <MenuItem icon="log-out" label={t("chrome.sign_out")} danger onClick={signOut} />
        </>
      )}
    </Popover>
  );
}

// Export menu: downloads CSVs for the active project. History export honours the
// date window the user last picked on the dashboard (persisted in localStorage).
function ExportMenu() {
  const download = (path) => {
    const a = document.createElement("a");
    a.href = path;
    a.rel = "noopener";
    document.body.appendChild(a);
    a.click();
    a.remove();
    toast(t("chrome.export_started"), { tone: "success" });
  };
  let days = 90;
  try { const v = Number(localStorage.getItem("sqseo_days")); if ([7, 28, 90, 365].includes(v)) days = v; } catch (e) {}
  return (
    <Popover align="right" width={264}
      trigger={(open, toggle) => (
        <button onClick={toggle} className="lt-hide-mobile" aria-label={t("chrome.export")}
          style={{ display: "inline-flex", alignItems: "center", gap: 7, height: 32, padding: "0 12px", border: "1px solid var(--border-subtle)", background: open ? "var(--ink-50)" : "var(--paper)", borderRadius: 8, cursor: "pointer", fontFamily: "var(--font-sans)", fontSize: 12.5, fontWeight: 500, color: "var(--text-body)" }}>
          <Icon name="download" size={14} /> {t("chrome.export")} <Icon name="chevron-down" size={13} style={{ color: "var(--text-faint)" }} />
        </button>
      )}>
      {(close) => (
        <>
          <div style={{ fontSize: 11, fontWeight: 600, color: "var(--text-faint)", letterSpacing: "0.02em", padding: "4px 9px 6px" }}>{t("chrome.download_csv")}</div>
          <MenuItem icon="line-chart" label={t("chrome.performance_history")} sub={days >= 365 ? t("chrome.window_12m") : t("chrome.window_days", { n: days })} onClick={() => { close(); download("/api/export/history.csv?days=" + days); }} />
          <MenuItem icon="list" label={t("chrome.all_keywords")} onClick={() => { close(); download("/api/export/keywords.csv"); }} />
          <MenuItem icon="layers" label={t("chrome.clusters")} onClick={() => { close(); download("/api/export/clusters.csv"); }} />
        </>
      )}
    </Popover>
  );
}

function Topbar({ onNavigate, onMenu, onOpenPalette }) {
  return (
    <header data-tour="topbar" style={{ height: "var(--topbar-h)", flex: "none", display: "flex", alignItems: "center", gap: 8,
      padding: "0 20px", borderBottom: "1px solid var(--border-subtle)", background: "var(--paper)",
      position: "sticky", top: 0, zIndex: 20 }}>
      <button className="lt-menu-btn" onClick={onMenu} aria-label={t("chrome.open_menu")}
        style={{ width: 44, height: 44, margin: "0 -4px 0 -8px", placeItems: "center", border: "1px solid var(--border-subtle)", background: "var(--paper)", borderRadius: 10, cursor: "pointer", color: "var(--text-muted)" }}>
        <Icon name="menu" size={18} />
      </button>
      <ProjectSwitcher />
      <div style={{ flex: 1 }} />

      <button onClick={onOpenPalette} aria-label={t("chrome.search_shortcut")} className="lt-hide-mobile"
        style={{ display: "inline-flex", alignItems: "center", gap: 8, height: 32, padding: "0 10px", border: "1px solid var(--border-subtle)", background: "var(--paper)", borderRadius: 8, cursor: "pointer", color: "var(--text-faint)" }}>
        <Icon name="search" size={14} />
        <kbd style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, color: "var(--text-faint)" }}>⌘K</kbd>
      </button>
      <AlertsBell />
      <ExportMenu />
      <button className="lt-hide-mobile" onClick={() => onNavigate && onNavigate("saved")} style={{ display: "inline-flex", alignItems: "center", gap: 7, height: 32, padding: "0 12px", border: "none", background: "var(--ink-900)", color: "#fff", borderRadius: 8, cursor: "pointer", fontFamily: "var(--font-sans)", fontSize: 12.5, fontWeight: 500 }}><Icon name="bookmark-plus" size={14} /> {t("nav.saved")}</button>
      <AccountMenu onNavigate={onNavigate} />
    </header>
  );
}
window.LTQ.Topbar = Topbar;
})();
