/* ANISAN — Top bar. Search field, period filter, icons, user chip.
   Mirrors the Coursue top bar but in the warm ledger palette. */

function TopBar({ unit, period, setPeriod, mobile, onMenu, active, user, onLogout }) {
  const store = window.useStore();
  const [menu, setMenu] = React.useState(false);
  React.useEffect(() => {
    if (!menu) return;
    const close = () => setMenu(false);
    window.addEventListener("click", close);
    return () => window.removeEventListener("click", close);
  }, [menu]);
  const saved = store.lastSaved;
  const savedTxt = saved ? ("salvo " + saved.toLocaleTimeString("pt-BR", { hour: "2-digit", minute: "2-digit" })) : "salvo automaticamente";
  const restore = () => { if (window.confirm("Restaurar todos os dados de exemplo? As alterações salvas serão perdidas.")) store.reset(); };
  return (
    <header style={{
      display: "flex", alignItems: "center", flexWrap: "wrap", columnGap: mobile ? 10 : 14, rowGap: 12,
      padding: mobile ? "12px 14px" : "18px 32px", borderBottom: "1px solid var(--hairline)",
      position: mobile ? "sticky" : "static", top: 0, background: "var(--ink)", zIndex: 60,
    }}>
      {mobile && (
        <button onClick={onMenu} title="Menu" style={{ ...iconBtn, width: 40 }}>
          <i data-lucide="menu" style={{ width: 19, height: 19, strokeWidth: 1.8 }}></i>
        </button>
      )}

      <div style={{ flex: 1, minWidth: 0 }}></div>

      <div style={{ display: "flex", alignItems: "center", flexWrap: "wrap", gap: mobile ? 8 : 12, marginLeft: "auto" }}>
        {period && setPeriod && active !== "painel" && active !== "fixas" && active !== "checklist" && (
          <div style={{ display: "flex", alignItems: "center", gap: 9 }}>
            {!mobile && <span style={{ fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--muted-2)" }}>Período</span>}
            <DateRange from={period.from} to={period.to} onChange={setPeriod} />
          </div>
        )}

        {!mobile && (
          <div style={{ display: "flex", alignItems: "center", gap: 7, fontFamily: "var(--font-mono)", fontSize: 10.5, letterSpacing: "0.03em", color: "var(--jade)", whiteSpace: "nowrap" }}>
            <i data-lucide="check-circle-2" style={{ width: 13, height: 13, strokeWidth: 1.8 }}></i>{savedTxt}
          </div>
        )}

        <button onClick={restore} title="Restaurar dados de exemplo" style={{ ...iconBtn, width: mobile ? 40 : "auto", borderRadius: "var(--radius-pill)", padding: mobile ? 0 : "0 14px", gap: 7, fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--muted)", whiteSpace: "nowrap" }}>
          <i data-lucide="rotate-ccw" style={iconGlyph}></i>{!mobile && "Restaurar"}
        </button>

        <div style={{ position: "relative" }} onClick={(e) => e.stopPropagation()}>
          <button onClick={() => setMenu((m) => !m)} title="Conta" style={{ display: "flex", alignItems: "center", gap: 11, paddingLeft: mobile ? 0 : 12, borderLeft: mobile ? "none" : "1px solid var(--hairline)", background: "none", border: "none", cursor: "pointer", borderRadius: 8 }}>
            {!mobile && (
              <span style={{ textAlign: "right", whiteSpace: "nowrap" }}>
                <span style={{ display: "block", fontFamily: "var(--font-body)", fontSize: 13, color: "var(--paper)", fontWeight: 500 }}>{(user && user.nome) || "Usuário"}</span>
                <span style={{ display: "block", fontFamily: "var(--font-mono)", fontSize: 10.5, color: "var(--muted-2)", marginTop: 1 }}>{unit} · {user && user.role === "master" ? "Master" : "Comum"}</span>
              </span>
            )}
            <span style={{
              width: 38, height: 38, borderRadius: "50%", background: "var(--surface-2)", flexShrink: 0,
              border: `1px solid ${menu ? "var(--brass)" : "var(--hairline-strong)"}`, display: "grid", placeItems: "center",
              fontFamily: "var(--font-display)", fontWeight: 500, fontSize: 15, color: "var(--brass)", lineHeight: 1,
            }}>{(((user && user.nome) || "U").split(/[\s—-]+/).filter(w => /^[A-Za-zÀ-ÿ]/.test(w)).slice(0, 2).map(w => w[0]).join("") || "U").toUpperCase()}</span>
          </button>
          {menu && (
            <div style={{ position: "absolute", top: "calc(100% + 10px)", right: 0, width: 248, background: "var(--surface)", border: "1px solid var(--hairline-strong)", borderRadius: "var(--radius)", boxShadow: "0 16px 40px rgba(0,0,0,0.45)", padding: 6, zIndex: 80 }}>
              <div style={{ padding: "12px 14px 10px", borderBottom: "1px solid var(--hairline)", marginBottom: 6 }}>
                <div style={{ fontFamily: "var(--font-body)", fontSize: 14, fontWeight: 500, color: "var(--paper)" }}>{(user && user.nome) || "Usuário"}</div>
                {user && user.email && <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--muted-2)", marginTop: 3 }}>{user.email}</div>}
                <div style={{ display: "inline-flex", alignItems: "center", gap: 5, marginTop: 8, padding: "3px 9px", borderRadius: "var(--radius-pill)", background: "var(--fill-accent)", fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.06em", textTransform: "uppercase", color: user && user.role === "master" ? "var(--brass)" : "var(--muted)" }}>
                  <i data-lucide="shield" style={{ width: 11, height: 11, strokeWidth: 1.8 }}></i>{user && user.role === "master" ? "Master" : "Comum"}
                </div>
              </div>
              <div style={{ padding: "6px 14px 8px", fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.05em", textTransform: "uppercase", color: "var(--muted-2)" }}>Unidade ativa</div>
              <div style={{ padding: "0 14px 10px", fontFamily: "var(--font-body)", fontSize: 13, color: "var(--paper)" }}>{unit}</div>
              <button onClick={() => { setMenu(false); onLogout && onLogout(); }} style={{ width: "100%", display: "flex", alignItems: "center", gap: 9, padding: "10px 14px", background: "none", border: "none", borderTop: "1px solid var(--hairline)", cursor: "pointer", color: "var(--clay)", fontFamily: "var(--font-body)", fontSize: 13.5, borderRadius: 8 }}>
                <i data-lucide="log-out" style={{ width: 15, height: 15, strokeWidth: 1.8 }}></i>Sair
              </button>
            </div>
          )}
        </div>
      </div>
    </header>
  );
}

const iconBtn = {
  width: 40, height: 40, borderRadius: "50%", flexShrink: 0,
  background: "var(--surface)", border: "1px solid var(--hairline)",
  display: "inline-flex", alignItems: "center", justifyContent: "center", cursor: "pointer", color: "var(--muted)",
};
const iconGlyph = { width: 17, height: 17, strokeWidth: 1.6 };

window.TopBar = TopBar;
