// CENTRAL DA MARCA — Sanvi Activewear · UI compartilhada: login, sidebar, componentes.
// Exporta window.SV_UI
(function () {
  const { useState, useEffect, useRef } = React;
  const h = React.createElement;
  const D = window.SV_DATA;
  const S = window.SV_STORE;

  // ─── DROPDOWN (seleção única) ───
  function Dropdown({ value, options, onChange, placeholder, full, align }) {
    const [open, setOpen] = useState(false);
    const ref = useRef(null);
    useEffect(() => { function onDoc(e) { if (ref.current && !ref.current.contains(e.target)) setOpen(false); } document.addEventListener("mousedown", onDoc); return () => document.removeEventListener("mousedown", onDoc); }, []);
    const opts = (options || []).map((o) => (typeof o === "string" ? { value: o, label: o } : o));
    const cur = opts.find((o) => o.value === value);
    return h("div", { className: "dd" + (open ? " open" : "") + (full ? " dd-full" : ""), ref },
      h("button", { type: "button", className: "dd-btn", onClick: () => setOpen((o) => !o) },
        h("span", { className: "dd-btn-txt" }, cur ? cur.label : (placeholder || "Selecionar")),
        h("span", { className: "dd-caret" }, "\u25be")),
      open && h("div", { className: "dd-menu" + (align === "right" ? " right" : "") }, opts.map((o) => h("button", { type: "button", key: o.value, className: "dd-opt" + (o.value === value ? " on" : ""), onClick: () => { onChange(o.value); setOpen(false); } }, o.label)))
    );
  }

  // ─── MULTI-DROPDOWN (múltipla escolha) ───
  function MultiDropdown({ values, options, onToggle, placeholder, full }) {
    const [open, setOpen] = useState(false);
    const ref = useRef(null);
    useEffect(() => { function onDoc(e) { if (ref.current && !ref.current.contains(e.target)) setOpen(false); } document.addEventListener("mousedown", onDoc); return () => document.removeEventListener("mousedown", onDoc); }, []);
    const vals = values || [];
    const txt = vals.length ? (vals.length <= 2 ? vals.join(" \u00b7 ") : vals.length + " selecionados") : (placeholder || "Selecionar");
    return h("div", { className: "dd" + (open ? " open" : "") + (full ? " dd-full" : ""), ref },
      h("button", { type: "button", className: "dd-btn", onClick: () => setOpen((o) => !o) },
        h("span", { className: "dd-btn-txt" }, txt),
        h("span", { className: "dd-caret" }, "\u25be")),
      open && h("div", { className: "dd-menu" }, (options || []).map((o) => { const val = typeof o === "string" ? o : o.value; const lab = typeof o === "string" ? o : o.label; const on = vals.includes(val); return h("button", { type: "button", key: val, className: "dd-opt" + (on ? " on" : ""), onClick: () => onToggle(val) }, h("span", { className: "dd-ck" }, on ? "\u2713" : ""), lab); }))
    );
  }

  function SyncBadge() {
    const C = window.SV_CLOUD;
    const [st, setSt] = useState(C ? C.status() : "local");
    useEffect(() => { if (C && C.onStatus) return C.onStatus(setSt); }, []);
    const map = {
      local: { d: "●", t: "Salvo neste aparelho", c: "sync-local" },
      conectando: { d: "◍", t: "Conectando à nuvem…", c: "sync-wait" },
      salvando: { d: "◍", t: "Salvando na nuvem…", c: "sync-wait" },
      ok: { d: "●", t: "Sincronizado na nuvem", c: "sync-ok" },
      erro: { d: "▲", t: "Sem conexão — salvo local", c: "sync-err" },
    };
    const m = map[st] || map.local;
    return h("div", { className: "sync " + m.c }, h("span", { className: "sync-dot" }, m.d), h("span", null, m.t));
  }

  // ─── LOGIN ───
  function Login({ onOk }) {
    const [user, setUser] = useState("");
    const [pass, setPass] = useState("");
    const [err, setErr] = useState("");
    const [busy, setBusy] = useState(false);
    async function submit(e) {
      e && e.preventDefault();
      if (busy) return;
      setBusy(true); setErr("");
      const ok = await S.login(user, pass);
      setBusy(false);
      if (ok) onOk();
      else setErr("Usuário ou senha incorretos. Tente novamente.");
    }
    return h("div", { className: "lg-wrap" },
      h("form", { className: "lg-card", onSubmit: submit },
        h("div", { className: "lg-mark" }, "S"),
        h("div", { className: "lg-eyebrow" }, "Central da Marca"),
        h("div", { className: "lg-title" }, "Sanvi Activewear"),
        h("div", { className: "lg-sub" }, "Estilo de vida ativo · acesso protegido"),
        h("div", { className: "lg-field" },
          h("label", null, "Usuário"),
          h("input", { className: "lg-input", value: user, autoFocus: true, autoComplete: "username", placeholder: "seu usuário", onChange: (e) => setUser(e.target.value) })
        ),
        h("div", { className: "lg-field" },
          h("label", null, "Senha"),
          h("input", { className: "lg-input", type: "password", value: pass, autoComplete: "current-password", placeholder: "••••••••", onChange: (e) => setPass(e.target.value) })
        ),
        h("div", { className: "lg-err" }, err),
        h("button", { type: "submit", className: "btn btn-pri full", disabled: busy, style: { height: 46 } }, busy ? "Entrando…" : "Entrar"),
        h("div", { className: "lg-note" },
          h("span", null, "🔒"),
          h("span", null, h("b", null, "Central exclusiva da Sanvi."), " Gestão de conteúdo pela Agência Logue.")
        )
      )
    );
  }

  // ─── SIDEBAR ───
  const NAV = [
    { grp: "Marca", items: [
      { id: "inicio", ic: "◈", nome: "Início" },
      { id: "aprovar-ideias", ic: "✎", nome: "Aprovar ideias" },
      { id: "aprovar-design", ic: "◫", nome: "Aprovar conteúdo" },
    ] },
    { grp: "Produção", items: [
      { id: "posts", ic: "▤", nome: "Posts entregues" },
      { id: "campanha", ic: "❋", nome: "Movimento Sanvi" },
      { id: "calendario", ic: "▦", nome: "Calendário" },
    ] },
    { grp: "Parceria", items: [
      { id: "divulgacao", ic: "⇄", nome: "Divulgação Logue" },
    ] },
    { grp: "Recursos", items: [
      { id: "arquivos", ic: "▣", nome: "Arquivos & Logos" },
      { id: "ferramentas", ic: "✦", nome: "Ferramentas" },
    ] },
  ];

  function Sidebar({ rota, go, open, setOpen, onLogout }) {
    const r = S.resumo();
    const badges = { "aprovar-ideias": r.novas + r.analise, "aprovar-design": r.aguardandoDesign };
    return h("aside", { className: "side" + (open ? " open" : "") },
      h("div", { className: "side-brand" },
        h("div", { className: "side-mark" }, "S"),
        h("div", null, h("div", { className: "side-brand-n" }, "Sanvi"), h("div", { className: "side-brand-s" }, "Central da Marca"))
      ),
      h("nav", { className: "nav" }, NAV.map((g) => h(React.Fragment, { key: g.grp },
        h("div", { className: "nav-lbl" }, g.grp),
        g.items.map((it) => h("button", { key: it.id, className: "nav-item" + (rota === it.id ? " on" : ""), onClick: () => { go(it.id); setOpen && setOpen(false); } },
          h("span", { className: "nav-ic" }, it.ic),
          h("span", { className: "grow" }, it.nome),
          badges[it.id] ? h("span", { className: "nav-badge" }, badges[it.id]) : null
        ))
      ))),
      h("div", { className: "side-foot" },
        h(SyncBadge, null),
        h("div", { className: "side-user" },
          h("div", { className: "side-av" }, "S"),
          h("div", null, h("div", { className: "side-user-n" }, "Sabrina Sanches"), h("div", { className: "side-user-r" }, "Fundadora · Sanvi"))
        ),
        h("button", { className: "side-out", onClick: onLogout }, "↩  Sair da central")
      )
    );
  }

  // ─── COMPONENTES ───
  function PageHead({ eyebrow, titulo, sub, actions }) {
    return h("div", { className: "phead" },
      h("div", null,
        eyebrow && h("div", { className: "phead-eyebrow" }, eyebrow),
        h("h1", { className: "phead-t" }, titulo),
        sub && h("div", { className: "phead-s" }, sub)
      ),
      actions && h("div", { className: "phead-actions" }, actions)
    );
  }

  function StatusPill({ status, big }) {
    const cor = D.STATUS_COR[status] || "#8A8F94";
    return h("span", { className: "pill", style: { background: cor + "1E", color: cor, fontSize: big ? 12.5 : 11, padding: big ? "5px 13px" : undefined } },
      h("span", { style: { width: 6, height: 6, borderRadius: 6, background: cor, display: "inline-block" } }), status);
  }

  function Modal({ onClose, children, wide }) {
    return h("div", { className: "modal-bg", onClick: onClose },
      h("div", { className: "modal", style: wide ? { maxWidth: 760 } : undefined, onClick: (e) => e.stopPropagation() },
        h("button", { className: "modal-x", onClick: onClose }, "✕"),
        h("div", { className: "modal-body" }, children)
      )
    );
  }

  window.SV_UI = { Login, Sidebar, PageHead, StatusPill, Modal, NAV, Dropdown, MultiDropdown };
})();
