// Octale Legal — App principal com autenticação real

// ─── URL ↔ view routing ───────────────────────────────────────────────────
const VIEW_TO_PATH = {
  painel:      '/',           // Meu Painel é a tela principal
  dash:        '/dashboard',  // dashboard antigo (fora da sidebar, mantido para validação)
  tasks:       '/tarefas',
  propostas:   '/propostas',
  'contratos-revisao': '/contratos/revisao',
  documentos:  '/documentos',
  'contratos-honorarios': '/contratos/honorarios',
  assinaturas: '/assinaturas',
  library:     '/biblioteca',
  clients:     '/clientes',
  cases:       '/casos',
  processos:   '/processos',
  andamentos:  '/andamentos',
  calendar:    '/calendario',
  team:        '/equipe',
  reports:     '/relatorios',
  publicacoes: '/publicacoes',
  ai:          '/ia',
  financeiro:  '/financeiro',
  artigos:     '/ferramentas/artigos',
  'pdf-studio': '/ferramentas/pdf',
  'org-admin':   '/organizacao',
  'gestor-dash': '/gestor',
  credits:       '/creditos',
};
const PATH_TO_VIEW = Object.fromEntries(
  Object.entries(VIEW_TO_PATH).map(([k, v]) => [v, k])
);
const viewFromPath = () => PATH_TO_VIEW[window.location.pathname] || 'painel';

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

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

  // Erro vindo do callback do Google (?google_error=...) — mostra e limpa a URL
  React.useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    const googleError = params.get('google_error');
    if (googleError) {
      setError(googleError);
      params.delete('google_error');
      const qs = params.toString();
      window.history.replaceState({}, '', window.location.pathname + (qs ? `?${qs}` : ''));
    }
  }, []);

  const handleLogin = async (e) => {
    e?.preventDefault();
    if (!email || !password) return;
    setLoading(true);
    setError('');
    try {
      const user = await window.OctaleApi.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: 'var(--octale-navy)',
        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: 380 }}>
          {/* Logo Octale Legal */}
          <div style={{ marginBottom: 48 }}>
            <svg viewBox="0 0 520 120" width="260" height="60" fill="none" xmlns="http://www.w3.org/2000/svg" style={{ display: 'block', margin: '0 auto' }}>
              <g stroke="#8A9A5B" strokeWidth="4" strokeLinecap="round">
                <path d="M60 50 Q60 33 71 34" />
                <path d="M60 50 Q60 33 71 34" transform="rotate(45 60 60)" />
                <path d="M60 50 Q60 33 71 34" transform="rotate(90 60 60)" />
                <path d="M60 50 Q60 33 71 34" transform="rotate(135 60 60)" />
                <path d="M60 50 Q60 33 71 34" transform="rotate(180 60 60)" />
                <path d="M60 50 Q60 33 71 34" transform="rotate(225 60 60)" />
                <path d="M60 50 Q60 33 71 34" transform="rotate(270 60 60)" />
                <path d="M60 50 Q60 33 71 34" transform="rotate(315 60 60)" />
              </g>
              <circle cx="60" cy="60" r="6.9" fill="#8A9A5B" />
              <text x="136" y="72" fontFamily="DM Sans, Helvetica, sans-serif" fontSize="60" fontWeight="500" letterSpacing="-2.7" fill="#FFFFFF">octale</text>
              <text x="137" y="100" fontFamily="DM Mono, monospace" fontSize="18" letterSpacing="5" fill="#8A9A5B">legal</text>
            </svg>
          </div>

          <h2 style={{
            color: '#ffffff',
            fontSize: 22,
            fontWeight: 700,
            lineHeight: 1.35,
            marginBottom: 16,
            fontFamily: 'var(--font-display)',
          }}>
            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: 'var(--octale-neon)', flexShrink: 0 }} />
                {item}
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Coluna direita — formulário */}
      <div className="login-form" style={{
        background: 'var(--octale-off-white)',
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'center',
        padding: '60px 48px',
      }}>
        <div style={{ width: '100%', maxWidth: 360 }}>
          <div style={{ marginBottom: 36 }}>
            {/* Logo compacta na coluna do form (mobile / telas pequenas onde a coluna esquerda some) */}
            <div className="login-logo-mobile" style={{ marginBottom: 20 }}>
              <svg viewBox="0 0 520 120" width="180" height="44" fill="none" xmlns="http://www.w3.org/2000/svg">
                <g stroke="#5C6640" strokeWidth="4" strokeLinecap="round">
                  <path d="M60 50 Q60 33 71 34" />
                  <path d="M60 50 Q60 33 71 34" transform="rotate(45 60 60)" />
                  <path d="M60 50 Q60 33 71 34" transform="rotate(90 60 60)" />
                  <path d="M60 50 Q60 33 71 34" transform="rotate(135 60 60)" />
                  <path d="M60 50 Q60 33 71 34" transform="rotate(180 60 60)" />
                  <path d="M60 50 Q60 33 71 34" transform="rotate(225 60 60)" />
                  <path d="M60 50 Q60 33 71 34" transform="rotate(270 60 60)" />
                  <path d="M60 50 Q60 33 71 34" transform="rotate(315 60 60)" />
                </g>
                <circle cx="60" cy="60" r="6.9" fill="#5C6640" />
                <text x="136" y="72" fontFamily="DM Sans, Helvetica, sans-serif" fontSize="60" fontWeight="500" letterSpacing="-2.7" fill="#16180F">octale</text>
                <text x="137" y="100" fontFamily="DM Mono, monospace" fontSize="18" letterSpacing="5" fill="#5C6640">legal</text>
              </svg>
            </div>
            <h1 style={{ fontSize: 24, fontWeight: 800, color: 'var(--octale-navy)', marginBottom: 6, fontFamily: 'var(--font-display)' }}>
              Entrar
            </h1>
            <p style={{ fontSize: 13, color: 'var(--fg-muted)', margin: 0 }}>
              Acesso restrito à equipe do seu escritório
            </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: 'var(--fg-muted)',
              }}>E-mail</label>
              <input
                type="email"
                value={email}
                onChange={e => setEmail(e.target.value)}
                placeholder="voce@escritorio.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: 'var(--octale-navy)',
                  outline: 'none',
                  transition: 'border-color .15s',
                }}
                onFocus={e => e.target.style.borderColor = 'var(--octale-navy)'}
                onBlur={e => e.target.style.borderColor = '#ddd'}
              />
            </div>

            <div>
              <label style={{
                display: 'block', marginBottom: 6,
                fontSize: 11, fontWeight: 700, textTransform: 'uppercase',
                letterSpacing: '.08em', color: 'var(--fg-muted)',
              }}>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: 'var(--octale-navy)',
                  outline: 'none',
                  transition: 'border-color .15s',
                }}
                onFocus={e => e.target.style.borderColor = 'var(--octale-navy)'}
                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' : 'var(--octale-navy)',
                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>

          {/* Login com Google (Google Workspace — mesmo e-mail já cadastrado) */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, margin: '20px 0' }}>
            <div style={{ flex: 1, height: 1, background: '#e8e8f0' }} />
            <span style={{ fontSize: 11, color: '#aaa', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '.08em' }}>ou</span>
            <div style={{ flex: 1, height: 1, background: '#e8e8f0' }} />
          </div>

          <button
            type="button"
            onClick={() => { window.location.href = window.OctaleApi.gmail.loginUrl(); }}
            style={{
              width: '100%',
              padding: '12px',
              background: '#ffffff',
              color: 'var(--octale-navy)',
              border: '1.5px solid #ddd',
              borderRadius: 8,
              fontWeight: 700,
              fontSize: 13.5,
              cursor: 'pointer',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              gap: 10,
              transition: 'border-color .15s, background .15s',
            }}
            onMouseOver={e => { e.currentTarget.style.borderColor = 'var(--octale-navy)'; e.currentTarget.style.background = '#fafaff'; }}
            onMouseOut={e => { e.currentTarget.style.borderColor = '#ddd'; e.currentTarget.style.background = '#ffffff'; }}
          >
            <svg width="17" height="17" viewBox="0 0 48 48" aria-hidden="true">
              <path fill="#EA4335" d="M24 9.5c3.54 0 6.71 1.22 9.21 3.6l6.85-6.85C35.9 2.38 30.47 0 24 0 14.62 0 6.51 5.38 2.56 13.22l7.98 6.19C12.43 13.72 17.74 9.5 24 9.5z"/>
              <path fill="#4285F4" d="M46.98 24.55c0-1.57-.15-3.09-.38-4.55H24v9.02h12.94c-.58 2.96-2.26 5.48-4.78 7.18l7.73 6c4.51-4.18 7.09-10.36 7.09-17.65z"/>
              <path fill="#FBBC05" d="M10.53 28.59c-.48-1.45-.76-2.99-.76-4.59s.27-3.14.76-4.59l-7.98-6.19C.92 16.46 0 20.12 0 24c0 3.88.92 7.54 2.56 10.78l7.97-6.19z"/>
              <path fill="#34A853" d="M24 48c6.48 0 11.93-2.13 15.89-5.81l-7.73-6c-2.15 1.45-4.92 2.3-8.16 2.3-6.26 0-11.57-4.22-13.47-9.91l-7.98 6.19C6.51 42.62 14.62 48 24 48z"/>
            </svg>
            Entrar com Google
          </button>

          <div style={{ marginTop: 32, paddingTop: 24, borderTop: '1px solid #e8e8f0', textAlign: 'center', fontSize: 12.5, color: 'var(--fg-muted)' }}>
            Novo por aqui?{' '}
            <a
              href="/cadastro"
              onClick={e => { e.preventDefault(); onGoToSignup(); }}
              style={{ color: 'var(--octale-navy)', fontWeight: 700, textDecoration: 'none' }}
            >
              Criar conta grátis
            </a>
          </div>
        </div>
      </div>
    </div>
  );
};

// ============================================================
// Tela de Cadastro — autoatendimento (POST /api/signup)
// ============================================================
const SignupScreen = ({ onSignup, onGoToLogin }) => {
  const [organizationName, setOrganizationName] = React.useState('');
  const [ownerName, setOwnerName] = React.useState('');
  const [ownerEmail, setOwnerEmail] = React.useState('');
  const [ownerPassword, setOwnerPassword] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState('');

  const fieldStyle = {
    width: '100%', boxSizing: 'border-box',
    padding: '11px 14px',
    background: '#ffffff',
    border: '1.5px solid #ddd',
    borderRadius: 8,
    fontSize: 13.5, color: 'var(--octale-navy)',
    outline: 'none',
    transition: 'border-color .15s',
  };
  const labelStyle = {
    display: 'block', marginBottom: 6,
    fontSize: 11, fontWeight: 700, textTransform: 'uppercase',
    letterSpacing: '.08em', color: 'var(--fg-muted)',
  };

  const handleSignup = async (e) => {
    e?.preventDefault();
    if (!organizationName || !ownerName || !ownerEmail || !ownerPassword) return;
    setLoading(true);
    setError('');
    try {
      const user = await window.OctaleApi.auth.signup({ organizationName, ownerName, ownerEmail, ownerPassword });
      onSignup(user);
    } catch (err) {
      setError(err.message || 'Não foi possível criar a conta.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="login-layout" style={{
      minHeight: '100vh',
      display: 'grid',
      gridTemplateColumns: '1fr 1fr',
    }}>
      {/* Coluna esquerda — identidade visual (mesma do login) */}
      <div className="login-brand" style={{
        background: 'var(--octale-navy)',
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'center',
        padding: '60px 48px',
        position: 'relative',
        overflow: 'hidden',
      }}>
        <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: 380 }}>
          <div style={{ marginBottom: 48 }}>
            <svg viewBox="0 0 520 120" width="260" height="60" fill="none" xmlns="http://www.w3.org/2000/svg" style={{ display: 'block', margin: '0 auto' }}>
              <g stroke="#8A9A5B" strokeWidth="4" strokeLinecap="round">
                <path d="M60 50 Q60 33 71 34" />
                <path d="M60 50 Q60 33 71 34" transform="rotate(45 60 60)" />
                <path d="M60 50 Q60 33 71 34" transform="rotate(90 60 60)" />
                <path d="M60 50 Q60 33 71 34" transform="rotate(135 60 60)" />
                <path d="M60 50 Q60 33 71 34" transform="rotate(180 60 60)" />
                <path d="M60 50 Q60 33 71 34" transform="rotate(225 60 60)" />
                <path d="M60 50 Q60 33 71 34" transform="rotate(270 60 60)" />
                <path d="M60 50 Q60 33 71 34" transform="rotate(315 60 60)" />
              </g>
              <circle cx="60" cy="60" r="6.9" fill="#8A9A5B" />
              <text x="136" y="72" fontFamily="DM Sans, Helvetica, sans-serif" fontSize="60" fontWeight="500" letterSpacing="-2.7" fill="#FFFFFF">octale</text>
              <text x="137" y="100" fontFamily="DM Mono, monospace" fontSize="18" letterSpacing="5" fill="#8A9A5B">legal</text>
            </svg>
          </div>

          <h2 style={{
            color: '#ffffff',
            fontSize: 22,
            fontWeight: 700,
            lineHeight: 1.35,
            marginBottom: 16,
            fontFamily: 'var(--font-display)',
          }}>
            Comece grátis, sem cartão
          </h2>
          <p style={{ color: 'rgba(255,255,255,.45)', fontSize: 13, lineHeight: 1.7 }}>
            14 dias de teste com o produto completo — Casos, Propostas e Motor de Contratos inclusos, para você ver o valor antes de decidir o plano.
          </p>

          <div style={{ marginTop: 48, display: 'flex', flexDirection: 'column', gap: 12 }}>
            {['14 dias grátis, sem cartão de crédito', 'Cancele quando quiser', 'Seus dados isolados dos de outros escritórios'].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: 'var(--octale-neon)', flexShrink: 0 }} />
                {item}
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Coluna direita — formulário de cadastro */}
      <div className="login-form" style={{
        background: 'var(--octale-off-white)',
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'center',
        padding: '60px 48px',
      }}>
        <div style={{ width: '100%', maxWidth: 360 }}>
          <div style={{ marginBottom: 28 }}>
            <div className="login-logo-mobile" style={{ marginBottom: 20 }}>
              <svg viewBox="0 0 520 120" width="180" height="44" fill="none" xmlns="http://www.w3.org/2000/svg">
                <g stroke="#5C6640" strokeWidth="4" strokeLinecap="round">
                  <path d="M60 50 Q60 33 71 34" />
                  <path d="M60 50 Q60 33 71 34" transform="rotate(45 60 60)" />
                  <path d="M60 50 Q60 33 71 34" transform="rotate(90 60 60)" />
                  <path d="M60 50 Q60 33 71 34" transform="rotate(135 60 60)" />
                  <path d="M60 50 Q60 33 71 34" transform="rotate(180 60 60)" />
                  <path d="M60 50 Q60 33 71 34" transform="rotate(225 60 60)" />
                  <path d="M60 50 Q60 33 71 34" transform="rotate(270 60 60)" />
                  <path d="M60 50 Q60 33 71 34" transform="rotate(315 60 60)" />
                </g>
                <circle cx="60" cy="60" r="6.9" fill="#5C6640" />
                <text x="136" y="72" fontFamily="DM Sans, Helvetica, sans-serif" fontSize="60" fontWeight="500" letterSpacing="-2.7" fill="#16180F">octale</text>
                <text x="137" y="100" fontFamily="DM Mono, monospace" fontSize="18" letterSpacing="5" fill="#5C6640">legal</text>
              </svg>
            </div>
            <h1 style={{ fontSize: 24, fontWeight: 800, color: 'var(--octale-navy)', marginBottom: 6, fontFamily: 'var(--font-display)' }}>
              Criar conta
            </h1>
            <p style={{ fontSize: 13, color: 'var(--fg-muted)', margin: 0 }}>
              Sem compromisso — avalie por 14 dias
            </p>
          </div>

          <form onSubmit={handleSignup} style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            <div>
              <label style={labelStyle}>Nome do escritório</label>
              <input
                type="text"
                value={organizationName}
                onChange={e => setOrganizationName(e.target.value)}
                placeholder="Advocacia Exemplo Ltda."
                autoFocus
                style={fieldStyle}
                onFocus={e => e.target.style.borderColor = 'var(--octale-navy)'}
                onBlur={e => e.target.style.borderColor = '#ddd'}
              />
            </div>

            <div>
              <label style={labelStyle}>Seu nome</label>
              <input
                type="text"
                value={ownerName}
                onChange={e => setOwnerName(e.target.value)}
                placeholder="Nome completo"
                style={fieldStyle}
                onFocus={e => e.target.style.borderColor = 'var(--octale-navy)'}
                onBlur={e => e.target.style.borderColor = '#ddd'}
              />
            </div>

            <div>
              <label style={labelStyle}>E-mail</label>
              <input
                type="email"
                value={ownerEmail}
                onChange={e => setOwnerEmail(e.target.value)}
                placeholder="voce@escritorio.com.br"
                style={fieldStyle}
                onFocus={e => e.target.style.borderColor = 'var(--octale-navy)'}
                onBlur={e => e.target.style.borderColor = '#ddd'}
              />
            </div>

            <div>
              <label style={labelStyle}>Senha</label>
              <input
                type="password"
                value={ownerPassword}
                onChange={e => setOwnerPassword(e.target.value)}
                placeholder="Mínimo 8 caracteres"
                style={fieldStyle}
                onFocus={e => e.target.style.borderColor = 'var(--octale-navy)'}
                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' : 'var(--octale-navy)',
                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' }} /> Criando conta…</>
                : 'Começar teste grátis de 14 dias'}
            </button>
          </form>

          <div style={{ marginTop: 24, paddingTop: 24, borderTop: '1px solid #e8e8f0', textAlign: 'center', fontSize: 12.5, color: 'var(--fg-muted)' }}>
            Já tem conta?{' '}
            <a
              href="/"
              onClick={e => { e.preventDefault(); onGoToLogin(); }}
              style={{ color: 'var(--octale-navy)', fontWeight: 700, textDecoration: 'none' }}
            >
              Entrar
            </a>
          </div>
        </div>
      </div>
    </div>
  );
};

// ============================================================
// Error Boundary — captura erros de render e mostra detalhes
// ============================================================
class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false, error: null };
  }
  static getDerivedStateFromError(error) {
    return { hasError: true, error };
  }
  componentDidCatch(error, info) {
    console.error('PAC ErrorBoundary:', error, info);
  }
  render() {
    if (this.state.hasError) {
      return (
        <div style={{ padding: 32, fontFamily: 'monospace', background: '#fff', minHeight: '100vh' }}>
          <div style={{ color: '#C2253E', fontWeight: 700, fontSize: 16, marginBottom: 12 }}>
            ⚠ Erro ao carregar componente
          </div>
          <pre style={{ background: 'var(--octale-off-white)', border: '1px solid #ddd', borderRadius: 6, padding: 16, fontSize: 12, overflow: 'auto', whiteSpace: 'pre-wrap' }}>
            {this.state.error && (this.state.error.stack || this.state.error.message || String(this.state.error))}
          </pre>
          <button
            style={{ marginTop: 16, padding: '8px 16px', background: 'var(--octale-navy)', color: '#fff', border: 0, borderRadius: 6, cursor: 'pointer' }}
            onClick={() => this.setState({ hasError: false, error: null })}
          >
            Tentar novamente
          </button>
        </div>
      );
    }
    return this.props.children;
  }
}

// ============================================================
// Modal de notificacao de aceite (polling global)
// ============================================================
const AcceptNotifModal = ({ proposals, onDismiss, onCreateTask }) => {
  const p = proposals[0];
  const [busy, setBusy] = React.useState(false);
  const [taskDone, setTaskDone] = React.useState(false);

  const handleDismiss = async () => {
    setBusy(true);
    await onDismiss(p.id);
    setBusy(false);
  };

  const handleCreateTask = async () => {
    setBusy(true);
    try {
      await onCreateTask(p.id);
      setTaskDone(true);
    } catch (e) {
      // ignore — continua e fecha
      await onDismiss(p.id);
    } finally {
      setBusy(false);
    }
  };

  if (taskDone) {
    return (
      <div style={{
        position: 'fixed', inset: 0, background: 'rgba(23,23,15,.85)',
        zIndex: 99999, display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontFamily: "'Jost', system-ui, sans-serif",
      }}>
        <div style={{
          background: '#fff', borderRadius: 16, padding: '48px 40px', maxWidth: 480,
          width: '90%', textAlign: 'center', boxShadow: '0 32px 80px rgba(23,23,15,.4)',
        }}>
          <div style={{ fontSize: 48, marginBottom: 16 }}>✅</div>
          <h2 style={{ color: 'var(--octale-navy)', fontSize: 20, fontWeight: 800, marginBottom: 8, fontFamily: 'var(--font-display)' }}>
            Tarefa criada!
          </h2>
          <p style={{ color: '#666', fontSize: 13, marginBottom: 28 }}>
            A tarefa para {p.client_name} foi adicionada ao Kanban.
          </p>
          <button
            onClick={handleDismiss}
            style={{
              padding: '11px 28px', borderRadius: 8, border: 0,
              background: 'var(--octale-navy)', color: '#fff', fontWeight: 700, fontSize: 14, cursor: 'pointer',
            }}
          >
            Ok, fechar
          </button>
        </div>
      </div>
    );
  }

  return (
    <div style={{
      position: 'fixed', inset: 0, background: 'rgba(23,23,15,.85)',
      zIndex: 99999, display: 'flex', alignItems: 'center', justifyContent: 'center',
      fontFamily: "'Jost', system-ui, sans-serif",
    }}>
      <div style={{
        background: '#fff', borderRadius: 16, padding: '48px 40px', maxWidth: 520,
        width: '90%', textAlign: 'center', position: 'relative',
        boxShadow: '0 32px 80px rgba(23,23,15,.4)',
      }}>
        {proposals.length > 1 && (
          <div style={{
            position: 'absolute', top: 16, right: 20,
            background: 'var(--octale-neon)', color: 'var(--octale-navy)',
            borderRadius: 12, padding: '2px 10px', fontSize: 11, fontWeight: 700,
          }}>
            +{proposals.length - 1} mais
          </div>
        )}
        <div style={{ fontSize: 56, marginBottom: 16 }}>&#x1F389;</div>
        <h2 style={{
          color: 'var(--octale-navy)', fontSize: 22, fontWeight: 800, marginBottom: 6,
          fontFamily: 'var(--font-display)',
        }}>
          Proposta aceita!
        </h2>
        <p style={{ color: '#333', fontSize: 15, fontWeight: 600, marginBottom: 4 }}>
          {p.client_name}
        </p>
        <p style={{ color: 'var(--fg-muted)', fontSize: 13, marginBottom: p.total_value ? 12 : 28 }}>
          {p.proposal_number}{p.responsible ? ' · ' + p.responsible : ''}
        </p>
        {p.total_value && (
          <div style={{
            display: 'inline-block', background: '#f0fff0',
            border: '1px solid #b6e6b6', borderRadius: 8,
            padding: '6px 18px', color: '#1a6e1a', fontWeight: 700,
            fontSize: 15, marginBottom: 28,
          }}>
            {p.total_value}
          </div>
        )}
        <div style={{ display: 'flex', gap: 12, justifyContent: 'center', flexWrap: 'wrap' }}>
          <button
            onClick={handleDismiss}
            disabled={busy}
            style={{
              padding: '12px 24px', borderRadius: 8,
              border: '1.5px solid #ddd', background: 'var(--octale-off-white)',
              color: '#333', fontWeight: 600, fontSize: 14,
              cursor: busy ? 'not-allowed' : 'pointer',
            }}
          >
            Ok, ciente
          </button>
          <button
            onClick={handleCreateTask}
            disabled={busy}
            style={{
              padding: '12px 24px', borderRadius: 8, border: 0,
              background: 'var(--octale-navy)', color: '#fff',
              fontWeight: 700, fontSize: 14,
              cursor: busy ? 'not-allowed' : 'pointer',
              display: 'flex', alignItems: 'center', gap: 8,
            }}
          >
            {busy ? (
              <><span className="spinner" style={{ width: 14, height: 14, borderColor: 'rgba(255,255,255,.2)', borderTopColor: '#fff' }} /> Criando...</>
            ) : 'Ok, criar tarefa'}
          </button>
        </div>
      </div>
    </div>
  );
};

// ============================================================
// App principal
// ============================================================
const App = () => {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [view, setView] = React.useState(() => viewFromPath());
  const [navCaseId, setNavCaseId] = React.useState(null);
  const [navClientId, setNavClientId] = React.useState(null);
  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);
  // Tela pública mostrada quando não há sessão: login (padrão) ou cadastro
  // (/cadastro — link direto de marketing). Troca sem reload via pushState.
  const [authScreen, setAuthScreen] = React.useState(
    window.location.pathname === '/cadastro' ? 'signup' : 'login'
  );
  const goToAuthScreen = (screen) => {
    const path = screen === 'signup' ? '/cadastro' : '/';
    window.history.pushState({}, '', path);
    setAuthScreen(screen);
  };

  const [counts, setCounts] = React.useState({ tasks: 0, clients: 0, cases: 0, publicacoes: 0, artigos: 0 });
  const [acceptNotifs, setAcceptNotifs] = React.useState([]);
  const [notifUnread, setNotifUnread] = React.useState(0);
  const [artigoBannerOff, setArtigoBannerOff] = React.useState(false);

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

  // Buscar contadores reais após autenticação
  // (super admin não pertence a nenhuma organização — não usa o app do escritório)
  React.useEffect(() => {
    if (!currentUser || currentUser.is_super_admin) return;
    const load = async () => {
      try {
        const [tasks, clients, cases, pubStats, andamentosCount] = await Promise.all([
          window.OctaleApi.tasks.list().catch(() => []),
          window.OctaleApi.clients.list().catch(() => []),
          window.OctaleApi.cases.list().catch(() => []),
          window.OctaleApi.publicacoes.stats().catch(() => ({ nova: 0 })),
          window.OctaleApi.andamentos.pendingCount().catch(() => 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),
          artigos: 0,
          andamentos: andamentosCount,
        });
      } catch (e) {
        // silencioso — counts ficam em zero se API falhar
      }
    };
    load();
  }, [currentUser]);

  // Polling de aceites pendentes (a cada 15s quando autenticado)
  React.useEffect(() => {
    if (!currentUser || currentUser.is_super_admin) return;
    const poll = async () => {
      try {
        const proposals = await window.OctaleApi.propostas.pendingAccepts().catch(() => []);
        setAcceptNotifs(proposals || []);
      } catch (e) {}
    };
    poll();
    const id = setInterval(poll, 15000);
    return () => clearInterval(id);
  }, [currentUser]);

  // Polling do badge de notificações não lidas (30s)
  React.useEffect(() => {
    if (!currentUser || currentUser.is_super_admin) return;
    const poll = () => {
      window.OctaleApi.notifications.unreadCount()
        .then(setNotifUnread)
        .catch(() => {});
    };
    poll();
    const id = setInterval(poll, 30000);
    return () => clearInterval(id);
  }, [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);
  }, []);

  // Sync view → URL (push state when view changes programmatically)
  React.useEffect(() => {
    const path = VIEW_TO_PATH[view] || '/';
    if (window.location.pathname !== path) {
      history.pushState({ view }, '', path);
    }
  }, [view]);

  // Sync URL → view on browser back / forward
  React.useEffect(() => {
    const onPop = () => { setView(viewFromPath()); };
    window.addEventListener('popstate', onPop);
    return () => window.removeEventListener('popstate', onPop);
  }, []);

  // Navegação programática via evento customizado (usado por componentes filhos)
  React.useEffect(() => {
    const onNav = (e) => { if (e.detail) setView(e.detail); };
    window.addEventListener('pac:nav', onNav);
    return () => window.removeEventListener('pac:nav', onNav);
  }, []);

  // 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) {
      // Navega para item específico vindo da busca (passa o ID direto)
      if (target === 'cases') setNavCaseId(item?.id || null);
      else if (target === 'clients') setNavClientId(item?.id || null);
      else { setNavCaseId(null); setNavClientId(null); }
      setView(target);
    }
  };

  // Loading inicial
  if (authLoading) return (
    <div style={{ minHeight: '100vh', background: 'var(--octale-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(--octale-neon)' }} />
      Carregando…
    </div>
  );

  // Não autenticado
  if (!currentUser) {
    return authScreen === 'signup'
      ? <SignupScreen onSignup={user => setCurrentUser(user)} onGoToLogin={() => goToAuthScreen('login')} />
      : <LoginScreen onLogin={user => setCurrentUser(user)} onGoToSignup={() => goToAuthScreen('signup')} />;
  }

  // Super admin do app (dono da plataforma) — shell próprio, sem sidebar do escritório.
  if (currentUser.is_super_admin) {
    return (
      <ErrorBoundary>
        <SuperAdminPanel currentUser={currentUser} onLogout={() => window.OctaleApi.auth.logout()} />
      </ErrorBoundary>
    );
  }

  return (
    <div className="app">
      <Sidebar
        view={view}
        onView={(v) => { setView(v); setNavCaseId(null); setNavClientId(null); 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={notifUnread}
          user={currentUser}
          onLogout={() => window.OctaleApi.auth.logout()}
          onMenuOpen={() => setMenuOpen(v => !v)}
        />
        <main className="view">
          <ErrorBoundary key={view}>
            {view === 'dash' && <Dashboard user={currentUser} />}
            {view === 'painel' && <MeuPainel user={currentUser} onNavigate={(v, id) => { if (v === 'cases') setNavCaseId(id ?? null); setView(v); }} />}
            {view === 'tasks' && <Tasks layout={t.kanbanLayout} currentUser={currentUser} />}
            {view === 'propostas' && <Propostas currentUser={currentUser} />}
            {view === 'contratos-revisao' && <ContratosRevisao currentUser={currentUser} />}
            {view === 'documentos' && <Documentos currentUser={currentUser} />}
            {view === 'contratos-honorarios' && <ContratosHonorarios currentUser={currentUser} />}
            {view === 'assinaturas' && <Assinaturas currentUser={currentUser} />}
            {view === 'library' && <Library currentUser={currentUser} />}
            {view === 'clients' && <Clients initialClientId={navClientId} onOpenCase={(id) => { setNavCaseId(id); setView('cases'); }} />}
            {view === 'cases' && <Cases aiPanel={t.aiPanel} caseId={navCaseId} />}
            {view === 'processos' && <Processos onOpenCase={(id) => { setNavCaseId(id); setView('cases'); }} />}
            {view === 'andamentos' && <Andamentos />}
            {view === 'calendar' && <Calendar currentUser={currentUser} />}
            {view === 'team' && <Team currentUser={currentUser} />}
            {view === 'reports' && <Reports />}
            {view === 'publicacoes-astrea' && <PublicacoesAstrea />}
            {view === 'publicacoes' && <PublicacoesDJen />}
            {view === 'upload' && (() => { setUploadOpen(true); setView('painel'); return null; })()}
            {view === 'ai' && <AIAssistant user={currentUser} />}
            {view === 'financeiro' && <Financeiro currentUser={currentUser} />}
            {view === 'artigos' && <Artigos currentUser={currentUser} />}
            {view === 'org-admin' && <OrgAdminPanel currentUser={currentUser} />}
            {view === 'gestor-dash' && <GestorDashboard user={currentUser} />}
            {view === 'credits' && <CreditsPanel currentUser={currentUser} />}
            {view === 'pdf-studio' && (
              <iframe
                src="/pdf-studio/"
                title="PDF Studio"
                style={{ width: '100%', height: '100%', border: 'none', display: 'block' }}
                allow="downloads"
              />
            )}
          </ErrorBoundary>
        </main>
        {notifOpen && (
          <NotifPop
            onClose={() => setNotifOpen(false)}
            onJump={onJump}
            onRead={() => window.OctaleApi.notifications.unreadCount().then(setNotifUnread).catch(() => {})}
          />
        )}
      </div>

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

      {acceptNotifs.length > 0 && (
        <AcceptNotifModal
          proposals={acceptNotifs}
          onDismiss={async (id) => {
            await window.OctaleApi.propostas.markAcceptRead(id).catch(() => {});
            setAcceptNotifs(prev => prev.filter(p => p.id !== id));
          }}
          onCreateTask={async (id) => {
            await window.OctaleApi.propostas.createTask(id, {}).catch(() => {});
            await window.OctaleApi.propostas.markAcceptRead(id).catch(() => {});
            setAcceptNotifs(prev => prev.filter(p => p.id !== id));
          }}
        />
      )}

      <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>
  );
};

// Captura erros globais (parse de scripts, runtime fora do React, etc.)
window.addEventListener('error', (e) => {
  const msg = e.message || String(e.error || e);
  const src = e.filename || '(desconhecido)';
  const ln = e.lineno || '?';
  console.error('[PAC global error]', msg, '@', src, ln);
  // Cria um banner visível no topo
  if (!document.getElementById('__pac_err_banner')) {
    const banner = document.createElement('div');
    banner.id = '__pac_err_banner';
    banner.style.cssText = 'position:fixed;top:0;left:0;right:0;z-index:99999;background:#C2253E;color:#fff;padding:12px 16px;font-family:monospace;font-size:12px;line-height:1.5;max-height:40vh;overflow:auto;white-space:pre-wrap;box-shadow:0 2px 8px rgba(0,0,0,.3)';
    document.body.appendChild(banner);
  }
  const banner = document.getElementById('__pac_err_banner');
  banner.textContent += '⚠ ' + msg + '\n   em ' + src.split('/').pop() + ':' + ln + '\n\n';
});

window.addEventListener('unhandledrejection', (e) => {
  console.error('[PAC unhandled rejection]', e.reason);
});

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