/* global React, ReactDOM */

const SBIcon = {
  home: (<svg className="sb-icon" viewBox="0 0 16 16" fill="none"><path d="M2 7l6-5 6 5v7H2V7z" stroke="currentColor" strokeWidth="1.4" strokeLinejoin="round"/></svg>),
  list: (<svg className="sb-icon" viewBox="0 0 16 16" fill="none"><path d="M3 4h10M3 8h10M3 12h10" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/></svg>),
  doc: (<svg className="sb-icon" viewBox="0 0 16 16" fill="none"><path d="M3 1.5h6L13 5.5v9H3v-13z" stroke="currentColor" strokeWidth="1.4" strokeLinejoin="round"/><path d="M9 1.5V6h4" stroke="currentColor" strokeWidth="1.4"/></svg>),
  edit: (<svg className="sb-icon" viewBox="0 0 16 16" fill="none"><path d="M11.5 2.5l2 2-8 8H3.5v-2l8-8z" stroke="currentColor" strokeWidth="1.4" strokeLinejoin="round"/></svg>),
  eye: (<svg className="sb-icon" viewBox="0 0 16 16" fill="none"><path d="M1 8s2.5-5 7-5 7 5 7 5-2.5 5-7 5-7-5-7-5z" stroke="currentColor" strokeWidth="1.4"/><circle cx="8" cy="8" r="2.2" stroke="currentColor" strokeWidth="1.4"/></svg>),
  card: (<svg className="sb-icon" viewBox="0 0 16 16" fill="none"><rect x="1.5" y="3.5" width="13" height="9" stroke="currentColor" strokeWidth="1.4"/><path d="M2 6.5h12" stroke="currentColor" strokeWidth="1.4"/></svg>),
  cash: (<svg className="sb-icon" viewBox="0 0 16 16" fill="none"><rect x="1.5" y="3.5" width="13" height="9" stroke="currentColor" strokeWidth="1.4"/><circle cx="8" cy="8" r="2" stroke="currentColor" strokeWidth="1.4"/></svg>),
  spark: (<svg className="sb-icon" viewBox="0 0 16 16" fill="none"><path d="M8 1l1.5 4.5L14 7l-4.5 1.5L8 13l-1.5-4.5L2 7l4.5-1.5L8 1z" fill="currentColor"/></svg>),
  cog: (<svg className="sb-icon" viewBox="0 0 16 16" fill="none"><circle cx="8" cy="8" r="2.5" stroke="currentColor" strokeWidth="1.4"/><path d="M8 1.5v2M8 12.5v2M14.5 8h-2M3.5 8h-2M12.6 3.4l-1.4 1.4M4.8 11.2l-1.4 1.4M12.6 12.6l-1.4-1.4M4.8 4.8L3.4 3.4" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/></svg>),
};

const NAV = [
  { label: "Visão Geral", items: [
    { route: "/home", label: "Início", icon: SBIcon.spark, num: "01", badge: "NEW" },
  ]},
  { label: "Cliente", items: [
    { route: "/propostas", label: "Propostas", icon: SBIcon.list, num: "12" },
    { route: "/clientes", label: "Clientes (CRM)", icon: SBIcon.doc },
    { route: "/editor", label: "Editor", icon: SBIcon.edit, badge: "IA" },
    { route: "/proposta", label: "Detalhe da proposta", icon: SBIcon.doc },
    { route: "/publica", label: "Vista pública", icon: SBIcon.eye },
  ]},
  { label: "Vendas", items: [
    { route: "/produtos", label: "Produtos", icon: SBIcon.list },
    { route: "/checkout-builder", label: "Builder de checkout", icon: SBIcon.spark },
    { route: "/checkout", label: "Checkout (preview)", icon: SBIcon.card },
    { route: "/checkout-public", label: "Página pública", icon: SBIcon.eye, badge: "NEW" },
    { route: "/assinantes", label: "Assinantes", icon: SBIcon.eye },
  ]},
  { label: "Financeiro", items: [
    { route: "/saldo", label: "Saldo & Saques", icon: SBIcon.cash },
    { route: "/pagamentos", label: "Pagamentos", icon: SBIcon.card },
  ]},
  { label: "Crescimento", items: [
    { route: "/portal", label: "Portal do assinante", icon: SBIcon.eye },
    { route: "/relatorios", label: "Relatórios & Analytics", icon: SBIcon.spark, badge: "NEW" },
  ]},
  { label: "Conta", items: [
    { route: "/onboarding", label: "Onboarding", icon: SBIcon.spark, badge: "NEW" },
    { route: "/configuracoes", label: "Configurações", icon: SBIcon.cog, badge: "NEW" },
  ]},
];

function Sidebar() {
  const [route, setRoute] = React.useState(window.location.hash.replace(/^#/, "") || "/landing");
  const [user, setUser] = React.useState(null);
  React.useEffect(() => {
    const onHash = () => setRoute(window.location.hash.replace(/^#/, "") || "/landing");
    window.addEventListener("hashchange", onHash);
    window.SEQ_API.me().then((d) => setUser(d.user));
    return () => window.removeEventListener("hashchange", onHash);
  }, []);

  async function handleLogout(e) {
    e.preventDefault();
    try {
      await window.SEQ_API.signOut();
    } catch {}
    window.location.hash = "/landing";
    window.location.reload();
  }

  const initials = (user?.name || user?.email || "K")
    .split(/[\s@]/).map((s) => s[0]).filter(Boolean).slice(0, 2).join("").toUpperCase();
  const displayName = user?.name || user?.email?.split("@")[0] || "Kaleidos";

  return (
    <>
      <div className="sb-brand">
        <div className="sb-brand-mark">Kaleidos<em>·</em> Pay</div>
        <span className="sb-brand-sub">Pagamentos · Propostas · Recorrência</span>
      </div>
      <div className="sb-search">
        <span style={{ opacity: 0.5 }}>⌕</span>
        <span style={{ flex: 1 }}>buscar…</span>
        <span style={{ opacity: 0.5 }}>⌘K</span>
      </div>

      {NAV.map((sec, i) => (
        <div className="sb-section" key={i}>
          <div className="sb-section-label">{sec.label}</div>
          {sec.items.map((it) => {
            const active = route === it.route;
            return (
              <a key={it.route} href={"#" + it.route} className={"sb-link" + (active ? " is-active" : "")} onClick={() => {
                document.getElementById("sidebar").classList.remove("is-open");
              }}>
                {it.icon}
                <span>{it.label}</span>
                {it.badge ? <span className="sb-badge">{it.badge}</span> : it.num ? <span className="sb-num">{it.num}</span> : null}
              </a>
            );
          })}
        </div>
      ))}

      <div className="sb-foot">
        <div className="sb-user">
          <div style={{
            width: 34, height: 34, background: "var(--kp-pink)", border: "1.5px solid var(--kp-paper)",
            display: "inline-flex", alignItems: "center", justifyContent: "center",
            fontFamily: "var(--kp-display)", fontSize: 16, fontStyle: "italic", color: "var(--kp-ink)",
          }}>{initials}</div>
          <div style={{ minWidth: 0 }}>
            <div className="sb-user-name">{displayName}</div>
            <div className="sb-user-plan">PRO · 31 dias</div>
          </div>
        </div>
        <div style={{ marginTop: 10, display: "flex", gap: 12 }}>
          <a href="#/configuracoes" className="sb-link" style={{ padding: "6px 0", fontSize: 11, color: "rgba(247,241,232,0.55)", border: "none" }}>Configurações</a>
          <button onClick={handleLogout} className="sb-link" style={{ padding: "6px 0", fontSize: 11, color: "rgba(247,241,232,0.55)", border: "none", background: "transparent", cursor: "pointer", fontFamily: "inherit" }}>Sair</button>
        </div>
      </div>
    </>
  );
}

window.SEQ_SIDEBAR = Sidebar;
