// ─── Raiz da aplicação ─────────────────────────────────────────────────────
const { useState: useStateApp, useEffect: useEffectApp } = React;

// ─── Tela de Login ──────────────────────────────────────────────────────────
const LoginScreen = ({ onLogin, initialModo }) => {
  const params0 = new URLSearchParams(window.location.search);
  const resetToken = params0.get('reset_token');

  const [email, setEmail] = useStateApp('');
  const [senha, setSenha] = useStateApp('');
  const [novaSenha, setNovaSenha] = useStateApp('');
  const [confirmarSenha, setConfirmarSenha] = useStateApp('');
  const [erro, setErro] = useStateApp('');
  const [loading, setLoading] = useStateApp(false);
  const [modo, setModo] = useStateApp(resetToken ? 'reset' : (initialModo || 'login')); // 'login' | 'signup' | 'forgot' | 'reset'
  const [nome, setNome] = useStateApp('');
  const [sucesso, setSucesso] = useStateApp('');
  const [mostrarSenha, setMostrarSenha] = useStateApp(false);
  const [mostrarNovaSenha, setMostrarNovaSenha] = useStateApp(false);
  const [mostrarConfirmar, setMostrarConfirmar] = useStateApp(false);

  const C = {
    sage: '#5C8A6E', sageDark: '#2C4A35', sagePale: '#EAF2ED',
    cream: '#F5F0E8', bg: '#F8F5EF', text: '#1A2B1E',
    textMuted: '#8FAA96', border: '#DDD8CE', white: '#FFFFFF',
    red: '#B84040', redLight: '#FFF0F0',
  };

  const trocarModo = (novoModo) => { setModo(novoModo); setErro(''); setSucesso(''); };

  const handleLogin = async (e) => {
    e.preventDefault();
    setErro(''); setLoading(true);
    try {
      const r = await fetch('/api/auth/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({ email, senha }),
      });
      const data = await r.json();
      if (!r.ok) { setErro(data.error || 'Erro ao entrar'); return; }
      onLogin(data);
    } catch { setErro('Erro de conexão'); }
    finally { setLoading(false); }
  };

  const handleSignup = async (e) => {
    e.preventDefault();
    setErro(''); setLoading(true);
    try {
      const r = await fetch('/api/auth/signup', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({ nome, email, senha }),
      });
      const data = await r.json();
      if (!r.ok) { setErro(data.error || 'Erro ao cadastrar'); return; }
      setSucesso('Cadastro recebido! Aguarde aprovação do administrador.');
      setModo('login');
    } catch { setErro('Erro de conexão'); }
    finally { setLoading(false); }
  };

  const handleForgot = async (e) => {
    e.preventDefault();
    setErro(''); setLoading(true);
    try {
      await fetch('/api/auth/forgot-password', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email }),
      });
      setSucesso('Se esse e-mail estiver cadastrado, você receberá um link em breve. Verifique também o spam.');
    } catch { setErro('Erro de conexão'); }
    finally { setLoading(false); }
  };

  const handleReset = async (e) => {
    e.preventDefault();
    setErro('');
    if (novaSenha.length < 8) { setErro('A senha deve ter no mínimo 8 caracteres'); return; }
    if (novaSenha !== confirmarSenha) { setErro('As senhas não coincidem'); return; }
    setLoading(true);
    try {
      const r = await fetch('/api/auth/reset-password', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ token: resetToken, novaSenha }),
      });
      const data = await r.json();
      if (!r.ok) { setErro(data.error || 'Erro ao redefinir senha'); return; }
      setSucesso('Senha redefinida com sucesso! Você já pode entrar.');
      window.history.replaceState({}, '', '/');
      setTimeout(() => trocarModo('login'), 2000);
    } catch { setErro('Erro de conexão'); }
    finally { setLoading(false); }
  };

  const inputStyle = {
    width: '100%', padding: '12px 14px', borderRadius: 10,
    border: `1.5px solid ${C.border}`, fontSize: 14, color: C.text,
    background: C.white, boxSizing: 'border-box', outline: 'none',
  };

  const btnStyle = {
    width: '100%', padding: '13px', borderRadius: 10, border: 'none',
    background: C.sage, color: C.white, fontSize: 15, fontWeight: 700,
    cursor: loading ? 'not-allowed' : 'pointer', opacity: loading ? 0.7 : 1,
    marginTop: 8,
  };

  const EyeIcon = ({ aberto }) => aberto
    ? <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94"/><path d="M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19"/><line x1="1" y1="1" x2="23" y2="23"/></svg>
    : <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>;

  const inputWrap = (input, mostrar, setMostrar) => (
    <div style={{ position: 'relative' }}>
      {React.cloneElement(input, { type: mostrar ? 'text' : 'password', style: { ...input.props.style, paddingRight: 42 } })}
      <button
        type="button"
        onClick={() => setMostrar(v => !v)}
        style={{ position: 'absolute', right: 10, top: '50%', transform: 'translateY(-50%)', background: 'none', border: 'none', cursor: 'pointer', color: C.textMuted, padding: 4, display: 'flex', alignItems: 'center' }}
        tabIndex={-1}
        aria-label={mostrar ? 'Ocultar senha' : 'Mostrar senha'}
      >
        <EyeIcon aberto={mostrar} />
      </button>
    </div>
  );

  const subtitulos = { login: 'Acesso restrito a médicos', signup: 'Criar nova conta', forgot: 'Recuperar acesso', reset: 'Criar nova senha' };

  return (
    <div style={{ minHeight: '100vh', background: C.bg, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 16 }}>
      <div style={{ background: C.white, borderRadius: 20, padding: 36, width: '100%', maxWidth: 380, boxShadow: '0 8px 32px rgba(30,51,38,0.10)', border: `1px solid ${C.border}` }}>
        <div style={{ textAlign: 'center', marginBottom: 28 }}>
          <div style={{ width: 48, height: 48, borderRadius: 14, background: C.sage, display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 12px' }}>
            <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke={C.white} strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round">
              <line x1="8" y1="4.5" x2="8" y2="19.5" />
              <path d="M17.5 4.5 L9 12 L17.5 19.5" />
            </svg>
          </div>
          <h1 style={{ fontSize: 22, fontWeight: 700, color: C.sageDark, fontFamily: 'Lora, serif', margin: 0 }}>KIATI<span style={{ fontWeight: 400 }}>exames</span></h1>
          <p style={{ fontSize: 13, color: C.textMuted, marginTop: 4 }}>{subtitulos[modo]}</p>
        </div>

        {sucesso && <div style={{ background: C.sagePale, border: `1px solid ${C.sage}`, borderRadius: 8, padding: '10px 14px', fontSize: 13, color: C.sageDark, marginBottom: 16 }}>{sucesso}</div>}
        {erro && <div style={{ background: C.redLight, border: `1px solid ${C.red}`, borderRadius: 8, padding: '10px 14px', fontSize: 13, color: C.red, marginBottom: 16 }}>{erro}</div>}

        {/* ── Login ── */}
        {modo === 'login' && (
          <form onSubmit={handleLogin}>
            <div style={{ marginBottom: 14 }}>
              <label style={{ display: 'block', fontSize: 12, fontWeight: 600, color: C.textMuted, marginBottom: 6 }}>E-mail</label>
              <input style={inputStyle} type="email" value={email} onChange={e => setEmail(e.target.value)} placeholder="seu@email.com" required autoFocus />
            </div>
            <div style={{ marginBottom: 6 }}>
              <label style={{ display: 'block', fontSize: 12, fontWeight: 600, color: C.textMuted, marginBottom: 6 }}>Senha</label>
              {inputWrap(<input style={inputStyle} type="password" value={senha} onChange={e => setSenha(e.target.value)} placeholder="••••••••" required />, mostrarSenha, setMostrarSenha)}
            </div>
            <div style={{ textAlign: 'right', marginBottom: 4 }}>
              <button type="button" onClick={() => trocarModo('forgot')} style={{ background: 'none', border: 'none', color: C.sage, cursor: 'pointer', fontSize: 12, padding: 0 }}>Esqueci minha senha</button>
            </div>
            <button type="submit" style={btnStyle} disabled={loading}>{loading ? 'Aguarde...' : 'Entrar'}</button>
          </form>
        )}

        {/* ── Cadastro ── */}
        {modo === 'signup' && (
          <form onSubmit={handleSignup}>
            <div style={{ marginBottom: 14 }}>
              <label style={{ display: 'block', fontSize: 12, fontWeight: 600, color: C.textMuted, marginBottom: 6 }}>Nome completo</label>
              <input style={inputStyle} type="text" value={nome} onChange={e => setNome(e.target.value)} placeholder="Dr. João Silva" required autoFocus />
            </div>
            <div style={{ marginBottom: 14 }}>
              <label style={{ display: 'block', fontSize: 12, fontWeight: 600, color: C.textMuted, marginBottom: 6 }}>E-mail</label>
              <input style={inputStyle} type="email" value={email} onChange={e => setEmail(e.target.value)} placeholder="seu@email.com" required />
            </div>
            <div style={{ marginBottom: 6 }}>
              <label style={{ display: 'block', fontSize: 12, fontWeight: 600, color: C.textMuted, marginBottom: 6 }}>Senha</label>
              {inputWrap(<input style={inputStyle} type="password" value={senha} onChange={e => setSenha(e.target.value)} placeholder="Mínimo 8 caracteres" required />, mostrarSenha, setMostrarSenha)}
            </div>
            <button type="submit" style={btnStyle} disabled={loading}>{loading ? 'Aguarde...' : 'Criar conta'}</button>
          </form>
        )}

        {/* ── Esqueci a senha ── */}
        {modo === 'forgot' && !sucesso && (
          <form onSubmit={handleForgot}>
            <p style={{ fontSize: 13, color: C.textMuted, marginBottom: 16, lineHeight: 1.6 }}>
              Digite seu e-mail e enviaremos um link para criar uma nova senha.
            </p>
            <div style={{ marginBottom: 6 }}>
              <label style={{ display: 'block', fontSize: 12, fontWeight: 600, color: C.textMuted, marginBottom: 6 }}>E-mail</label>
              <input style={inputStyle} type="email" value={email} onChange={e => setEmail(e.target.value)} placeholder="seu@email.com" required autoFocus />
            </div>
            <button type="submit" style={btnStyle} disabled={loading}>{loading ? 'Enviando...' : 'Enviar link'}</button>
          </form>
        )}

        {/* ── Redefinir senha ── */}
        {modo === 'reset' && !sucesso && (
          <form onSubmit={handleReset}>
            <div style={{ marginBottom: 14 }}>
              <label style={{ display: 'block', fontSize: 12, fontWeight: 600, color: C.textMuted, marginBottom: 6 }}>Nova senha</label>
              {inputWrap(<input style={inputStyle} type="password" value={novaSenha} onChange={e => setNovaSenha(e.target.value)} placeholder="Mínimo 8 caracteres" required autoFocus />, mostrarNovaSenha, setMostrarNovaSenha)}
            </div>
            <div style={{ marginBottom: 6 }}>
              <label style={{ display: 'block', fontSize: 12, fontWeight: 600, color: C.textMuted, marginBottom: 6 }}>Confirmar senha</label>
              {inputWrap(<input style={inputStyle} type="password" value={confirmarSenha} onChange={e => setConfirmarSenha(e.target.value)} placeholder="Repita a senha" required />, mostrarConfirmar, setMostrarConfirmar)}
            </div>
            <button type="submit" style={btnStyle} disabled={loading}>{loading ? 'Salvando...' : 'Salvar nova senha'}</button>
          </form>
        )}

        {/* ── Links de navegação entre modos ── */}
        <p style={{ textAlign: 'center', fontSize: 13, color: C.textMuted, marginTop: 20 }}>
          {modo === 'login' && <><span>Não tem conta? </span><button onClick={() => trocarModo('signup')} style={{ background: 'none', border: 'none', color: C.sage, cursor: 'pointer', fontWeight: 600, fontSize: 13 }}>Cadastre-se</button></>}
          {modo === 'signup' && <><span>Já tem conta? </span><button onClick={() => trocarModo('login')} style={{ background: 'none', border: 'none', color: C.sage, cursor: 'pointer', fontWeight: 600, fontSize: 13 }}>Entrar</button></>}
          {(modo === 'forgot' || modo === 'reset') && <button onClick={() => trocarModo('login')} style={{ background: 'none', border: 'none', color: C.sage, cursor: 'pointer', fontWeight: 600, fontSize: 13 }}>← Voltar para o login</button>}
        </p>
      </div>
    </div>
  );
};

// ─── App principal ──────────────────────────────────────────────────────────
const App = () => {
  const params = new URLSearchParams(window.location.search);
  const view  = params.get('view');
  const envId = params.get('env');

  const [medico, setMedico] = useStateApp(null);
  const [verificando, setVerificando] = useStateApp(true);

  useEffectApp(() => {
    if (view === 'paciente') { setVerificando(false); return; }
    fetch('/api/auth/me', { credentials: 'include' })
      .then(r => r.ok ? r.json() : null)
      .then(data => { setMedico(data); setVerificando(false); })
      .catch(() => setVerificando(false));
  }, []);

  if (view === 'paciente') return React.createElement(PatientArea, { envId });
  if (verificando) return React.createElement('div', { style: { minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', background: '#F8F5EF', color: '#8FAA96', fontSize: 15 } }, 'Carregando...');
  if (!medico) return React.createElement(LoginScreen, { onLogin: setMedico });
  return React.createElement(DoctorApp, { medico, onLogout: () => {
    fetch('/api/auth/logout', { method: 'POST', credentials: 'include' }).then(() => setMedico(null));
  }});
};

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(React.createElement(App, null));
