/* global React, BezaLogo, Icon, Pill, Card, Delta, Infotip, fmt,
   GESTAO_PASSWORD, GESTAO_PERIOD,
   REVENUE_HISTORY, CONTRACTS, COST_STRUCTURE,
   TEAM_ALLOCATION, CLIENT_HEALTH, PROPOSALS,
   ALERTS, GOALS, DAILY_CALENDAR,
   STAGE_META, PAYMENT_STATUS_META, BURNOUT_META, TREND_META, RISK_META,
   TEAM, LineChart */
const { useState: useStateGes, useEffect: useEffectGes, useMemo: useMemoGes, useRef: useRefGes } = React;

/* ============================================================
   GESTÃO APP · root com gate de senha
   ============================================================ */
const GESTAO_AUTH_KEY = 'beza_gestao_auth_v1';

function GestaoApp() {
  const [authed, setAuthed] = useStateGes(() => sessionStorage.getItem(GESTAO_AUTH_KEY) === 'ok');
  const [section, setSection] = useStateGes('overview');

  if (!authed) {
    return <GestaoLogin onAuth={() => { sessionStorage.setItem(GESTAO_AUTH_KEY, 'ok'); setAuthed(true); }} />;
  }

  return (
    <div style={{ padding: 'var(--space-6) 0 0' }}>
      <GestaoHeader onLogout={() => { sessionStorage.removeItem(GESTAO_AUTH_KEY); setAuthed(false); }} />
      <GestaoNav section={section} setSection={setSection} />
      <div style={{ marginTop: 'var(--space-5)' }}>
        {section === 'overview'    && <SectionOverview />}
        {section === 'pulse'       && <SectionTeamPulse />}
        {section === 'alertas'     && <SectionAlertas />}
        {section === 'inbox'       && <SectionInbox />}
        {section === 'allhands'    && <SectionAllHands />}
        {section === 'transcript'  && <SectionTranscriptions />}
        {section === 'financeiro'  && <SectionFinanceiro />}
        {section === 'custos'      && <SectionCustos />}
        {section === 'time'        && <SectionTime />}
        {section === 'clientes'    && <SectionClientes />}
        {section === 'comparativos'&& <SectionComparativos />}
        {section === 'propostas'   && <SectionPropostasV2 />}
        {section === 'onboarding'  && <SectionOnboarding />}
        {section === 'calendario'  && <SectionCalendario />}
      </div>
    </div>
  );
}

/* ============================================================
   LOGIN GATE
   ============================================================ */
function GestaoLogin({ onAuth }) {
  const [pwd, setPwd] = useStateGes('');
  const [error, setError] = useStateGes(false);
  const submit = (e) => {
    e.preventDefault();
    if (pwd === GESTAO_PASSWORD) onAuth();
    else { setError(true); setTimeout(() => setError(false), 1500); }
  };
  return (
    <div style={{
      padding: 'var(--space-7) var(--space-5)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      minHeight: '60vh',
    }}>
      <div style={{
        width: '100%', maxWidth: 460,
        padding: 'var(--space-6)',
        background: 'linear-gradient(135deg, rgba(154,155,229,0.10), rgba(154,155,229,0.02))',
        border: '1px solid rgba(154,155,229,0.30)',
        borderRadius: 'var(--r-card-lg)',
        position: 'relative', overflow: 'hidden',
      }}>
        <div aria-hidden="true" style={{
          position: 'absolute', top: '-30%', right: '-10%',
          width: 400, height: 400, borderRadius: '50%',
          background: 'radial-gradient(circle, rgba(154,155,229,0.22), transparent 60%)',
          filter: 'blur(40px)', pointerEvents: 'none',
        }} />
        <div style={{ position: 'relative' }}>
          <div style={{
            width: 56, height: 56, borderRadius: '50%',
            background: 'var(--accent-soft)', color: 'var(--accent)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            marginBottom: 20, fontSize: 26,
          }}>🔒</div>
          <div className="t-overline" style={{ color: 'var(--accent)', marginBottom: 10 }}>
            Acesso restrito · gestão
          </div>
          <h2 className="t-h2" style={{ margin: '0 0 14px', color: 'var(--text)' }}>
            <span className="t-light">Essa área é </span>
            <span className="punch">restrita</span>
            <span className="t-light">.</span>
          </h2>
          <p style={{ margin: '0 0 28px', fontSize: 14, color: 'var(--text-muted)', lineHeight: 1.6 }}>
            Financeiro, custos, margens e visão consolidada do time. O acesso ficará lembrado durante esta sessão do navegador.
          </p>

          <form onSubmit={submit}>
            <label className="t-overline" style={{ color: 'var(--text-faint)', display: 'block', marginBottom: 8 }}>
              Senha
            </label>
            <input
              type="password"
              value={pwd}
              onChange={(e) => setPwd(e.target.value)}
              autoFocus
              placeholder="••••••••"
              style={{
                width: '100%', appearance: 'none',
                border: '1px solid', borderColor: error ? 'var(--error)' : 'var(--border-strong)',
                background: 'var(--surface-strong)', color: 'var(--text)',
                padding: '12px 14px', fontSize: 15,
                borderRadius: 'var(--r-btn)',
                fontFamily: 'inherit', outline: 'none',
                marginBottom: 14,
                animation: error ? 'shake 0.4s' : 'none',
              }}
            />
            <button type="submit" style={{
              width: '100%', appearance: 'none',
              border: '1px solid var(--accent)',
              background: 'var(--accent)', color: '#fff',
              padding: '12px 16px', borderRadius: 'var(--r-btn)',
              fontSize: 14, fontWeight: 500, fontFamily: 'inherit',
              cursor: 'pointer',
            }}>
              Entrar
            </button>
            {error && (
              <div style={{ marginTop: 10, fontSize: 12, color: 'var(--error)', textAlign: 'center' }}>
                Senha incorreta.
              </div>
            )}
          </form>

          <div style={{
            marginTop: 28, paddingTop: 20,
            borderTop: '1px solid var(--border)',
            fontSize: 11, color: 'var(--text-faint)', lineHeight: 1.5, textAlign: 'center',
          }}>
            Este é um gate visual. Quando a Beza migrar para infraestrutura própria, vira autenticação real com 2FA.
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { GestaoApp, GestaoLogin });
