/* chrome.jsx — Sidebar, XP widget, Streak, Stats, Topbar, Filters, Toasts. Exported to window. */

function XPWidget({ xp, justLeveled }) {
  const { Ic, Store } = window;
  const info = Store.levelInfo(xp);
  return (
    <div className={"xp" + (justLeveled ? " levelup" : "")}>
      <div className="xp-top">
        <div className="xp-level">
          <div className="xp-badge">{info.level}</div>
          <div>
            <b>Nível {info.level}</b>
            <span>Dev {info.level < 3 ? "Aprendiz" : info.level < 6 ? "Pleno" : info.level < 10 ? "Sênior" : "Lenda"}</span>
          </div>
        </div>
        <div className="xp-pts">{info.into}/{info.need} XP</div>
      </div>
      <div className="xp-track"><div className="xp-fill" style={{ width: info.pct + "%" }} /></div>
    </div>
  );
}

function StreakPill({ streak }) {
  return (
    <div className="streak-pill">
      <span className="streak-flame">🔥</span>
      <div>
        <b>{streak} {streak === 1 ? "dia" : "dias"}</b>
        <span>sequência</span>
      </div>
    </div>
  );
}

const NAV = [
  { id: "tarefas", label: "Tarefas", icon: "Tasks" },
];

function Sidebar({ game, justLeveled, user, onOpenSettings, onLogout, canAdmin, onOpenAdmin,
                   canApprove, pendingCount, onOpenApprovals }) {
  const { Ic } = window;
  const [active, setActive] = React.useState("tarefas");
  const [menu, setMenu] = React.useState(false);
  const ref = React.useRef(null);
  React.useEffect(() => {
    const h = (e) => { if (ref.current && !ref.current.contains(e.target)) setMenu(false); };
    document.addEventListener("mousedown", h); return () => document.removeEventListener("mousedown", h);
  }, []);
  const initials = (user.name || "U").trim().split(/\s+/).map(w => w[0]).slice(0, 2).join("").toUpperCase();

  return (
    <aside className="sidebar">
      <div className="brand">
        <img className="brand-logo" src="assets/logo.png" alt="Mil Grau RP" />
        <div className="brand-name">Mil Grau RP<span>Tarefas</span></div>
      </div>

      <nav className="nav">
        {NAV.map(n => {
          const I = Ic[n.icon];
          return (
            <button key={n.id} className={"nav-item" + (active === n.id ? " active" : "")}
              onClick={() => { setActive(n.id); window.FX.sfx.play("click"); }}
              aria-current={active === n.id ? "page" : undefined}>
              <I /> <span>{n.label}</span>
            </button>
          );
        })}
      </nav>

      <div className="side-stats">
        <XPWidget xp={game.xp} justLeveled={justLeveled} />
        <StreakPill streak={game.streak} />
      </div>

      <div className="profile" ref={ref}>
        {menu && (
          <div className="dropdown" role="menu">
            <button onClick={() => { setMenu(false); onOpenSettings("perfil"); }}><Ic.User /> Meu perfil</button>
            <button onClick={() => { setMenu(false); onOpenSettings("conta"); }}><Ic.Settings /> Configurações</button>
            {canApprove && (
              <button onClick={() => { setMenu(false); onOpenApprovals && onOpenApprovals(); }}>
                <Ic.Mail /> Solicitações de cadastro
                {pendingCount > 0 && <span className="pill-badge">{pendingCount}</span>}
              </button>
            )}
            {canAdmin && <button onClick={() => { setMenu(false); onOpenAdmin && onOpenAdmin(); }}><Ic.User /> Administração</button>}
            <button className="danger" onClick={onLogout}><Ic.Logout /> Sair</button>
          </div>
        )}
        <button className="profile-card" aria-expanded={menu} onClick={() => setMenu(m => !m)}>
          {user.avatar
            ? <img className="avatar" alt={user.name} src={user.avatar} />
            : <span className="avatar avatar-initials">{initials}</span>}
          <div className="profile-meta">
            <b>{user.name}</b>
            <span>{user.role}</span>
          </div>
          {canApprove && pendingCount > 0 && <span className="profile-dot" aria-label={pendingCount + ' pendente(s)'}>{pendingCount}</span>}
          <Ic.Chevron className="profile-chev" size={16} />
        </button>
      </div>
    </aside>
  );
}

function Topbar({ query, setQuery, onNew, muted, toggleMute }) {
  const { Ic } = window;
  return (
    <header className="topbar">
      <h1 className="page-title">Minhas Tarefas</h1>
      <div className="topbar-actions">
        <button className="btn-primary" onClick={onNew}><Ic.Plus size={18} /> Nova Tarefa</button>
        <div className="search">
          <Ic.Search />
          <input placeholder="Buscar tarefa..." value={query}
            onChange={e => setQuery(e.target.value)} aria-label="Buscar tarefa" />
          {query && <button className="clear" onClick={() => setQuery("")} aria-label="Limpar"><Ic.Close size={16} /></button>}
        </div>
        <button className={"icon-btn" + (muted ? "" : " on")} onClick={toggleMute}
          aria-label={muted ? "Ativar som" : "Silenciar"} title={muted ? "Ativar som" : "Silenciar"}>
          {muted ? <Ic.VolumeOff /> : <Ic.Volume />}
        </button>
      </div>
    </header>
  );
}

function StatBar({ game, totalTasks }) {
  const { Ic, Store } = window;
  const rate = totalTasks ? Math.round((game.totalDone / (totalTasks + game.totalDone)) * 100) : 0;
  const stats = [
    { ico: "Check", c: "var(--c-melhoria)", bg: "var(--c-melhoria-bg)", num: game.todayCount, lbl: "concluídas hoje" },
    { ico: "Calendar", c: "var(--accent)", bg: "rgba(var(--accent-rgb),0.14)", num: game.weekCount, lbl: "essa semana" },
    { ico: "Target", c: "var(--gold)", bg: "rgba(245,185,66,0.14)", num: rate + "%", lbl: "taxa de conclusão" },
    { ico: "Trophy", c: "var(--c-feature)", bg: "var(--c-feature-bg)", num: game.totalDone, lbl: "total concluídas" },
  ];
  return (
    <div className="statbar">
      {stats.map((s, i) => {
        const I = Ic[s.ico];
        return (
          <div className="stat" key={i}>
            <div className="stat-ico" style={{ background: s.bg, color: s.c }}><I size={20} /></div>
            <div>
              <div className="stat-num" data-stat={i}>{s.num}</div>
              <div className="stat-lbl">{s.lbl}</div>
            </div>
          </div>
        );
      })}
    </div>
  );
}

function Filters({ catFilter, setCatFilter, prioFilter, setPrioFilter }) {
  const { Store } = window;
  const cats = Object.entries(Store.CATEGORIES);
  const prios = Object.entries(Store.PRIORITIES);
  const toggle = (val, cur, set) => set(cur === val ? null : val);
  const any = catFilter || prioFilter;
  return (
    <div className="filters">
      <button className={"fchip fchip-todas" + (!any ? " on" : "")}
        onClick={() => { setCatFilter(null); setPrioFilter(null); }}>Todas</button>
      {cats.map(([k, m]) => (
        <button key={k} className={"fchip" + (catFilter === k ? " on" : "")}
          onClick={() => toggle(k, catFilter, setCatFilter)}
          style={catFilter === k ? { color: m.color, borderColor: m.color } : {}}>{m.label}</button>
      ))}
      <span style={{ width: 1, height: 18, background: "var(--border)" }} />
      {prios.map(([k, m]) => (
        <button key={k} className={"fchip" + (prioFilter === k ? " on" : "")}
          onClick={() => toggle(k, prioFilter, setPrioFilter)}
          style={prioFilter === k ? { color: m.color, borderColor: m.color } : {}}>{m.label}</button>
      ))}
      {any && <button className="fchip fchip-clear" onClick={() => { setCatFilter(null); setPrioFilter(null); }}>Limpar filtros ✕</button>}
    </div>
  );
}

function ToastHost({ toasts }) {
  return (
    <div className="toast-host" aria-live="polite">
      {toasts.map(t => (
        <div key={t.id} className={"toast" + (t.out ? " out" : "")}>
          <span className="emoji">{t.e}</span> {t.t}
        </div>
      ))}
    </div>
  );
}

/* MobileHero — logo grande de marca no topo do conteúdo (só no celular).
   Fica dentro da .main (rola com a página); o CSS a esconde no desktop. */
function MobileHero() {
  return (
    <div className="m-hero">
      <img className="m-hero-logo" src="assets/logo.png" alt="Mil Grau RP" />
      <div className="m-hero-name">MIL GRAU RP</div>
      <div className="m-hero-sub">TAREFAS</div>
    </div>
  );
}

/* MobileChrome — barra superior, FAB e barra inferior do celular.
   Renderizada sempre; o CSS a esconde no desktop (≥821px). */
function MobileChrome({ game, justLeveled, user, muted, toggleMute, onNew,
                        onOpenSettings, onLogout, canAdmin, onOpenAdmin,
                        canApprove, pendingCount, onOpenApprovals }) {
  const { Ic, FX } = window;
  const [drawer, setDrawer] = React.useState(false);
  const [sheet, setSheet] = React.useState(null); // "nivel" | "sequencia" | null
  const initials = (user.name || "U").trim().split(/\s+/).map(w => w[0]).slice(0, 2).join("").toUpperCase();

  return (
    <>
      <header className="m-topbar">
        <button className="m-icon" aria-label="Abrir menu"
          onClick={() => { setDrawer(true); FX.sfx.play("click"); }}>
          <Ic.Menu size={22} />
        </button>
        <button className={"m-icon" + (muted ? "" : " on")} onClick={toggleMute}
          aria-label={muted ? "Ativar som" : "Silenciar"}>
          {muted ? <Ic.VolumeOff size={20} /> : <Ic.Volume size={20} />}
        </button>
      </header>

      <button className="m-fab" onClick={onNew} aria-label="Nova tarefa"><Ic.Plus size={26} /></button>

      <nav className="m-bottomnav">
        <button className={"m-tab" + (sheet === null ? " on" : "")}
          onClick={() => { setSheet(null); const m = document.querySelector(".main"); if (m) m.scrollTo({ top: 0, behavior: "smooth" }); }}>
          <Ic.Tasks size={22} /><span>Tarefas</span>
        </button>
        <button className={"m-tab" + (sheet === "nivel" ? " on" : "")}
          onClick={() => { setSheet(s => s === "nivel" ? null : "nivel"); FX.sfx.play("click"); }}>
          <Ic.Trophy size={22} /><span>Nível</span>
        </button>
        <button className={"m-tab" + (sheet === "sequencia" ? " on" : "")}
          onClick={() => { setSheet(s => s === "sequencia" ? null : "sequencia"); FX.sfx.play("click"); }}>
          <Ic.Flame size={22} /><span>Sequência</span>
        </button>
      </nav>

      {drawer && (
        <div className="m-scrim" onClick={() => setDrawer(false)}>
          <aside className="m-drawer" onClick={e => e.stopPropagation()}>
            <div className="m-drawer-brand">
              <img src="assets/logo.png" alt="Mil Grau RP" />
              <div className="brand-name">Mil Grau RP<span>Tarefas</span></div>
            </div>
            <div className="m-drawer-user">
              {user.avatar
                ? <img className="avatar" src={user.avatar} alt="" />
                : <span className="avatar avatar-initials">{initials}</span>}
              <div className="profile-meta"><b>{user.name}</b><span>{user.role}</span></div>
            </div>
            <div className="m-drawer-stats">
              <XPWidget xp={game.xp} justLeveled={justLeveled} />
              <StreakPill streak={game.streak} />
            </div>
            <div className="m-drawer-menu">
              <button onClick={() => { setDrawer(false); onOpenSettings("perfil"); }}><Ic.User size={19} /> Meu perfil</button>
              <button onClick={() => { setDrawer(false); onOpenSettings("conta"); }}><Ic.Settings size={19} /> Configurações</button>
              {canApprove && (
                <button onClick={() => { setDrawer(false); onOpenApprovals && onOpenApprovals(); }}>
                  <Ic.Mail size={19} /> Solicitações
                  {pendingCount > 0 && <span className="pill-badge">{pendingCount}</span>}
                </button>
              )}
              {canAdmin && <button onClick={() => { setDrawer(false); onOpenAdmin && onOpenAdmin(); }}><Ic.User size={19} /> Administração</button>}
              <button className="danger" onClick={onLogout}><Ic.Logout size={19} /> Sair</button>
            </div>
          </aside>
        </div>
      )}

      {sheet && (
        <div className="m-scrim sheet" onClick={() => setSheet(null)}>
          <div className="m-sheet" onClick={e => e.stopPropagation()}>
            <div className="m-sheet-grip" />
            {sheet === "nivel" && (<>
              <h3><Ic.Trophy size={18} /> Seu nível</h3>
              <XPWidget xp={game.xp} justLeveled={justLeveled} />
              <p className="m-sheet-note">Conclua tarefas para ganhar XP e subir de nível.</p>
            </>)}
            {sheet === "sequencia" && (<>
              <h3><Ic.Flame size={18} /> Sua sequência</h3>
              <StreakPill streak={game.streak} />
              <p className="m-sheet-note">Volte todos os dias e conclua tarefas para manter sua ofensiva acesa.</p>
            </>)}
          </div>
        </div>
      )}
    </>
  );
}

Object.assign(window, { Sidebar, Topbar, StatBar, Filters, ToastHost, XPWidget, StreakPill, MobileChrome, MobileHero });
