// PAC Sistema — App principal com autenticação real

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "kanbanLayout": "cards",
  "aiPanel": "fixed"
}/*EDITMODE-END*/;

// ============================================================
// Tela de Login
// ============================================================
const LoginScreen = ({ onLogin }) => {
  const [email, setEmail] = React.useState('');
  const [password, setPassword] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState('');

  const handleLogin = async (e) => {
    e?.preventDefault();
    if (!email || !password) return;
    setLoading(true);
    setError('');
    try {
      const user = await window.PACApi.auth.login(email, password);
      onLogin(user);
    } catch (err) {
      setError(err.message || 'Credenciais inválidas.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="login-layout" style={{
      minHeight: '100vh',
      display: 'grid',
      gridTemplateColumns: '1fr 1fr',
    }}>
      {/* Coluna esquerda — identidade visual */}
      <div className="login-brand" style={{
        background: '#0D0D6B',
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'center',
        padding: '60px 48px',
        position: 'relative',
        overflow: 'hidden',
      }}>
        {/* Círculos decorativos de fundo */}
        <div style={{ position: 'absolute', width: 500, height: 500, borderRadius: '50%', border: '1px solid rgba(255,255,255,.05)', top: -120, left: -120 }} />
        <div style={{ position: 'absolute', width: 350, height: 350, borderRadius: '50%', border: '1px solid rgba(255,255,255,.05)', bottom: -80, right: -80 }} />

        <div style={{ position: 'relative', zIndex: 1, textAlign: 'center', maxWidth: 360 }}>
          {/* Logo */}
          <img
            src="assets/logo_offwhite.png"
            alt="PAC Advogados"
            style={{ height: 52, marginBottom: 40, opacity: 0.95 }}
          />

          {/* Divisor neon */}
          <div style={{ width: 48, height: 3, background: '#C8F135', borderRadius: 2, margin: '0 auto 32px' }} />

          <h2 style={{
            color: '#ffffff',
            fontSize: 22,
            fontWeight: 700,
            lineHeight: 1.35,
            marginBottom: 16,
            fontFamily: 'Georgia, serif',
          }}>
            Gestão jurídica integrada para o escritório moderno
          </h2>
          <p style={{ color: 'rgba(255,255,255,.45)', fontSize: 13, lineHeight: 1.7 }}>
            Casos, tarefas, agenda e documentos em um único lugar — seguro e acessível de qualquer dispositivo.
          </p>

          <div style={{ marginTop: 48, display: 'flex', flexDirection: 'column', gap: 12 }}>
            {['Kanban de tarefas com cronômetro', 'IA integrada para análise de casos', 'Calendário com Google Calendar'].map(item => (
              <div key={item} style={{ display: 'flex', alignItems: 'center', gap: 10, color: 'rgba(255,255,255,.6)', fontSize: 12.5 }}>
                <div style={{ width: 6, height: 6, borderRadius: '50%', background: '#C8F135', flexShrink: 0 }} />
                {item}
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Coluna direita — formulário */}
      <div className="login-form" style={{
        background: '#f7f7fb',
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'center',
        padding: '60px 48px',
      }}>
        <div style={{ width: '100%', maxWidth: 360 }}>
          <div style={{ marginBottom: 36 }}>
            <h1 style={{ fontSize: 24, fontWeight: 800, color: '#0D0D6B', marginBottom: 6, fontFamily: 'Georgia, serif' }}>
              Entrar
            </h1>
            <p style={{ fontSize: 13, color: '#888', margin: 0 }}>
              Acesso restrito à equipe PAC Advogados
            </p>
          </div>

          <form onSubmit={handleLogin} style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            <div>
              <label style={{
                display: 'block', marginBottom: 6,
                fontSize: 11, fontWeight: 700, textTransform: 'uppercase',
                letterSpacing: '.08em', color: '#555',
              }}>E-mail</label>
              <input
                type="email"
                value={email}
                onChange={e => setEmail(e.target.value)}
                placeholder="fernando@pacadvogados.com.br"
                autoFocus
                style={{
                  width: '100%', boxSizing: 'border-box',
                  padding: '11px 14px',
                  background: '#ffffff',
                  border: '1.5px solid #ddd',
                  borderRadius: 8,
                  fontSize: 13.5, color: '#1a1a2e',
                  outline: 'none',
                  transition: 'border-color .15s',
                }}
                onFocus={e => e.target.style.borderColor = '#0D0D6B'}
                onBlur={e => e.target.style.borderColor = '#ddd'}
              />
            </div>

            <div>
              <label style={{
                display: 'block', marginBottom: 6,
                fontSize: 11, fontWeight: 700, textTransform: 'uppercase',
                letterSpacing: '.08em', color: '#555',
              }}>Senha</label>
              <input
                type="password"
                value={password}
                onChange={e => setPassword(e.target.value)}
                placeholder="••••••••••••"
                style={{
                  width: '100%', boxSizing: 'border-box',
                  padding: '11px 14px',
                  background: '#ffffff',
                  border: '1.5px solid #ddd',
                  borderRadius: 8,
                  fontSize: 13.5, color: '#1a1a2e',
                  outline: 'none',
                  transition: 'border-color .15s',
                }}
                onFocus={e => e.target.style.borderColor = '#0D0D6B'}
                onBlur={e => e.target.style.borderColor = '#ddd'}
              />
            </div>

            {error && (
              <div style={{
                padding: '10px 14px', borderRadius: 6, fontSize: 12.5,
                background: 'rgba(194,37,62,.07)', border: '1px solid rgba(194,37,62,.2)',
                color: '#C2253E',
              }}>
                {error}
              </div>
            )}

            <button
              type="submit"
              disabled={loading}
              style={{
                marginTop: 4,
                padding: '13px',
                background: loading ? '#555' : '#0D0D6B',
                color: '#ffffff',
                border: 'none',
                borderRadius: 8,
                fontWeight: 700,
                fontSize: 14,
                cursor: loading ? 'not-allowed' : 'pointer',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                gap: 8,
                transition: 'background .15s',
                letterSpacing: '.01em',
              }}
            >
              {loading
                ? <><span className="spinner" style={{ width: 14, height: 14, borderColor: 'rgba(255,255,255,.2)', borderTopColor: '#fff' }} /> Entrando…</>
                : 'Entrar na plataforma'}
            </button>
          </form>

          <div style={{ marginTop: 32, paddingTop: 24, borderTop: '1px solid #e8e8f0', textAlign: 'center', fontSize: 11.5, color: '#aaa' }}>
            PAC Sistema · Peracini, Alves & Cottas Advogados
          </div>
        </div>
      </div>
    </div>
  );
};

// ============================================================
// App principal
// ============================================================
const App = () => {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [view, setView] = React.useState('dash');
  const [cmdOpen, setCmdOpen] = React.useState(false);
  const [uploadOpen, setUploadOpen] = React.useState(false);
  const [notifOpen, setNotifOpen] = React.useState(false);
  const [menuOpen, setMenuOpen] = React.useState(false);
  const [currentUser, setCurrentUser] = React.useState(null);
  const [authLoading, setAuthLoading] = React.useState(true);

  const [counts, setCounts] = React.useState({ tasks: 0, clients: 0, cases: 0, publicacoes: 0 });

  // Verificar sessão ao carregar
  React.useEffect(() => {
    window.PACApi.auth.me()
      .then(user => { setCurrentUser(user); })
      .catch(() => setCurrentUser(null))
      .finally(() => setAuthLoading(false));
  }, []);

  // Buscar contadores reais após autenticação
  React.useEffect(() => {
    if (!currentUser) return;
    const load = async () => {
      try {
        const [tasks, clients, cases, pubStats] = await Promise.all([
          window.PACApi.tasks.list().catch(() => []),
          window.PACApi.clients.list().catch(() => []),
          window.PACApi.cases.list().catch(() => []),
          window.PACApi.publicacoes.stats().catch(() => ({ nova: 0 })),
        ]);
        setCounts({
          tasks: tasks.filter(t => t.kanban_column !== 'concluido').length,
          clients: clients.length,
          cases: cases.length,
          publicacoes: (pubStats.nova || 0) + (pubStats.sem_vinculo || 0),
        });
      } catch (e) {
        // silencioso — counts ficam em zero se API falhar
      }
    };
    load();
  }, [currentUser]);

  // ⌘K / Ctrl+K
  React.useEffect(() => {
    const onKey = (e) => {
      const isCmd = e.metaKey || e.ctrlKey;
      if (isCmd && (e.key === 'k' || e.key === 'K')) {
        e.preventDefault();
        setCmdOpen(true);
      }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, []);

  // close notif on outside click
  React.useEffect(() => {
    if (!notifOpen) return;
    const onClick = () => setNotifOpen(false);
    window.addEventListener('click', onClick);
    return () => window.removeEventListener('click', onClick);
  }, [notifOpen]);

  const onJump = (target, item) => {
    if (target === '__upload') { setUploadOpen(true); return; }
    if (target === '__ai') { setView('ai'); return; }
    if (target) setView(target);
  };

  // Loading inicial
  if (authLoading) return (
    <div style={{ minHeight: '100vh', background: 'var(--pac-dark-purple)', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 12, color: 'rgba(255,255,255,.4)', fontSize: 13 }}>
      <div className="spinner" style={{ borderColor: 'rgba(255,255,255,.1)', borderTopColor: 'var(--pac-neon)' }} />
      Carregando PAC Sistema…
    </div>
  );

  // Não autenticado
  if (!currentUser) return <LoginScreen onLogin={user => setCurrentUser(user)} />;

  return (
    <div className="app">
      <Sidebar
        view={view}
        onView={(v) => { setView(v); setMenuOpen(false); }}
        counts={counts}
        user={currentUser}
        open={menuOpen}
        onClose={() => setMenuOpen(false)}
      />
      <div className="main">
        <Topbar
          view={view}
          onOpenCmd={() => setCmdOpen(true)}
          onOpenUpload={() => setUploadOpen(true)}
          onOpenNotif={(e) => { e?.stopPropagation?.(); setNotifOpen(v => !v); }}
          notifOpen={notifOpen}
          notifCount={0}
          user={currentUser}
          onLogout={() => window.PACApi.auth.logout()}
          onMenuOpen={() => setMenuOpen(v => !v)}
        />
        <main className="view">
          {view === 'dash' && <Dashboard user={currentUser} />}
          {view === 'tasks' && <Tasks layout={t.kanbanLayout} currentUser={currentUser} />}
          {view === 'clients' && <Clients />}
          {view === 'cases' && <Cases aiPanel={t.aiPanel} />}
          {view === 'calendar' && <Calendar currentUser={currentUser} />}
          {view === 'team' && <Team currentUser={currentUser} />}
          {view === 'reports' && <Reports />}
          {view === 'publicacoes' && <Publicacoes />}
          {view === 'upload' && (() => { setUploadOpen(true); setView('dash'); return null; })()}
          {view === 'ai' && <AIAssistant user={currentUser} />}
        </main>
        {notifOpen && <NotifPop onClose={() => setNotifOpen(false)} />}
      </div>

      <CommandPalette open={cmdOpen} onClose={() => setCmdOpen(false)} onJump={onJump} />
      {uploadOpen && <UploadModal onClose={() => setUploadOpen(false)} />}

      <TweaksPanel>
        <TweakSection label="Layout do Kanban" />
        <TweakRadio
          label="Estilo das tarefas"
          value={t.kanbanLayout}
          options={['cards', 'rows']}
          onChange={(v) => setTweak('kanbanLayout', v)}
        />

        <TweakSection label="Painel da IA · Casos" />
        <TweakRadio
          label="Posição"
          value={t.aiPanel}
          options={['fixed', 'floating']}
          onChange={(v) => setTweak('aiPanel', v)}
        />
        <div style={{ fontSize: 10.5, color: 'rgba(41,38,27,.55)', lineHeight: 1.4, padding: '4px 2px' }}>
          <b>Fixa</b>: assistente sempre visível na lateral direita.<br/>
          <b>Flutuante</b>: botão circular no canto inferior, abre on-demand.
        </div>

        <TweakSection label="Atalhos" />
        <TweakButton onClick={() => setCmdOpen(true)}>
          Abrir Command Bar (⌘K)
        </TweakButton>
        <TweakButton onClick={() => setUploadOpen(true)}>
          Abrir Upload inteligente
        </TweakButton>
      </TweaksPanel>
    </div>
  );
};

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
