import { useState, useEffect } from 'react';
import { Link, useSearchParams } from 'react-router-dom';
import AuthBgCol from '../components/AuthBgCol.jsx';

export default function VerifyEmail() {
  const [params]  = useSearchParams();
  const token     = params.get('token') || '';
  const [status,  setStatus]  = useState('loading'); // 'loading' | 'ok' | 'error'
  const [errMsg,  setErrMsg]  = useState('');
  const [appInfo, setAppInfo] = useState({ appName: 'Crowdlending Tracker', iconUrl: null });

  useEffect(() => {
    fetch('/api/app-info').then(r => r.json()).then(d => setAppInfo(d)).catch(() => {});
  }, []);

  useEffect(() => {
    if (!token) { setStatus('error'); setErrMsg('Lien de vérification invalide ou manquant.'); return; }
    fetch(`/api/auth/verify-email?token=${encodeURIComponent(token)}`)
      .then(async r => {
        const data = await r.json();
        if (!r.ok) { setErrMsg(data.error || 'Lien invalide.'); setStatus('error'); }
        else setStatus('ok');
      })
      .catch(() => { setErrMsg('Impossible de joindre le serveur.'); setStatus('error'); });
  }, [token]);

  return (
    <div style={{ display: 'flex', minHeight: '100dvh' }}>

      <AuthBgCol appInfo={appInfo} />


      <div style={{
        flex: '1 1 50%', display: 'flex', flexDirection: 'column',
        alignItems: 'center', justifyContent: 'center',
        padding: '48px 24px', background: 'var(--background, #fff)', minWidth: 0,
      }}>
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 10, marginBottom: 32 }}>
          {appInfo.iconUrl && <img src={appInfo.iconUrl} alt={appInfo.appName} width={52} height={52} style={{ borderRadius: 12 }} />}
          <span style={{ fontSize: 20, fontWeight: 700, color: 'var(--text)', letterSpacing: '-0.4px' }}>{appInfo.appName}</span>
        </div>

        <div style={{ width: '100%', maxWidth: 360, textAlign: 'center' }}>

          {status === 'loading' && (
            <p style={{ color: 'var(--text-muted)' }}>Vérification en cours…</p>
          )}

          {status === 'ok' && (
            <>
              <div style={{
                width: 56, height: 56, borderRadius: '50%',
                background: 'var(--success-bg, #f0fdf4)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                margin: '0 auto 20px',
              }}>
                <svg width="26" height="26" viewBox="0 0 24 24" fill="none">
                  <path d="M20 6L9 17l-5-5" stroke="var(--success, #16a34a)" strokeWidth="2.2"
                    strokeLinecap="round" strokeLinejoin="round"/>
                </svg>
              </div>
              <h1 style={{ margin: '0 0 10px', fontSize: 24, fontWeight: 700, color: 'var(--text)' }}>
                Email vérifié !
              </h1>
              <p style={{ margin: '0 0 28px', color: 'var(--text-muted)', fontSize: 14, lineHeight: 1.6 }}>
                Votre adresse email a bien été confirmée. Vous pouvez maintenant vous connecter.
              </p>
              <Link to="/login" style={{
                display: 'block', width: '100%', padding: '11px 0',
                background: 'var(--primary, #1e40af)', color: '#fff',
                borderRadius: 8, fontSize: 15, fontWeight: 600,
                textDecoration: 'none',
              }}>
                Se connecter
              </Link>
            </>
          )}

          {status === 'error' && (
            <>
              <div style={{
                width: 56, height: 56, borderRadius: '50%',
                background: 'var(--danger-bg, #fef2f2)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                margin: '0 auto 20px',
              }}>
                <svg width="26" height="26" viewBox="0 0 24 24" fill="none">
                  <path d="M12 9v4m0 4h.01M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z"
                    stroke="var(--danger, #dc2626)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
                </svg>
              </div>
              <h1 style={{ margin: '0 0 10px', fontSize: 22, fontWeight: 700, color: 'var(--text)' }}>
                Lien invalide
              </h1>
              <p style={{ margin: '0 0 28px', color: 'var(--text-muted)', fontSize: 14, lineHeight: 1.6 }}>
                {errMsg}
              </p>
              <Link to="/login" style={{
                display: 'block', width: '100%', padding: '11px 0',
                background: 'var(--primary, #1e40af)', color: '#fff',
                borderRadius: 8, fontSize: 15, fontWeight: 600,
                textDecoration: 'none',
              }}>
                Retour à la connexion
              </Link>
            </>
          )}

        </div>
      </div>
    </div>
  );
}
