// Main App — login + router

const { useState: appState, useEffect: appEffect, useRef: appRef } = React;

/* ── Floating test panel ── */
function TestPanel({ novaSenha, setNovaSenha, perfil, setPerfil }) {
  const [open, setOpen] = appState(false);

  const perfilLabel = { admin:'Admin', terapeuta:'Terapeuta', secretaria:'Secretária' };

  return (
    <div style={{ position:'fixed', bottom:20, right:20, zIndex:999, display:'flex', flexDirection:'column', alignItems:'flex-end', gap:8 }}>
      {/* Expanded panel */}
      {open && (
        <div style={{
          background:'rgba(15,12,40,0.88)', backdropFilter:'blur(12px)',
          borderRadius:10, padding:'14px 16px', width:230,
          boxShadow:'0 8px 32px rgba(0,0,0,0.4)', border:'1px solid rgba(255,255,255,0.08)',
          display:'flex', flexDirection:'column', gap:12,
        }}>
          <div style={{ fontSize:10, fontWeight:700, color:'rgba(255,255,255,0.4)', letterSpacing:1.2, textTransform:'uppercase' }}>Controles de teste</div>

          {/* Checkbox */}
          <label style={{ display:'flex', alignItems:'center', gap:8, cursor:'pointer', userSelect:'none' }}
            onClick={() => setNovaSenha(s => !s)}>
            <div style={{
              width:15, height:15, borderRadius:4, flexShrink:0,
              border:`2px solid ${novaSenha ? '#818cf8' : 'rgba(255,255,255,0.25)'}`,
              background: novaSenha ? '#818cf8' : 'transparent',
              display:'flex', alignItems:'center', justifyContent:'center', transition:'all 0.15s',
            }}>
              {novaSenha && <svg width="9" height="7" viewBox="0 0 9 7" fill="none"><path d="M1 3.5l2.5 2.5 4.5-5" stroke="white" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/></svg>}
            </div>
            <span style={{ fontSize:12, color:'rgba(255,255,255,0.75)' }}>Primeiro acesso (trocar senha)</span>
          </label>

          {/* Divider */}
          <div style={{ height:1, background:'rgba(255,255,255,0.08)' }} />

          {/* Radio group */}
          <div>
            <div style={{ fontSize:10, fontWeight:600, color:'rgba(255,255,255,0.4)', letterSpacing:0.8, textTransform:'uppercase', marginBottom:8 }}>Perfil</div>
            <div style={{ display:'flex', flexDirection:'column', gap:7 }}>
              {[
                { value:'admin',      label:'Administrador' },
                { value:'terapeuta',  label:'Terapeuta' },
                { value:'secretaria', label:'Secretária' },
              ].map(opt => (
                <label key={opt.value} onClick={() => setPerfil(opt.value)}
                  style={{ display:'flex', alignItems:'center', gap:8, cursor:'pointer', userSelect:'none' }}>
                  <div style={{
                    width:14, height:14, borderRadius:'50%', flexShrink:0,
                    border:`2px solid ${perfil === opt.value ? '#818cf8' : 'rgba(255,255,255,0.25)'}`,
                    background: perfil === opt.value ? '#818cf8' : 'transparent',
                    display:'flex', alignItems:'center', justifyContent:'center', transition:'all 0.15s',
                  }}>
                    {perfil === opt.value && <div style={{ width:5, height:5, borderRadius:'50%', background:'white' }} />}
                  </div>
                  <span style={{ fontSize:12, color: perfil === opt.value ? 'white' : 'rgba(255,255,255,0.6)' }}>{opt.label}</span>
                </label>
              ))}
            </div>
          </div>
        </div>
      )}

      {/* Toggle pill */}
      <button onClick={() => setOpen(s => !s)} style={{
        display:'flex', alignItems:'center', gap:6,
        padding:'7px 12px', borderRadius:20,
        background:'rgba(15,12,40,0.75)', backdropFilter:'blur(10px)',
        border:'1px solid rgba(255,255,255,0.12)',
        color:'rgba(255,255,255,0.7)', fontSize:12, fontWeight:500,
        cursor:'pointer', boxShadow:'0 4px 16px rgba(0,0,0,0.3)',
        transition:'all 0.15s',
      }}>
        <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <path d="M12 2a10 10 0 1 0 0 20A10 10 0 0 0 12 2z M12 8v4l3 3" />
        </svg>
        Teste · {perfilLabel[perfil]}{novaSenha ? ' · Nova senha' : ''}
      </button>
    </div>
  );
}

/* ── Recuperação de senha ── */
function ForgotPasswordPage({ onBack }) {
  const [subStep, setSubStep] = appState('form'); // 'form' | 'sent' | 'reset'
  const [email, setEmail]     = appState('');
  const [nova, setNova]       = appState('');
  const [confirmar, setConfirmar] = appState('');
  const [showNova, setShowNova]   = appState(false);
  const [showConf, setShowConf]   = appState(false);
  const [loading, setLoading]     = appState(false);
  const [erro, setErro]           = appState('');
  const [expiry, setExpiry]       = appState(15 * 60); // 900s
  const timerRef = appRef(null);

  /* Contagem regressiva de 15 min na tela reset */
  appEffect(() => {
    if (subStep !== 'reset') return;
    setExpiry(15 * 60);
    timerRef.current = setInterval(() => {
      setExpiry(e => {
        if (e <= 1) { clearInterval(timerRef.current); return 0; }
        return e - 1;
      });
    }, 1000);
    return () => clearInterval(timerRef.current);
  }, [subStep]);

  const fmtTime = s => `${String(Math.floor(s/60)).padStart(2,'0')}:${String(s%60).padStart(2,'0')}`;

  /* Força da senha */
  const pwdChecks = [
    { ok: nova.length >= 8,          text: 'Mínimo 8 caracteres' },
    { ok: /[A-Z]/.test(nova),        text: 'Uma letra maiúscula' },
    { ok: /[0-9]/.test(nova),        text: 'Um número' },
    { ok: /[^A-Za-z0-9]/.test(nova), text: 'Um caractere especial' },
  ];
  const score = pwdChecks.filter(c => c.ok).length;
  const str = nova ? (
    score <= 1 ? { label:'Fraca',    color:'#ef4444', width:'25%' } :
    score === 2 ? { label:'Razoável', color:'#f59e0b', width:'50%' } :
    score === 3 ? { label:'Boa',      color:'#3b82f6', width:'75%' } :
                  { label:'Forte',    color:'#16a34a', width:'100%' }
  ) : null;

  const BrainIcon = () => (
    <svg width="34" height="34" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
      <path d="M9.5 2A2.5 2.5 0 0 1 12 4.5v15a2.5 2.5 0 0 1-4.96-.44 2.5 2.5 0 0 1-2.96-3.08 3 3 0 0 1-.34-5.58 2.5 2.5 0 0 1 1.32-4.24 2.5 2.5 0 0 1 1.98-3A2.5 2.5 0 0 1 9.5 2Z" />
      <path d="M14.5 2A2.5 2.5 0 0 0 12 4.5v15a2.5 2.5 0 0 0 4.96-.44 2.5 2.5 0 0 0 2.96-3.08 3 3 0 0 0 .34-5.58 2.5 2.5 0 0 0-1.32-4.24 2.5 2.5 0 0 0-1.98-3A2.5 2.5 0 0 0 14.5 2Z" />
    </svg>
  );

  const card = {
    background:'white', borderRadius:12, width:420, padding:'36px 40px',
    boxShadow:'0 20px 60px rgba(0,0,0,0.3)',
  };
  const wrap = {
    minHeight:'100vh', display:'flex', alignItems:'center', justifyContent:'center',
    background:'#1C416B',
  };
  const inputStyle = { width:'100%', padding:'10px 12px', border:'1px solid #d1d5db', borderRadius:6, fontSize:14, outline:'none', color:'#111', boxSizing:'border-box' };
  const btn = (primary) => ({ width:'100%', padding:'11px', background: primary ? C.primary : 'white', color: primary ? 'white' : '#374151', border: primary ? 'none' : '1px solid #d1d5db', borderRadius:6, fontSize:14, fontWeight:600, cursor:'pointer' });

  /* ── TELA 1: Informe o e-mail ── */
  if (subStep === 'form') return (
    <div style={wrap}>
      <div style={card}>
        <div style={{ textAlign:'center', marginBottom:28 }}>
          <img src="uploads/WhatsApp_Image_2026-03-16_at_20.39.04_-_Copia-removebg-preview.png" alt="Conexão Psi" style={{ height:48, width:'auto', objectFit:'contain', margin:'0 auto 14px', display:'block' }} />
          <h1 style={{ fontSize:20, fontWeight:700, color:'#111', margin:0 }}>Recuperar senha</h1>
          <p style={{ fontSize:13, color:'#6b7280', margin:'8px 0 0', lineHeight:1.5 }}>Informe o e-mail cadastrado e enviaremos<br />um link para redefinir sua senha.</p>
        </div>
        <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
          <div>
            <label style={{ fontSize:13, fontWeight:500, color:'#374151', display:'block', marginBottom:5 }}>E-mail</label>
            <input type="email" value={email} onChange={e => { setEmail(e.target.value); setErro(''); }}
              placeholder="seu.email@exemplo.com" style={inputStyle} />
            {erro && <p style={{ fontSize:12, color:'#ef4444', margin:'5px 0 0' }}>{erro}</p>}
          </div>
        </div>
        <div style={{ display:'flex', flexDirection:'column', gap:8, marginTop:20 }}>
          <button onClick={() => {
            if (!email || !email.includes('@')) { setErro('Informe um e-mail válido.'); return; }
            setLoading(true);
            setTimeout(() => { setLoading(false); setSubStep('sent'); }, 800);
          }} disabled={loading} style={btn(true)}>
            {loading ? 'Enviando...' : 'Enviar link de recuperação'}
          </button>
          <button onClick={onBack} style={btn(false)}>← Voltar ao login</button>
        </div>
      </div>
    </div>
  );

  /* ── TELA 2: E-mail enviado ── */
  if (subStep === 'sent') return (
    <div style={wrap}>
      <div style={card}>
        <div style={{ textAlign:'center', marginBottom:24 }}>
          <div style={{ width:64, height:64, borderRadius:'50%', background:'#dcfce7', display:'flex', alignItems:'center', justifyContent:'center', margin:'0 auto 16px' }}>
            <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="#16a34a" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <rect x="2" y="4" width="20" height="16" rx="2"/>
              <path d="m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"/>
            </svg>
          </div>
          <h1 style={{ fontSize:20, fontWeight:700, color:'#111', margin:0 }}>Verifique seu e-mail</h1>
          <p style={{ fontSize:13, color:'#6b7280', margin:'10px 0 0', lineHeight:1.6 }}>
            Enviamos um link de recuperação para<br />
            <strong style={{ color:'#111' }}>{email}</strong><br />
            O link expira em <strong>15 minutos</strong>.
          </p>
        </div>
        <div style={{ background:'#eff6ff', border:'1px solid #bfdbfe', borderRadius:8, padding:'12px 14px', fontSize:13, color:'#374151', lineHeight:1.5, marginBottom:20 }}>
          ℹ Não encontrou o e-mail? Verifique a caixa de spam ou lixo eletrônico.
        </div>
        <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
          {/* Simula clique no link do e-mail */}
          <button onClick={() => setSubStep('reset')} style={btn(true)}>Simular clique no link →</button>
          <button onClick={() => { setSubStep('form'); }}
            style={{ ...btn(false), fontSize:13, color:'#6b7280' }}>
            Reenviar e-mail
          </button>
          <button onClick={onBack} style={{ ...btn(false), fontSize:13 }}>← Voltar ao login</button>
        </div>
      </div>
    </div>
  );

  /* ── TELA 3: Redefinir senha (com timer 15 min) ── */
  return (
    <div style={wrap}>
      <div style={card}>
        <div style={{ textAlign:'center', marginBottom:24 }}>
          <img src="uploads/WhatsApp_Image_2026-03-16_at_20.39.04_-_Copia-removebg-preview.png" alt="Conexão Psi" style={{ height:48, width:'auto', objectFit:'contain', margin:'0 auto 14px', display:'block' }} />
          <h1 style={{ fontSize:20, fontWeight:700, color:'#111', margin:0 }}>Redefinir senha</h1>
          <p style={{ fontSize:13, color:'#6b7280', margin:'8px 0 0' }}>Crie uma nova senha segura para sua conta.</p>
        </div>

        {/* Timer */}
        <div style={{ display:'flex', alignItems:'center', justifyContent:'center', gap:8, marginBottom:20, padding:'8px 14px', background: expiry < 60 ? '#fee2e2' : '#fef9c3', borderRadius:8, border:`1px solid ${expiry < 60 ? '#fca5a5' : '#fde047'}` }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke={expiry < 60 ? '#dc2626' : '#92400e'} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/>
          </svg>
          <span style={{ fontSize:13, fontWeight:600, color: expiry < 60 ? '#dc2626' : '#92400e' }}>
            {expiry > 0 ? `Link válido por ${fmtTime(expiry)}` : 'Link expirado — solicite um novo.'}
          </span>
        </div>

        {expiry > 0 ? (
          <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
            {/* Nova senha */}
            <div>
              <label style={{ fontSize:13, fontWeight:500, color:'#374151', display:'block', marginBottom:5 }}>Nova senha</label>
              <div style={{ position:'relative' }}>
                <input type={showNova ? 'text' : 'password'} value={nova}
                  onChange={e => { setNova(e.target.value); setErro(''); }}
                  placeholder="Mínimo 8 caracteres"
                  style={{ ...inputStyle, paddingRight:40 }} />
                <button onClick={() => setShowNova(s => !s)}
                  style={{ position:'absolute', right:10, top:'50%', transform:'translateY(-50%)', background:'none', border:'none', cursor:'pointer' }}>
                  <Icon name={showNova ? 'eyeOff' : 'eye'} size={18} color="#9ca3af" />
                </button>
              </div>
              {str && nova.length > 0 && (
                <div style={{ marginTop:6 }}>
                  <div style={{ height:4, background:'#e5e7eb', borderRadius:2, overflow:'hidden' }}>
                    <div style={{ height:'100%', width:str.width, background:str.color, borderRadius:2, transition:'width .3s' }} />
                  </div>
                  <span style={{ fontSize:11, color:str.color, fontWeight:500 }}>Força: {str.label}</span>
                </div>
              )}
            </div>
            {/* Requisitos */}
            {nova.length > 0 && (
              <div style={{ background:'#f9fafb', borderRadius:8, padding:'10px 14px', display:'flex', flexDirection:'column', gap:5 }}>
                {pwdChecks.map(r => (
                  <div key={r.text} style={{ display:'flex', alignItems:'center', gap:7, fontSize:12, color: r.ok ? '#16a34a' : '#9ca3af' }}>
                    <span style={{ fontSize:14 }}>{r.ok ? '✓' : '○'}</span>{r.text}
                  </div>
                ))}
              </div>
            )}
            {/* Confirmar */}
            <div>
              <label style={{ fontSize:13, fontWeight:500, color:'#374151', display:'block', marginBottom:5 }}>Confirmar senha</label>
              <div style={{ position:'relative' }}>
                <input type={showConf ? 'text' : 'password'} value={confirmar}
                  onChange={e => { setConfirmar(e.target.value); setErro(''); }}
                  placeholder="Repita a nova senha"
                  style={{ ...inputStyle, paddingRight:40 }} />
                <button onClick={() => setShowConf(s => !s)}
                  style={{ position:'absolute', right:10, top:'50%', transform:'translateY(-50%)', background:'none', border:'none', cursor:'pointer' }}>
                  <Icon name={showConf ? 'eyeOff' : 'eye'} size={18} color="#9ca3af" />
                </button>
              </div>
              {confirmar.length > 0 && (
                <p style={{ fontSize:12, margin:'5px 0 0', color: nova === confirmar ? '#16a34a' : '#ef4444' }}>
                  {nova === confirmar ? '✓ Senhas coincidem' : '✕ Senhas não coincidem'}
                </p>
              )}
            </div>
            {erro && <div style={{ background:'#fee2e2', border:'1px solid #fca5a5', borderRadius:6, padding:'9px 12px', fontSize:13, color:'#991b1b' }}>{erro}</div>}
            <button onClick={() => {
              if (!nova) { setErro('Informe a nova senha.'); return; }
              if (nova.length < 8) { setErro('Mínimo 8 caracteres.'); return; }
              if (nova !== confirmar) { setErro('As senhas não coincidem.'); return; }
              setLoading(true);
              setTimeout(() => { setLoading(false); onBack(); }, 800);
            }} disabled={loading} style={btn(true)}>
              {loading ? 'Salvando...' : 'Salvar nova senha'}
            </button>
          </div>
        ) : (
          <button onClick={() => setSubStep('form')} style={btn(true)}>Solicitar novo link</button>
        )}
      </div>
    </div>
  );
}

/* ── Login page ── */
function LoginPage({ onLogin, onForgot }) {
  const [email, setEmail] = appState('ana.silva@conexaopsi.com');
  const [senha, setSenha] = appState('••••••••');
  const [showPwd, setShowPwd] = appState(false);
  const [loading, setLoading] = appState(false);
  const [novaSenha, setNovaSenha] = appState(false);
  const [perfil, setPerfil] = appState('admin');

  function handleLogin() {
    setLoading(true);
    setTimeout(() => { setLoading(false); onLogin({ novaSenha, perfil }); }, 700);
  }

  const Checkbox = ({ checked, onChange, label }) => (
    <label style={{ display:'flex', alignItems:'center', gap:8, cursor:'pointer', fontSize:13, color:'#374151', userSelect:'none' }}>
      <div onClick={onChange} style={{
        width:16, height:16, borderRadius:4, border:`2px solid ${checked ? C.primary : '#d1d5db'}`,
        background: checked ? C.primary : 'white', display:'flex', alignItems:'center', justifyContent:'center',
        transition:'all 0.15s', flexShrink:0,
      }}>
        {checked && <svg width="10" height="8" viewBox="0 0 10 8" fill="none"><path d="M1 4l3 3 5-6" stroke="white" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/></svg>}
      </div>
      {label}
    </label>
  );

  return (
    <div style={{
      minHeight:'100vh', display:'flex', alignItems:'center', justifyContent:'center',
      background:'#1C416B',
    }}>
      <div style={{
        background:'white', borderRadius:12, width:420, padding:'36px 40px',
        boxShadow:'0 20px 60px rgba(0,0,0,0.3)',
      }}>
        {/* Logo */}
        <div style={{ textAlign:'center', marginBottom:28 }}>
          <img src="uploads/WhatsApp_Image_2026-03-16_at_20.39.04_-_Copia-removebg-preview.png" alt="Conexão Psi" style={{ height:56, width:'auto', objectFit:'contain', margin:'0 auto 14px', display:'block' }} />
          <p style={{ fontSize:13, color:'#6b7280', margin:0 }}>Sistema de gestão para clínicas de psicologia</p>
        </div>

        {/* Fields */}
        <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
          <div>
            <label style={{ fontSize:13, fontWeight:500, color:'#374151', display:'block', marginBottom:5 }}>E-mail</label>
            <input type="email" value={email} onChange={e => setEmail(e.target.value)}
              placeholder="seu.email@exemplo.com"
              style={{ width:'100%', padding:'10px 12px', border:'1px solid #d1d5db', borderRadius:6, fontSize:14, outline:'none', color:'#111', boxSizing:'border-box' }} />
          </div>
          <div>
            <label style={{ fontSize:13, fontWeight:500, color:'#374151', display:'block', marginBottom:5 }}>Senha</label>
            <div style={{ position:'relative' }}>
              <input type={showPwd ? 'text' : 'password'} value={senha} onChange={e => setSenha(e.target.value)}
                style={{ width:'100%', padding:'10px 40px 10px 12px', border:'1px solid #d1d5db', borderRadius:6, fontSize:14, outline:'none', color:'#111', boxSizing:'border-box' }} />
              <button onClick={() => setShowPwd(s => !s)}
                style={{ position:'absolute', right:10, top:'50%', transform:'translateY(-50%)', background:'none', border:'none', cursor:'pointer', color:'#9ca3af', lineHeight:1 }}>
                <Icon name={showPwd ? 'eyeOff' : 'eye'} size={18} color="#9ca3af" />
              </button>
            </div>
          </div>
        </div>

        {/* ── Controles de teste ── */}

        <div style={{ display:'flex', flexDirection:'column', gap:10, marginTop:20 }}>
          <button onClick={handleLogin} disabled={loading}
            style={{ width:'100%', padding:'11px', background:C.primary, color:'white', border:'none', borderRadius:6, fontSize:15, fontWeight:600, cursor:'pointer', opacity: loading ? 0.7 : 1 }}>
            {loading ? 'Entrando...' : 'Entrar'}
          </button>
          <button onClick={onForgot} style={{ width:'100%', padding:'10px', background:'white', color:'#374151', border:'1px solid #d1d5db', borderRadius:6, fontSize:14, fontWeight:500, cursor:'pointer' }}>
            Esqueci minha senha
          </button>
        </div>
      </div>

      {/* ── Floating test panel ── */}
      <TestPanel novaSenha={novaSenha} setNovaSenha={setNovaSenha} perfil={perfil} setPerfil={setPerfil} />
    </div>
  );
}

/* ── Change Password page ── */
function ChangePasswordPage({ onDone }) {
  const [nova, setNova] = appState('');
  const [confirmar, setConfirmar] = appState('');
  const [showNova, setShowNova] = appState(false);
  const [showConfirmar, setShowConfirmar] = appState(false);
  const [loading, setLoading] = appState(false);
  const [erro, setErro] = appState('');

  const BrainIcon = () => (
    <svg width="34" height="34" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
      <path d="M9.5 2A2.5 2.5 0 0 1 12 4.5v15a2.5 2.5 0 0 1-4.96-.44 2.5 2.5 0 0 1-2.96-3.08 3 3 0 0 1-.34-5.58 2.5 2.5 0 0 1 1.32-4.24 2.5 2.5 0 0 1 1.98-3A2.5 2.5 0 0 1 9.5 2Z" />
      <path d="M14.5 2A2.5 2.5 0 0 0 12 4.5v15a2.5 2.5 0 0 0 4.96-.44 2.5 2.5 0 0 0 2.96-3.08 3 3 0 0 0 .34-5.58 2.5 2.5 0 0 0-1.32-4.24 2.5 2.5 0 0 0-1.98-3A2.5 2.5 0 0 0 14.5 2Z" />
    </svg>
  );

  function PasswordField({ label, value, onChange, show, onToggle, placeholder }) {
    return (
      <div>
        <label style={{ fontSize:13, fontWeight:500, color:'#374151', display:'block', marginBottom:5 }}>{label}</label>
        <div style={{ position:'relative' }}>
          <input
            type={show ? 'text' : 'password'}
            value={value}
            onChange={e => { onChange(e.target.value); setErro(''); }}
            placeholder={placeholder}
            style={{ width:'100%', padding:'10px 40px 10px 12px', border:`1px solid ${erro ? '#fca5a5' : '#d1d5db'}`, borderRadius:6, fontSize:14, outline:'none', color:'#111', boxSizing:'border-box' }}
          />
          <button onClick={onToggle}
            style={{ position:'absolute', right:10, top:'50%', transform:'translateY(-50%)', background:'none', border:'none', cursor:'pointer', lineHeight:1 }}>
            <Icon name={show ? 'eyeOff' : 'eye'} size={18} color="#9ca3af" />
          </button>
        </div>
      </div>
    );
  }

  /* password strength */
  function strength(pwd) {
    if (!pwd) return null;
    const checks = [pwd.length >= 8, /[A-Z]/.test(pwd), /[0-9]/.test(pwd), /[^A-Za-z0-9]/.test(pwd)];
    const score = checks.filter(Boolean).length;
    if (score <= 1) return { label:'Fraca', color:'#ef4444', width:'25%' };
    if (score === 2) return { label:'Razoável', color:'#f59e0b', width:'50%' };
    if (score === 3) return { label:'Boa', color:'#3b82f6', width:'75%' };
    return { label:'Forte', color:'#16a34a', width:'100%' };
  }

  const str = strength(nova);

  function handleSalvar() {
    if (!nova) { setErro('Informe a nova senha.'); return; }
    if (nova.length < 8) { setErro('A senha deve ter pelo menos 8 caracteres.'); return; }
    if (nova !== confirmar) { setErro('As senhas não coincidem.'); return; }
    setLoading(true);
    setTimeout(() => { setLoading(false); onDone(); }, 700);
  }

  return (
    <div style={{
      minHeight:'100vh', display:'flex', alignItems:'center', justifyContent:'center',
      background:'#1C416B',
    }}>
      <div style={{
        background:'white', borderRadius:12, width:420, padding:'36px 40px',
        boxShadow:'0 20px 60px rgba(0,0,0,0.3)',
      }}>
        {/* Logo */}
        <div style={{ textAlign:'center', marginBottom:28 }}>
          <img src="uploads/WhatsApp_Image_2026-03-16_at_20.39.04_-_Copia-removebg-preview.png" alt="Conexão Psi" style={{ height:48, width:'auto', objectFit:'contain', margin:'0 auto 14px', display:'block' }} />
          <h1 style={{ fontSize:22, fontWeight:700, color:'#111', margin:0 }}>Criar nova senha</h1>
          <p style={{ fontSize:13, color:'#6b7280', margin:'8px 0 0', lineHeight:1.5 }}>
            Por segurança, crie uma nova senha<br />para continuar usando o sistema
          </p>
        </div>

        {/* Fields */}
        <div style={{ display:'flex', flexDirection:'column', gap:16 }}>
          <PasswordField
            label="Nova senha"
            value={nova}
            onChange={setNova}
            show={showNova}
            onToggle={() => setShowNova(s => !s)}
            placeholder="Mínimo 8 caracteres"
          />

          {/* Strength bar */}
          {nova.length > 0 && str && (
            <div style={{ marginTop:-8 }}>
              <div style={{ height:4, background:'#e5e7eb', borderRadius:2, overflow:'hidden' }}>
                <div style={{ height:'100%', width:str.width, background:str.color, borderRadius:2, transition:'width 0.3s, background 0.3s' }} />
              </div>
              <div style={{ fontSize:11, color:str.color, marginTop:4, fontWeight:500 }}>Força da senha: {str.label}</div>
            </div>
          )}

          {/* Password requirements */}
          {nova.length > 0 && (
            <div style={{ background:'#f9fafb', borderRadius:8, padding:'10px 14px', display:'flex', flexDirection:'column', gap:5 }}>
              {[
                { ok: nova.length >= 8,           text: 'Mínimo 8 caracteres' },
                { ok: /[A-Z]/.test(nova),          text: 'Uma letra maiúscula' },
                { ok: /[0-9]/.test(nova),          text: 'Um número' },
                { ok: /[^A-Za-z0-9]/.test(nova),   text: 'Um caractere especial' },
              ].map(req => (
                <div key={req.text} style={{ display:'flex', alignItems:'center', gap:7, fontSize:12, color: req.ok ? '#16a34a' : '#9ca3af' }}>
                  <span style={{ fontSize:14, lineHeight:1 }}>{req.ok ? '✓' : '○'}</span>
                  {req.text}
                </div>
              ))}
            </div>
          )}

          <PasswordField
            label="Confirmar nova senha"
            value={confirmar}
            onChange={setConfirmar}
            show={showConfirmar}
            onToggle={() => setShowConfirmar(s => !s)}
            placeholder="Repita a nova senha"
          />

          {/* Match indicator */}
          {confirmar.length > 0 && (
            <div style={{ fontSize:12, marginTop:-8, color: nova === confirmar ? '#16a34a' : '#ef4444', display:'flex', alignItems:'center', gap:5 }}>
              <span>{nova === confirmar ? '✓' : '✕'}</span>
              {nova === confirmar ? 'Senhas coincidem' : 'Senhas não coincidem'}
            </div>
          )}

          {/* Error */}
          {erro && (
            <div style={{ background:'#fee2e2', border:'1px solid #fca5a5', borderRadius:6, padding:'9px 12px', fontSize:13, color:'#991b1b' }}>
              {erro}
            </div>
          )}
        </div>

        <div style={{ marginTop:22 }}>
          <button onClick={handleSalvar} disabled={loading}
            style={{ width:'100%', padding:'11px', background:C.primary, color:'white', border:'none', borderRadius:6, fontSize:15, fontWeight:600, cursor:'pointer', opacity: loading ? 0.7 : 1 }}>
            {loading ? 'Salvando...' : 'Salvar e continuar'}
          </button>
        </div>
      </div>
    </div>
  );
}

/* ── Toast de inatividade ── */
const INACTIVITY_MS = 10 * 60 * 1000; // 10 min inativo → logout
const WARN_MS       =  1 * 60 * 1000; // aviso 1 min antes

function InactivityManager({ onLogout }) {
  const [visible,   setVisible]   = appState(false);
  const [countdown, setCountdown] = appState(60);
  const logoutTimer = appRef(null);
  const warnTimer   = appRef(null);
  const countTimer  = appRef(null);

  const reset = React.useCallback(() => {
    clearTimeout(logoutTimer.current);
    clearTimeout(warnTimer.current);
    clearInterval(countTimer.current);
    setVisible(false);
    setCountdown(60);

    warnTimer.current = setTimeout(() => {
      setVisible(true);
      let c = 60;
      setCountdown(c);
      countTimer.current = setInterval(() => {
        c--;
        setCountdown(c);
        if (c <= 0) clearInterval(countTimer.current);
      }, 1000);
    }, INACTIVITY_MS - WARN_MS);

    logoutTimer.current = setTimeout(onLogout, INACTIVITY_MS);
  }, []);

  appEffect(() => {
    reset();
    const evts = ['mousemove','keydown','click','touchstart','scroll'];
    evts.forEach(e => window.addEventListener(e, reset, { passive:true }));
    return () => {
      evts.forEach(e => window.removeEventListener(e, reset));
      clearTimeout(logoutTimer.current);
      clearTimeout(warnTimer.current);
      clearInterval(countTimer.current);
    };
  }, [reset]);

  if (!visible) return null;

  return (
    <div style={{ position:'fixed', bottom:24, left:'50%', transform:'translateX(-50%)', zIndex:9999,
      background:'#1e293b', color:'white', borderRadius:10, padding:'14px 20px',
      boxShadow:'0 8px 32px rgba(0,0,0,0.4)', display:'flex', alignItems:'center', gap:14,
      minWidth:360, border:'1px solid rgba(255,255,255,0.08)' }}>
      <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#fbbf24" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink:0 }}>
        <path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/>
        <line x1="12" y1="9" x2="12" y2="13"/>
        <line x1="12" y1="17" x2="12.01" y2="17"/>
      </svg>
      <div style={{ flex:1 }}>
        <div style={{ fontSize:13, fontWeight:600, marginBottom:2 }}>Sessão expirando em {countdown}s</div>
        <div style={{ fontSize:12, color:'rgba(255,255,255,0.55)' }}>Você será desconectado por inatividade.</div>
      </div>
      <button onClick={reset}
        style={{ padding:'7px 16px', background:C.primary, border:'none', borderRadius:6, color:'white', fontSize:13, fontWeight:600, cursor:'pointer', flexShrink:0 }}>
        Continuar
      </button>
    </div>
  );
}

/* ── Main App ── */
function App() {
  const [step, setStep] = appState('login'); // 'login' | 'forgot' | 'changePassword' | 'app'
  const [page, setPage] = appState('dashboard');
  const [modal, setModal] = appState(null);
  const [perfil, setPerfil] = appState('admin');

  function handleLogin({ novaSenha, perfil: p }) {
    setPerfil(p);
    setStep(novaSenha ? 'changePassword' : 'app');
  }

  if (step === 'login')          return <LoginPage onLogin={handleLogin} onForgot={() => setStep('forgot')} />;
  if (step === 'forgot')         return <ForgotPasswordPage onBack={() => setStep('login')} />;
  if (step === 'changePassword') return <ChangePasswordPage onDone={() => setStep('app')} />;

  function closeModal() { setModal(null); }

  const pageMap = {
    dashboard:    <Dashboard setPage={setPage} setModal={setModal} perfil={perfil} />,
    agenda:       <Agenda setModal={setModal} perfil={perfil} />,
    pacientes:    <Pacientes setModal={setModal} />,
    usuarios:     <Sistema />,
    financeiro:   <Financeiro setModal={setModal} />,
    unidades:     <Unidades />,
    relatorios:    <Relatorios />,
    auditoria:    <Auditoria />,
    configuracoes:<Configuracoes />,
    meuperfil:    <MeuPerfil />,
  };

  const doLogout = () => { setStep('login'); setPage('dashboard'); };

  return (
    <div style={{ display:'flex', height:'100vh', overflow:'hidden', fontFamily:"'Inter', system-ui, sans-serif" }}>
      <Sidebar page={page} setPage={setPage} perfil={perfil} onLogout={doLogout} />
      <div style={{ flex:1, display:'flex', flexDirection:'column', minWidth:0, overflow:'hidden' }}>
        {pageMap[page] || pageMap.dashboard}
      </div>
      <InactivityManager onLogout={doLogout} />

      {/* Global modals */}
      {modal === 'novoPaciente'    && <ModalNovoPaciente    onClose={closeModal} />}
      {modal === 'agendarConsulta' && <ModalAgendarConsulta onClose={closeModal} />}
      {modal === 'lancamento'      && <ModalLancamento      onClose={closeModal} />}
    </div>
  );
}

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