// ═══════════════════════════════════════════════════════════════════
// App root — shell + navegação
// ═══════════════════════════════════════════════════════════════════

// Regras vigentes por período:
//   ≤ 1T/2026 → regras 2025 (NPS ≥ 4,5 · sem proposta_bonus)
//   ≥ 2T/2026 → regras 2026 (NPS ≥ 3,5 · com proposta_bonus R$100)
function regrasPara(trimestre, base) {
  const m = String(trimestre).match(/^(\d)T\/(\d{4})/);
  const ano = m ? +m[2] : 0, q = m ? +m[1] : 0;
  if (ano > 2026 || (ano === 2026 && q >= 2)) return base;
  const { proposta_bonus, ...varSem } = base.variavel || {};
  return {
    ...base,
    variavel: {
      ...varSem,
      fideliz_nps: { ...(varSem.fideliz_nps || {}), limiar: 4.5, label: 'NPS ≥ 4,5 — nota de satisfação' },
    },
  };
}

function App() {
  const [state, setStateRaw] = useState({
    trimestre: '1T/2026',
    vendedores: window.vendedoresSeed,
    regras: window.regrasSeed,
    leads: window.leadsSeed,
    historico: window.historicoSeed,
    avisos: window.avisosSeed,
    fechado: false,
    historicoPeriodos: window.historicoPeriodosSeed || [],
    dreRealizado: 0,
  });

  // ── Firebase Auth + sincronização em tempo real ──────────────────
  // fbPronto: false enquanto aguarda onAuthStateChanged; true após (com ou sem user)
  const [fbPronto,    setFbPronto]    = useState(!window.FIREBASE_AUTH);
  const [fbConectado, setFbConectado] = useState(false);
  const meuWid      = useRef(null);
  const timerSalvar = useRef(null);
  const fbRefLocal  = useRef(null);

  const conectarRTDB = () => {
    const ref = firebase.database().ref('escalab/estado');
    fbRefLocal.current = ref;
    window.FBREF = ref;
    ref.once('value', snap => {
      const d = snap.val();
      if (d) { const { _wid, ...r } = d; setStateRaw(p => ({ ...p, ...r })); }
      setFbPronto(true);
      setFbConectado(true);
    });
    ref.on('value', snap => {
      const d = snap.val();
      if (!d || d._wid === meuWid.current) return;
      const { _wid, ...r } = d;
      setStateRaw(p => ({ ...p, ...r }));
    });
  };

  const desconectarRTDB = () => {
    if (fbRefLocal.current) { fbRefLocal.current.off(); fbRefLocal.current = null; }
    window.FBREF = null;
    setFbConectado(false);
  };

  useEffect(() => {
    if (!window.FIREBASE_AUTH) { setFbPronto(true); return; }
    const timeout = setTimeout(() => setFbPronto(true), 6000);
    const unsub = window.FIREBASE_AUTH.onAuthStateChanged(user => {
      clearTimeout(timeout);
      if (user) { conectarRTDB(); }
      else      { desconectarRTDB(); setFbPronto(true); }
    });
    return () => { unsub(); desconectarRTDB(); clearTimeout(timeout); };
  }, []); // eslint-disable-line

  // Salva no Firebase 1s após qualquer mudança de estado (debounce)
  useEffect(() => {
    if (!fbPronto || !fbConectado || !window.FBREF) return;
    clearTimeout(timerSalvar.current);
    timerSalvar.current = setTimeout(() => {
      const wid = Date.now() + '_' + Math.random().toString(36).slice(2, 6);
      meuWid.current = wid;
      window.FBREF.set({
        trimestre:         state.trimestre,
        vendedores:        state.vendedores,
        regras:            state.regras,
        leads:             state.leads,
        historico:         state.historico,
        avisos:            state.avisos,
        fechado:           state.fechado,
        historicoPeriodos: state.historicoPeriodos,
        dreRealizado:      state.dreRealizado,
        _wid:              wid,
      }).catch(e => console.error('[Firebase] erro ao salvar:', e));
    }, 1000);
  }, [state, fbPronto, fbConectado]);
  // ─────────────────────────────────────────────────────────────────

  const [perfilId, setPerfilId] = useState(null);
  const [tela, setTela] = useState('dashboard');
  const [fecharOpen, setFecharOpen] = useState(false);
  const [vendedorModal, setVendedorModal] = useState({ open: false, vendedor: null });

  const perfil = state.vendedores.find(v => v.id === perfilId);
  const isMaria = perfil?.papel === 'Diretora' || perfil?.papel === 'Diretor';

  const { isMobile } = useMobile();
  const [sidebarAberta, setSidebarAberta] = useState(false);
  const [trimestreView, setTrimestreView] = useState(state.trimestre);

  const parseQ = (t) => { const m = String(t).match(/(\d)T\/(\d{4})/); return m ? {q:+m[1],year:+m[2]} : null; };
  const parseAno = (t) => { const m = String(t).match(/^(\d{4})/); return m ? +m[1] : null; };
  const prevQ = (t) => { const p = parseQ(t); if(!p) return t; return p.q===1 ? `4T/${p.year-1}` : `${p.q-1}T/${p.year}`; };
  const nextQ = (t) => { const p = parseQ(t); if(!p) { const a = parseAno(t); return a ? `1T/${a+1}` : t; } return p.q===4 ? `1T/${p.year+1}` : `${p.q+1}T/${p.year}`; };

  // Índice de todos os períodos históricos por chave de busca (suporta ano '2025' e trimestre '1T/2026')
  const periodosPorChave = {};
  (state.historicoPeriodos||[]).forEach(p => {
    const key = p.periodo || p.label;
    periodosPorChave[key] = p;
    // indexar também pelo ano (ex: '2025') e por trimestres ficticios
    const ano = parseAno(key);
    if (ano && !parseQ(key)) periodosPorChave[String(ano)] = p;
  });

  // Navegar "prev": se trimestre anterior não existe como período, verifica se há período anual para aquele ano
  const prevTrim = (t) => {
    const q = prevQ(t);
    if (periodosPorChave[q]) return q;
    const p = parseQ(q);
    if (p && periodosPorChave[String(p.year)]) return String(p.year);
    return q;
  };
  const nextTrim = (t) => nextQ(t);

  const canPrev = !!periodosPorChave[prevTrim(trimestreView)];
  const canNext = (() => {
    const curr = parseQ(state.trimestre);
    const view = parseQ(trimestreView) || { year: parseAno(trimestreView) || 0, q: 4 };
    return view.year < (curr?.year || 9999) || (view.year === curr?.year && view.q < (curr?.q || 4));
  })();

  const periodoHistorico = periodosPorChave[trimestreView];

  // Leads históricos normalizados (adiciona campos ausentes nos dados 2025)
  const leadsHistNorm = (periodoHistorico?.leads || []).map(l => ({
    cliente: '', data: '2025-01-01', vendido: !!l.comissiona, valor: 0, markup: 0,
    setor: 'pd', participacoes: [], justificativa: '',
    status: l.proposta === 'nao' ? 'perdido' : (l.comissiona ? 'fechado' : l.proposta === 'aprovada' ? 'negociacao' : 'qualificado'),
    ...l,
  }));

  const stateEfetivo = periodoHistorico ? {
    ...state, trimestre: trimestreView, regras: regrasPara(trimestreView, state.regras),
    leads: leadsHistNorm, fechado: true, modoHistorico: true, periodoHistorico,
  } : trimestreView !== state.trimestre ? {
    ...state, trimestre: trimestreView, regras: regrasPara(trimestreView, state.regras),
    leads: [], fechado: false, modoFuturo: true,
  } : { ...state, regras: regrasPara(state.trimestre, state.regras) };

  useEffect(() => {
    if (!perfilId) return;
    if (!isMaria && tela !== 'extrato' && tela !== 'avisos') setTela('extrato');
    if (isMaria && tela === 'extrato') setTela('dashboard');
  }, [isMaria, perfilId]);

  const sair = () => {
    setPerfilId(null);
    setTela('dashboard');
    if (window.FIREBASE_AUTH) window.FIREBASE_AUTH.signOut().catch(() => {});
  };

  const salvarVendedor = (v) => {
    setStateRaw(s => {
      const exists = s.vendedores.find(x => x.id === v.id);
      const novo = exists
        ? s.vendedores.map(x => x.id === v.id ? v : x)
        : [...s.vendedores, { ...v, id: 'v' + (s.vendedores.length + 1) }];
      return { ...s, vendedores: novo };
    });
    setVendedorModal({ open: false, vendedor: null });
  };

  const excluirVendedor = (id) => {
    setStateRaw(s => ({ ...s, vendedores: s.vendedores.map(v => v.id === id ? { ...v, ativo: false } : v) }));
    setVendedorModal({ open: false, vendedor: null });
  };

  if (!fbPronto) return (
    <div style={{ minHeight:'100vh', display:'flex', alignItems:'center', justifyContent:'center', flexDirection:'column', gap:18, background:'var(--escalab-paper)' }}>
      <div style={{ width:44, height:44, border:'3px solid var(--escalab-brand)', borderTopColor:'transparent', borderRadius:'50%', animation:'spin .8s linear infinite' }} />
      <div style={{ fontSize:14, color:'var(--escalab-slate)', fontWeight:500 }}>Conectando ao servidor…</div>
    </div>
  );

  if (!perfilId) {
    return <LoginScreen vendedores={state.vendedores} onLogin={(id) => setPerfilId(id)} />;
  }

  const navMaria = [
    { id: 'dashboard', label: 'Painel',     icon: 'chart'   },
    { id: 'leads',     label: 'Leads',      icon: 'leads'   },
    { id: 'regras',    label: 'Regras',     icon: 'rules'   },
    { id: 'historico', label: 'Histórico',  icon: 'history' },
    { id: 'avisos',    label: 'Avisos',     icon: 'mail'    },
  ];
  const navVendedor = [
    { id: 'extrato', label: 'Meu extrato', icon: 'user' },
    { id: 'avisos',  label: 'Avisos',      icon: 'mail' },
  ];
  const nav = isMaria ? navMaria : navVendedor;

  const setState = {
    openFechar:    setFecharOpen,
    setLeads:      (leads)     => setStateRaw(s => ({ ...s, leads })),
    setRegras:     (regras)    => setStateRaw(s => ({ ...s, regras })),
    setVendedores: (vendedores)=> setStateRaw(s => ({ ...s, vendedores })),
    setAvisos:     (avisos)    => setStateRaw(s => ({ ...s, avisos })),
    setDreRealizado: (v)       => setStateRaw(s => ({ ...s, dreRealizado: v })),
    addHistorico:  (entry)     => setStateRaw(s => ({ ...s, historico: [entry, ...s.historico] })),
    abrirVendedor:     (vendedor) => setVendedorModal({ open: true, vendedor }),
    abrirNovoVendedor: ()         => setVendedorModal({ open: true, vendedor: null }),
  };

  const avisosNaoLidos = state.avisos.length;

  return (
    <div style={{ minHeight: '100vh', background: 'var(--escalab-paper)', display: 'flex' }}>
      {/* Sidebar */}
      <aside style={{
        width: 260, background: 'var(--escalab-ink)', color: '#fff', padding: '26px 20px',
        display: (!isMobile || sidebarAberta) ? 'flex' : 'none',
        flexDirection: 'column', gap: 28,
        position: isMobile ? 'fixed' : 'sticky',
        top: 0, left: 0, height: '100vh', zIndex: isMobile ? 200 : 'auto',
        overflowY: 'auto',
      }}>
        {/* Logo */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '0 6px' }}>
          <div style={{ color: 'var(--escalab-brand-accent)' }}><Dot /></div>
          <div>
            <div style={{ fontSize: 17, fontWeight: 700, letterSpacing: '-.01em' }}>Escalab</div>
            <div style={{ fontSize: 10.5, fontWeight: 500, letterSpacing: '.14em', textTransform: 'uppercase', color: 'rgba(255,255,255,.5)' }}>Comissionamento</div>
          </div>
        </div>
        {isMobile && (
          <button onClick={() => setSidebarAberta(false)}
            style={{ position: 'absolute', top: 14, right: 14, border: 0, background: 'rgba(255,255,255,.15)', borderRadius: 8, cursor: 'pointer', padding: '6px 10px', color: '#fff', fontSize: 18, lineHeight: 1 }}>✕</button>
        )}

        {/* Nav */}
        <div>
          <div style={{ fontSize: 10, fontWeight: 600, letterSpacing: '.14em', textTransform: 'uppercase', color: 'rgba(255,255,255,.4)', padding: '0 10px 10px' }}>
            {isMaria ? 'Diretoria' : 'Área do vendedor'}
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
            {nav.map(item => (
              <button key={item.id} onClick={() => setTela(item.id)}
                style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 12px', border: 0,
                  background: tela === item.id ? 'rgba(94,233,196,.12)' : 'transparent',
                  color: tela === item.id ? 'var(--escalab-brand-accent)' : 'rgba(255,255,255,.78)',
                  borderRadius: 8, fontFamily: 'inherit', fontSize: 13.5, fontWeight: 500,
                  letterSpacing: '-.005em', cursor: 'pointer', textAlign: 'left', transition: 'all .15s',
                  width: '100%' }}>
                <Icon name={item.icon} size={17} />
                <span style={{ flex: 1 }}>{item.label}</span>
                {item.id === 'avisos' && avisosNaoLidos > 0 && (
                  <span style={{ fontSize: 10, fontWeight: 700, background: 'var(--escalab-brand-accent)', color: '#00382E', borderRadius: 999, padding: '2px 6px', lineHeight: 1.4 }}>
                    {avisosNaoLidos}
                  </span>
                )}
              </button>
            ))}
          </div>
        </div>

        {/* Perfil atual — sem troca livre, só sair */}
        <div style={{ marginTop: 'auto' }}>
          <div style={{ fontSize: 10, fontWeight: 600, letterSpacing: '.14em', textTransform: 'uppercase', color: 'rgba(255,255,255,.4)', padding: '0 10px 10px' }}>Minha conta</div>
          <div style={{ padding: 10, background: 'rgba(255,255,255,.04)', border: '1px solid rgba(255,255,255,.08)', borderRadius: 10 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
              <Avatar v={perfil} size={32} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13, fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{perfil.nome}</div>
                <div style={{ fontSize: 11, color: 'rgba(255,255,255,.6)' }}>{perfil.papel} · {isMaria ? 'Admin' : 'Visualizador'}</div>
              </div>
            </div>
            <button onClick={sair}
              style={{ width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, padding: '9px 12px', border: '1px solid rgba(255,255,255,.15)', borderRadius: 8, background: 'transparent', color: 'rgba(255,255,255,.75)', fontFamily: 'inherit', fontSize: 13, fontWeight: 500, cursor: 'pointer', transition: 'all .15s' }}>
              <Icon name="close" size={14} />
              Sair da conta
            </button>
          </div>
        </div>
      </aside>

      {/* Main */}
      <main style={{ flex: 1, padding: isMobile ? '20px 16px 60px' : '36px 44px 80px', maxWidth: 1320, minWidth: 0 }}>
        {/* Top bar */}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 32, paddingBottom: 18, borderBottom: '1px solid var(--escalab-line)' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
            {isMaria ? (
              <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
                <button onClick={() => setTrimestreView(prevTrim(trimestreView))} disabled={!canPrev}
                  style={{ border: '1px solid var(--escalab-line)', borderRadius: 6, background: '#fff', cursor: canPrev ? 'pointer' : 'default', padding: '4px 10px', fontSize: 16, color: canPrev ? 'var(--escalab-ink)' : 'var(--escalab-line)', lineHeight: 1 }}>‹</button>
                <Tag tone={trimestreView === state.trimestre ? 'brand' : 'outline'}>{trimestreView}</Tag>
                <button onClick={() => setTrimestreView(nextTrim(trimestreView))} disabled={!canNext}
                  style={{ border: '1px solid var(--escalab-line)', borderRadius: 6, background: '#fff', cursor: canNext ? 'pointer' : 'default', padding: '4px 10px', fontSize: 16, color: canNext ? 'var(--escalab-ink)' : 'var(--escalab-line)', lineHeight: 1 }}>›</button>
              </div>
            ) : <Tag tone="brand">{state.trimestre}</Tag>}
            <span style={{ fontSize: 13, color: 'var(--escalab-slate)' }}>{stateEfetivo.fechado ? 'Fechado' : 'Trimestre aberto'}</span>
            <span style={{ width: 1, height: 14, background: 'var(--escalab-line)' }} />
            <span style={{ fontSize: 13, color: 'var(--escalab-mute)' }}>{stateEfetivo.leads.length} leads · {stateEfetivo.vendedores.filter(v => v.ativo).length} vendedores ativos</span>
          </div>
          <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
            {isMobile && (
              <button onClick={() => setSidebarAberta(s => !s)}
                style={{ border: '1px solid var(--escalab-line)', borderRadius: 8, background: '#fff', cursor: 'pointer', padding: '8px 10px', display: 'flex', flexDirection: 'column', gap: 4 }}>
                <span style={{ width: 16, height: 2, background: 'var(--escalab-ink)', display: 'block', borderRadius: 1 }} />
                <span style={{ width: 16, height: 2, background: 'var(--escalab-ink)', display: 'block', borderRadius: 1 }} />
                <span style={{ width: 16, height: 2, background: 'var(--escalab-ink)', display: 'block', borderRadius: 1 }} />
              </button>
            )}
            <button onClick={() => setTela('avisos')}
              style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '7px 14px', border: '1px solid transparent', borderRadius: 8, background: tela === 'avisos' ? 'var(--escalab-brand-tint)' : 'transparent', color: tela === 'avisos' ? 'var(--escalab-brand-deep)' : 'var(--escalab-slate)', fontFamily: 'inherit', fontSize: 13, fontWeight: 500, cursor: 'pointer', position: 'relative' }}>
              <Icon name="mail" size={14} />
              <span>Avisos</span>
              {avisosNaoLidos > 0 && (
                <span style={{ position: 'absolute', top: 4, right: 6, width: 7, height: 7, background: 'var(--escalab-brand)', borderRadius: '50%' }} />
              )}
            </button>
            <Button variant="ghost" size="sm" icon="close" onClick={sair}>Sair</Button>
          </div>
        </div>

        {stateEfetivo.modoHistorico && (
          <div style={{ marginBottom: 16, padding: '10px 16px', background: '#fef3c7', border: '1px solid #f59e0b', borderRadius: 8, fontSize: 13, color: '#92400e' }}>
            Visualizando período fechado: <strong>{stateEfetivo.trimestre}</strong>. Dados somente leitura.
            <button onClick={() => setTrimestreView(state.trimestre)} style={{ marginLeft: 12, border: 'none', background: 'transparent', color: '#92400e', cursor: 'pointer', textDecoration: 'underline', fontSize: 13 }}>Voltar ao atual</button>
          </div>
        )}
        {stateEfetivo.modoFuturo && (
          <div style={{ marginBottom: 16, padding: '10px 16px', background: '#eff6ff', border: '1px solid #3b82f6', borderRadius: 8, fontSize: 13, color: '#1d4ed8' }}>
            Período futuro: <strong>{stateEfetivo.trimestre}</strong> — nenhum dado cadastrado ainda.
            <button onClick={() => setTrimestreView(state.trimestre)} style={{ marginLeft: 12, border: 'none', background: 'transparent', color: '#1d4ed8', cursor: 'pointer', textDecoration: 'underline', fontSize: 13 }}>Voltar ao atual</button>
          </div>
        )}

        {tela === 'dashboard' && <PainelDiretoria state={stateEfetivo} setState={setState} />}
        {tela === 'leads'     && <LeadsScreen state={stateEfetivo} setState={setState} perfilId={perfilId} />}
        {tela === 'regras'    && <PainelRegras state={state} setState={setState} />}
        {tela === 'historico' && <HistoricoScreen state={state} />}
        {tela === 'extrato'   && <ExtratoVendedor state={state} vendedorId={perfilId} setState={setState} />}
        {tela === 'avisos'    && <AvisosScreen state={state} setState={setState} isMaria={isMaria} autorNome={perfil.nome} />}
      </main>

      <FecharTrimestreModal state={state} open={fecharOpen} onClose={() => setFecharOpen(false)}
        onConfirm={() => {
          setStateRaw(s => {
            const porV = calcularComissoes(s.leads, regrasPara(s.trimestre, s.regras), s.vendedores);
            const totalFaturado = s.leads.filter(l => l.vendido && l.comissiona).reduce((a, l) => a + l.valor, 0);
            const totalVariavel = Object.values(porV).reduce((a, v) => a + v.variavel + v.evento, 0);
            const totalFixa = Object.values(porV).reduce((a, v) => a + v.fixaSetor, 0);
            const periodo = {
              id: 'p_' + s.trimestre.replace('/', '_'),
              label: s.trimestre,
              periodo: s.trimestre,
              fechado: true,
              totalFaturado, totalVariavel, totalFixa,
              totalGeral: totalVariavel + totalFixa,
              porVendedor: s.vendedores.filter(v => v.ativo && (porV[v.id]?.total || 0) > 0).map(v => ({
                id: v.id, nome: v.nome,
                fixa: porV[v.id]?.fixaSetor || 0,
                variavel: (porV[v.id]?.variavel || 0) + (porV[v.id]?.evento || 0),
                total: porV[v.id]?.total || 0,
              })),
              leads: s.leads,
            };
            // Leads que ainda estão em aberto (não vendidos, não perdidos) seguem para o próximo trimestre
            const pendentes = s.leads.filter(l => !l.vendido && l.status !== 'perdido');
            const novoTrim = nextQ(s.trimestre);
            return {
              ...s,
              fechado: false,
              trimestre: novoTrim,
              leads: pendentes,
              historicoPeriodos: [periodo, ...s.historicoPeriodos],
            };
          });
          // Sincroniza a visualização com o novo trimestre aberto
          setTrimestreView(nextQ(state.trimestre));
          setFecharOpen(false);
        }} />
      <VendedorModal open={vendedorModal.open} vendedor={vendedorModal.vendedor}
        onClose={() => setVendedorModal({ open: false, vendedor: null })}
        onSave={salvarVendedor} onDelete={excluirVendedor} />
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
