
// AuthFlow.jsx — Login / Registro / Recuperar contraseña

const AuthFlow = ({ onSuccess, onBack, context, box, defaultRole, initialScreen }) => {
  const [screen, setScreen] = React.useState(initialScreen || 'login'); // login | register | forgot

  // Debug: log the received defaultRole prop
  console.log('🔐 AuthFlow received defaultRole:', defaultRole);

  return (
    <div style={authStyles.root}>
      {screen === 'login'    && <LoginScreen    onRegister={() => setScreen('register')} onForgot={() => setScreen('forgot')} onSuccess={onSuccess} onBack={onBack} context={context} box={box} defaultRole={defaultRole} />}
      {screen === 'register' && <RegisterScreen onLogin={() => setScreen('login')} onSuccess={onSuccess} onBack={() => setScreen('login')} context={context} box={box} defaultRole={defaultRole} />}
      {screen === 'forgot'   && <ForgotScreen   onBack={() => setScreen('login')} />}
      <Footer />
    </div>
  );
};

// ─── LOGIN ────────────────────────────────────────────────────────────────────
const LoginScreen = ({ onRegister, onForgot, onSuccess, onBack, context, box, defaultRole }) => {
  const [email, setEmail] = React.useState('');
  const [password, setPassword] = React.useState('');
  const [showPass, setShowPass] = React.useState(false);
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState('');
  const [role, setRole] = React.useState(defaultRole || 'professional'); // professional | owner | admin
  const isMobile = useWindowWidth() <= 768;

  const handleLogin = async () => {
    if (!email || !password) { setError('Completa todos los campos.'); return; }
    if (!email.includes('@')) { setError('Ingresa un email válido.'); return; }
    setError('');
    setLoading(true);
    try {
      const response = await fetch('https://lokat.fly.dev/api/auth/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, password })
      });
      const data = await response.json();
      if (!response.ok) {
        setError(data.error || 'Error en inicio de sesión');
        setLoading(false);
        return;
      }
      localStorage.setItem('lokat_token', data.accessToken);
      localStorage.setItem('lokat_user', JSON.stringify(data.user));
      setLoading(false);
      onSuccess(data.user.role);
    } catch (err) {
      setError('Error de conexión. Intenta de nuevo.');
      setLoading(false);
    }
  };

  return (
    <div style={authStyles.page}>
      <button style={authStyles.backBtn} onClick={onBack}>
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="m15 18-6-6 6-6"/></svg>
        Volver
      </button>

      <div style={{...authStyles.card, padding: isMobile ? '24px 18px' : '36px 32px'}}>
        {/* LOGO */}
        <div style={authStyles.logoRow}>
          <img src="uploads/lokat_color.png" alt="Lokat" style={{height:36, objectFit:'contain'}} />
        </div>

        {context === 'booking' && box && (
          <div style={authStyles.bookingContext}>
            <span style={authStyles.bookingContextIcon}>🏥</span>
            <div>
              <div style={authStyles.bookingContextTitle}>Para reservar: {box.name}</div>
              <div style={authStyles.bookingContextSub}>{box.location} · ${box.price.toLocaleString()}/hr — Inicia sesión o crea tu cuenta para continuar</div>
            </div>
          </div>
        )}
        <h2 style={authStyles.title}>Iniciar sesión</h2>
        <p style={authStyles.subtitle}>Bienvenido de vuelta al marketplace médico</p>

        {/* ROLE SELECTOR */}
        {!defaultRole && (
          <div style={authStyles.roleRow}>
            <button style={{...authStyles.roleBtn, ...(role === 'professional' ? authStyles.roleBtnActive : {})}} onClick={() => setRole('professional')}>
              <span style={authStyles.roleIcon}>🩺</span> Profesional
            </button>
            <button style={{...authStyles.roleBtn, ...(role === 'owner' ? authStyles.roleBtnActive : {})}} onClick={() => setRole('owner')}>
              <span style={authStyles.roleIcon}>🏥</span> Propietario
            </button>
          </div>
        )}

        {/* FORM */}
        <div style={authStyles.formGroup}>
          <label style={authStyles.label}>Correo electrónico</label>
          <input
            style={{...authStyles.input, ...(error && !email ? authStyles.inputError : {})}}
            type="email"
            placeholder="tu@email.cl"
            value={email}
            onChange={e => { setEmail(e.target.value); setError(''); }}
            onKeyDown={e => e.key === 'Enter' && handleLogin()}
          />
        </div>

        <div style={authStyles.formGroup}>
          <div style={authStyles.labelRow}>
            <label style={authStyles.label}>Contraseña</label>
            <button style={authStyles.forgotLink} onClick={onForgot}>¿Olvidaste tu contraseña?</button>
          </div>
          <div style={authStyles.inputWrapper}>
            <input
              style={{...authStyles.input, ...(error && !password ? authStyles.inputError : {}), paddingRight: 44}}
              type={showPass ? 'text' : 'password'}
              placeholder="••••••••"
              value={password}
              onChange={e => { setPassword(e.target.value); setError(''); }}
              onKeyDown={e => e.key === 'Enter' && handleLogin()}
            />
            <button style={authStyles.eyeBtn} onClick={() => setShowPass(!showPass)}>
              {showPass
                ? <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#adb5bd" strokeWidth="2"><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="#adb5bd" strokeWidth="2"><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>
              }
            </button>
          </div>
        </div>

        {error && <div style={authStyles.errorBox}>{error}</div>}

        <button style={{...authStyles.primaryBtn, opacity: loading ? 0.8 : 1}} onClick={handleLogin} disabled={loading}>
          {loading
            ? <span style={authStyles.loadingRow}><span style={authStyles.spinner}></span> Ingresando...</span>
            : 'Ingresar'}
        </button>

        <div style={authStyles.divider}><span>o continúa con</span></div>

        {/* SOCIAL */}
        <div style={authStyles.socialRow}>
          <button style={authStyles.socialBtn} onClick={() => { window.location.href = 'https://lokat.fly.dev/api/auth/google'; }}>
            <svg width="18" height="18" viewBox="0 0 24 24"><path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"/><path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"/><path fill="#FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"/><path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"/></svg>
            Google
          </button>
          <button style={authStyles.socialBtn}>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="#0077B5"><path d="M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433a2.062 2.062 0 0 1-2.063-2.065 2.064 2.064 0 1 1 2.063 2.065zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z"/></svg>
            LinkedIn
          </button>
        </div>

        <p style={authStyles.switchText}>
          ¿No tienes cuenta?{' '}
          <button style={authStyles.switchLink} onClick={onRegister}>Regístrate gratis</button>
        </p>
      </div>
    </div>
  );
};

// ─── REGISTER ─────────────────────────────────────────────────────────────────
const RegisterScreen = ({ onLogin, onSuccess, onBack, context, box, defaultRole }) => {
  const [role, setRole] = React.useState(defaultRole || 'professional');
  const [form, setForm] = React.useState({ name: '', email: '', password: '', phone: '', rut: '', companyName: '', address: '', specialty: '', run_profesional: '', rnpi_declared: false });
  const [showPass, setShowPass] = React.useState(false);
  const [loading, setLoading] = React.useState(false);
  const [errors, setErrors] = React.useState({});
  const [agreed, setAgreed] = React.useState(false);
  const [customSpecialty, setCustomSpecialty] = React.useState('');
  const [showLegal, setShowLegal] = React.useState(null); // null | 'terms' | 'privacy'
  const isMobile = useWindowWidth() <= 768;

  // ── Phone helpers ────────────────────────────────────────────────────────────
  const PHONE_PREFIX = '+56 9 ';

  const handlePhoneFocus = () => {
    if (!form.phone) set('phone', PHONE_PREFIX);
  };

  const handlePhoneChange = (e) => {
    const raw = e.target.value;
    // Restore prefix if user deleted into it
    if (!raw.startsWith(PHONE_PREFIX)) {
      set('phone', PHONE_PREFIX);
      return;
    }
    // Only keep digits after the prefix, max 8
    const digits = raw.slice(PHONE_PREFIX.length).replace(/\D/g, '').slice(0, 8);
    // Auto-format: XXXX XXXX
    const formatted = digits.length > 4 ? digits.slice(0, 4) + ' ' + digits.slice(4) : digits;
    set('phone', PHONE_PREFIX + formatted);
  };

  const isPhoneValid = (v) => /^\+56 9 \d{4} \d{4}$/.test(v);

  const validate = () => {
    const e = {};
    if (!form.name.trim()) e.name = "Requerido";
    if (!form.email.includes("@")) e.email = "Email inválido";
    if (form.password.length < 6) e.password = "Mínimo 6 caracteres";
    if (!isPhoneValid(form.phone)) e.phone = "Ingresa un número válido: +56 9 XXXX XXXX";
    if (role === "owner" && !form.companyName.trim()) e.companyName = "Requerido";
    if (role === "professional" && !form.rnpi_declared) e.rnpi_declared = "Debes declarar tu inscripción en el RNPI para continuar";
    if (!agreed) e.agreed = "Debes aceptar los términos";
    return e;
  };
  const handleRegister = async () => {
    const e = validate();
    if (Object.keys(e).length) { setErrors(e); return; }
    setLoading(true);
    try {
      const payload = {
        email: form.email,
        password: form.password,
        fullName: form.name,
        role: role
      };
      if (role === "owner") {
        payload.companyName = form.companyName;
        payload.phone = form.phone;
        if (form.address.trim()) payload.address = form.address;
      }
      if (role === "professional") {
        if (form.specialty)       payload.specialty       = form.specialty;
        if (form.run_profesional) payload.run_profesional = form.run_profesional;
        payload.rnpi_declared = form.rnpi_declared;
      }
      const response = await fetch("https://lokat.fly.dev/api/auth/register", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload)
      });
      const data = await response.json();
      if (!response.ok) {
        setErrors({ submit: data.error || "Error en registro" });
        setLoading(false);
        return;
      }
      const userData = data.user;
      if (role === "owner") {
        userData.companyName = form.companyName;
        userData.phone = form.phone;
        userData.address = form.address || "";
      }
      if (role === "professional") {
        userData.specialty       = form.specialty       || "";
        userData.run_profesional = form.run_profesional || "";
        userData.rnpi_declared   = form.rnpi_declared   || false;
      }
      localStorage.setItem("lokat_token", data.accessToken);
      localStorage.setItem("lokat_user", JSON.stringify(userData));
      setLoading(false);
      onSuccess(userData.role);
    } catch (err) {
      setErrors({ submit: "Error de conexión. Intenta de nuevo." });
      setLoading(false);
    }
  };

  const set = (k, v) => { setForm(p => ({...p, [k]: v})); setErrors(p => ({...p, [k]: undefined})); };

  if (showLegal === 'terms')   return <TermsScreen   onBack={() => setShowLegal(null)} onNavigate={setShowLegal} />;
  if (showLegal === 'privacy') return <PrivacyScreen onBack={() => setShowLegal(null)} onNavigate={setShowLegal} />;

  return (
    <div style={authStyles.page}>
      <button style={authStyles.backBtn} onClick={onBack}>
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="m15 18-6-6 6-6"/></svg>
        Volver
      </button>
      <div style={{...authStyles.card, padding: isMobile ? '24px 18px' : '36px 32px'}}>
        <div style={authStyles.logoRow}>
          <img src="uploads/lokat_color.png" alt="Lokat" style={{height:36, objectFit:'contain'}} />
        </div>
        {context === 'booking' && box && (
          <div style={authStyles.bookingContext}>
            <span style={authStyles.bookingContextIcon}>🏥</span>
            <div>
              <div style={authStyles.bookingContextTitle}>Para reservar: {box.name}</div>
              <div style={authStyles.bookingContextSub}>{box.location} · ${box.price.toLocaleString()}/hr — Crea tu cuenta gratis para continuar</div>
            </div>
          </div>
        )}
        <h2 style={authStyles.title}>Crear cuenta</h2>
        <p style={authStyles.subtitle}>Únete al marketplace médico de Chile</p>

        {/* ROLE */}
        {!defaultRole && (
          <div style={authStyles.roleRow}>
            <button style={{...authStyles.roleBtn, ...(role === 'professional' ? authStyles.roleBtnActive : {})}} onClick={() => setRole('professional')}>
              <span style={authStyles.roleIcon}>🩺</span> Profesional
            </button>
            <button style={{...authStyles.roleBtn, ...(role === 'owner' ? authStyles.roleBtnActive : {})}} onClick={() => setRole('owner')}>
              <span style={authStyles.roleIcon}>🏥</span> Propietario
            </button>
          </div>
        )}

        <div style={authStyles.formGroup}>
          <label style={authStyles.label}>Nombre completo</label>
          <input style={{...authStyles.input, ...(errors.name ? authStyles.inputError : {})}} placeholder="Dr. Juan Pérez" value={form.name} onChange={e => set('name', e.target.value)} />
          {errors.name && <span style={authStyles.fieldError}>{errors.name}</span>}
        </div>

        <div style={authStyles.formGroup}>
          <label style={authStyles.label}>Correo electrónico</label>
          <input style={{...authStyles.input, ...(errors.email ? authStyles.inputError : {})}} type="email" placeholder="tu@email.cl" value={form.email} onChange={e => set('email', e.target.value)} />
          {errors.email && <span style={authStyles.fieldError}>{errors.email}</span>}
        </div>

        <div style={{display:'flex', gap:12}}>
          <div style={{...authStyles.formGroup, flex:1}}>
            <label style={authStyles.label}>Teléfono</label>
            <input
              style={{...authStyles.input, ...(errors.phone ? authStyles.inputError : {})}}
              type="tel"
              placeholder="+56 9 XXXX XXXX"
              value={form.phone}
              onFocus={handlePhoneFocus}
              onChange={handlePhoneChange}
              maxLength={15}
            />
            {errors.phone && <span style={authStyles.fieldError}>{errors.phone}</span>}
          </div>
          {role === 'professional' && (
            <div style={{...authStyles.formGroup, flex:1}}>
              <label style={authStyles.label}>RUT</label>
              <input style={authStyles.input} placeholder="12.345.678-9" value={form.rut} onChange={e => set('rut', e.target.value)} />
            </div>
          )}
        </div>

        {role === 'professional' && (
          <>
            <div style={authStyles.formGroup}>
              <label style={authStyles.label}>Especialidad <span style={{color:'#adb5bd', fontWeight:400}}>(opcional)</span></label>
              <select style={authStyles.input} value={form.specialty} onChange={e => set('specialty', e.target.value)}>
                <option value="">Seleccionar especialidad</option>
                {['Medicina General','Odontología','Kinesiología','Psicología','Nutrición','Fonoaudiología','Dermatología','Otra'].map(s => (
                  <option key={s} value={s}>{s}</option>
                ))}
              </select>
            </div>

            <div style={authStyles.formGroup}>
              <label style={authStyles.label}>RUN profesional <span style={{color:'#adb5bd', fontWeight:400}}>(opcional)</span></label>
              <input
                style={authStyles.input}
                placeholder="12345678"
                value={form.run_profesional}
                onChange={e => set('run_profesional', e.target.value)}
              />
              <span style={{fontSize:11, color:'#636e72', marginTop:4, display:'block'}}>
                Puedes verificar tu inscripción en{' '}
                <a href="https://rnpi.superdesalud.gob.cl" target="_blank" rel="noopener noreferrer" style={{color:'#0984e3', textDecoration:'none', fontWeight:600}}>
                  rnpi.superdesalud.gob.cl
                </a>
              </span>
            </div>

            <div style={{marginBottom: 12}}>
              <div
                style={{display:'flex', alignItems:'flex-start', gap:10, cursor:'pointer', padding:'10px 12px', borderRadius:10, border: `1.5px solid ${errors.rnpi_declared ? '#dc3545' : form.rnpi_declared ? '#0984e3' : '#dee2e6'}`, background: form.rnpi_declared ? '#e3f0fc' : '#fafbfc'}}
                onClick={() => { setForm(p => ({...p, rnpi_declared: !p.rnpi_declared})); setErrors(p => ({...p, rnpi_declared: undefined})); }}
              >
                <div style={{...authStyles.checkbox, ...(form.rnpi_declared ? authStyles.checkboxChecked : {}), flexShrink:0, marginTop:1}}>
                  {form.rnpi_declared && <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="3"><polyline points="20 6 9 17 4 12"/></svg>}
                </div>
                <span style={{fontSize:13, color:'#2D3436', lineHeight:1.5}}>
                  Declaro estar inscrito en el <strong>Registro Nacional de Prestadores Individuales de Salud (RNPI)</strong>
                </span>
              </div>
              {errors.rnpi_declared && <span style={{...authStyles.fieldError, marginTop:4, display:'block'}}>{errors.rnpi_declared}</span>}
            </div>
          </>
        )}

        {role === "owner" && (
          <>
            <div style={authStyles.formGroup}>
              <label style={authStyles.label}>Nombre de empresa/clínica *</label>
              <input style={{...authStyles.input, ...(errors.companyName ? authStyles.inputError : {})}} placeholder="Clínica Ejemplo S.A." value={form.companyName} onChange={e => set("companyName", e.target.value)} />
              {errors.companyName && <span style={authStyles.fieldError}>{errors.companyName}</span>}
            </div>

            <div style={authStyles.formGroup}>
              <label style={authStyles.label}>Dirección</label>
              <input style={authStyles.input} placeholder="Calle Principal 123, Suite 500" value={form.address} onChange={e => set("address", e.target.value)} />
            </div>

            <div style={authStyles.formGroup}>
              <label style={authStyles.label}>RUT empresa</label>
              <input style={authStyles.input} placeholder="12.345.678-9" value={form.rut} onChange={e => set("rut", e.target.value)} />
            </div>

            <div style={authStyles.formGroup}>
              {(() => {
                const OWNER_SPECIALTIES = ['Dental', 'Kinesiología', 'Psicología', 'Medicina General', 'Dermatología', 'Nutrición'];
                const showCustomInput = form.specialty !== '' && !OWNER_SPECIALTIES.includes(form.specialty);
                return (
                  <>
                    <label style={authStyles.label}>Especialidad principal <span style={{color:'#adb5bd', fontWeight:400}}>(opcional)</span></label>
                    <select
                      style={authStyles.input}
                      value={showCustomInput ? 'otro' : form.specialty}
                      onChange={e => {
                        if (e.target.value === 'otro') {
                          setCustomSpecialty('');
                          set('specialty', 'otro');
                        } else {
                          setCustomSpecialty('');
                          set('specialty', e.target.value);
                        }
                      }}
                    >
                      <option value="">Seleccionar especialidad</option>
                      {OWNER_SPECIALTIES.map(s => <option key={s} value={s}>{s}</option>)}
                      <option value="otro">Otro</option>
                    </select>
                    {showCustomInput && (
                      <input
                        style={{...authStyles.input, marginTop: 8}}
                        placeholder="Escribe tu especialidad"
                        value={customSpecialty}
                        onChange={e => {
                          setCustomSpecialty(e.target.value);
                          set('specialty', e.target.value);
                        }}
                      />
                    )}
                  </>
                );
              })()}
            </div>
          </>
        )}

        <div style={authStyles.formGroup}>
          <label style={authStyles.label}>Contraseña</label>
          <div style={authStyles.inputWrapper}>
            <input style={{...authStyles.input, ...(errors.password ? authStyles.inputError : {}), paddingRight: 44}} type={showPass ? 'text' : 'password'} placeholder="Mínimo 6 caracteres" value={form.password} onChange={e => set('password', e.target.value)} />
            <button style={authStyles.eyeBtn} onClick={() => setShowPass(!showPass)}>
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#adb5bd" strokeWidth="2"><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>
            </button>
          </div>
          {errors.password && <span style={authStyles.fieldError}>{errors.password}</span>}
          {/* STRENGTH BAR */}
          {form.password.length > 0 && (
            <div style={authStyles.strengthBar}>
              <div style={{...authStyles.strengthFill, width: `${Math.min(form.password.length / 12 * 100, 100)}%`, background: form.password.length < 6 ? '#dc3545' : form.password.length < 10 ? '#ffc107' : '#28a745'}}></div>
            </div>
          )}
        </div>

        <div style={authStyles.checkRow}>
          <div style={{...authStyles.checkbox, ...(agreed ? authStyles.checkboxChecked : {})}} onClick={() => { setAgreed(!agreed); setErrors(p => ({...p, agreed: undefined})); }}>
            {agreed && <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="3"><polyline points="20 6 9 17 4 12"/></svg>}
          </div>
          <span style={authStyles.checkLabel}>Acepto los <button style={authStyles.termsLink} onClick={() => setShowLegal('terms')}>Términos y Condiciones</button> y la <button style={authStyles.termsLink} onClick={() => setShowLegal('privacy')}>Política de Privacidad</button></span>
        </div>
        {errors.agreed && <span style={{...authStyles.fieldError, marginTop: -8}}>{errors.agreed}</span>}
        {errors.submit && <div style={authStyles.errorBox}>{errors.submit}</div>}

        <button style={{...authStyles.primaryBtn, marginTop: 8, opacity: loading ? 0.8 : 1}} onClick={handleRegister} disabled={loading}>
          {loading ? <span style={authStyles.loadingRow}><span style={authStyles.spinner}></span> Creando cuenta...</span> : 'Crear cuenta gratis'}
        </button>

        <p style={authStyles.switchText}>
          ¿Ya tienes cuenta?{' '}
          <button style={authStyles.switchLink} onClick={onLogin}>Inicia sesión</button>
        </p>
      </div>
    </div>
  );
};

// ─── FORGOT PASSWORD ──────────────────────────────────────────────────────────
const ForgotScreen = ({ onBack }) => {
  const isMobile = useWindowWidth() <= 768;
  const [step, setStep] = React.useState(1); // 1: email | 2: reset code and password
  const [email, setEmail] = React.useState('');
  const [code, setCode] = React.useState('');
  const [newPassword, setNewPassword] = React.useState('');
  const [confirmPassword, setConfirmPassword] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const [errors, setErrors] = React.useState({});
  const [showPassword, setShowPassword] = React.useState(false);
  const [successMsg, setSuccessMsg] = React.useState('');

  const handleSendCode = async () => {
    if (!email.includes('@')) { setErrors({ email: 'Email inválido' }); return; }
    setErrors({});
    setLoading(true);
    try {
      const response = await fetch('https://lokat.fly.dev/api/auth/forgot-password', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email })
      });
      const data = await response.json();
      setLoading(false);
      if (response.ok) {
        setStep(2);
      } else {
        setErrors({ submit: data.error || 'Error al enviar código' });
      }
    } catch (err) {
      setErrors({ submit: 'Error de conexión. Intenta de nuevo.' });
      setLoading(false);
    }
  };

  const handleResetPassword = async () => {
    const e = {};
    if (!code.trim()) e.code = 'Requerido';
    if (!newPassword) e.newPassword = 'Requerido';
    if (!confirmPassword) e.confirmPassword = 'Requerido';
    if (newPassword && newPassword.length < 6) e.newPassword = 'Mínimo 6 caracteres';
    if (newPassword !== confirmPassword) e.confirmPassword = 'Las contraseñas no coinciden';
    if (Object.keys(e).length) { setErrors(e); return; }

    setErrors({});
    setLoading(true);
    try {
      const response = await fetch('https://lokat.fly.dev/api/auth/reset-password', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, code, newPassword })
      });
      const data = await response.json();
      setLoading(false);
      if (response.ok) {
        setSuccessMsg('✅ Contraseña cambiada exitosamente. Redirigiendo...');
        setTimeout(() => onBack(), 2000);
      } else {
        setErrors({ submit: data.error || 'Error al restablecer contraseña' });
      }
    } catch (err) {
      setErrors({ submit: 'Error de conexión. Intenta de nuevo.' });
      setLoading(false);
    }
  };

  return (
    <div style={authStyles.page}>
      <button style={authStyles.backBtn} onClick={onBack}>
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="m15 18-6-6 6-6"/></svg>
        Volver
      </button>
      <div style={{...authStyles.card, padding: isMobile ? '24px 18px' : '36px 32px'}}>
        <div style={authStyles.logoRow}>
          <img src="uploads/lokat_color.png" alt="Lokat" style={{height:36, objectFit:'contain'}} />
        </div>

        {step === 1 ? (
          <>
            <div style={{fontSize: 40, textAlign: 'center', marginBottom: 12}}>🔑</div>
            <h2 style={authStyles.title}>Recuperar contraseña</h2>
            <p style={authStyles.subtitle}>Ingresa tu email para recibir un código de reset.</p>
            {errors.submit && <div style={authStyles.errorBox}>{errors.submit}</div>}
            <div style={authStyles.formGroup}>
              <label style={authStyles.label}>Correo electrónico</label>
              <input style={{...authStyles.input, ...(errors.email ? authStyles.inputError : {})}} type="email" placeholder="tu@email.cl" value={email} onChange={e => { setEmail(e.target.value); setErrors(p => ({...p, email: undefined})); }} onKeyDown={e => e.key === 'Enter' && handleSendCode()} />
              {errors.email && <span style={authStyles.fieldError}>{errors.email}</span>}
            </div>
            <button style={{...authStyles.primaryBtn, opacity: loading ? 0.8 : 1}} onClick={handleSendCode} disabled={loading}>
              {loading ? <span style={authStyles.loadingRow}><span style={authStyles.spinner}></span> Enviando...</span> : 'Enviar código'}
            </button>
          </>
        ) : (
          <>
            <div style={{fontSize: 40, textAlign: 'center', marginBottom: 12}}>✉️</div>
            <h2 style={authStyles.title}>Restablecer contraseña</h2>
            <p style={authStyles.subtitle}>Ingresa el código que recibiste y tu nueva contraseña.</p>
            {errors.submit && <div style={authStyles.errorBox}>{errors.submit}</div>}
            {successMsg && <div style={{...authStyles.errorBox, background: '#d4edda', borderColor: '#c3e6cb', color: '#155724'}}>{successMsg}</div>}

            <div style={authStyles.formGroup}>
              <label style={authStyles.label}>Código (6 dígitos)</label>
              <input style={{...authStyles.input, ...(errors.code ? authStyles.inputError : {})}} type="text" placeholder="000000" value={code} onChange={e => { setCode(e.target.value); setErrors(p => ({...p, code: undefined})); }} maxLength="6" />
              {errors.code && <span style={authStyles.fieldError}>{errors.code}</span>}
            </div>

            <div style={authStyles.formGroup}>
              <label style={authStyles.label}>Nueva contraseña</label>
              <div style={authStyles.inputWrapper}>
                <input style={{...authStyles.input, ...(errors.newPassword ? authStyles.inputError : {}), paddingRight: 44}} type={showPassword ? 'text' : 'password'} placeholder="Mínimo 6 caracteres" value={newPassword} onChange={e => { setNewPassword(e.target.value); setErrors(p => ({...p, newPassword: undefined})); }} />
                <button style={authStyles.eyeBtn} onClick={() => setShowPassword(!showPassword)}>
                  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#adb5bd" strokeWidth="2"><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>
                </button>
              </div>
              {errors.newPassword && <span style={authStyles.fieldError}>{errors.newPassword}</span>}
            </div>

            <div style={authStyles.formGroup}>
              <label style={authStyles.label}>Confirmar contraseña</label>
              <input style={{...authStyles.input, ...(errors.confirmPassword ? authStyles.inputError : {})}} type="password" placeholder="Confirma tu contraseña" value={confirmPassword} onChange={e => { setConfirmPassword(e.target.value); setErrors(p => ({...p, confirmPassword: undefined})); }} />
              {errors.confirmPassword && <span style={authStyles.fieldError}>{errors.confirmPassword}</span>}
            </div>

            <button style={{...authStyles.primaryBtn, opacity: loading ? 0.8 : 1}} onClick={handleResetPassword} disabled={loading}>
              {loading ? <span style={authStyles.loadingRow}><span style={authStyles.spinner}></span> Restableciendo...</span> : 'Restablecer contraseña'}
            </button>
            <button style={{...authStyles.primaryBtn, background: 'none', color: '#0984e3', border: '1.5px solid #0984e3', marginTop: 12}} onClick={() => setStep(1)}>
              Usar otro email
            </button>
          </>
        )}
      </div>
    </div>
  );
};

// ─── STYLES ───────────────────────────────────────────────────────────────────
const authStyles = {
  root: { minHeight: '100vh', background: '#F8F9FA' },
  page: { minHeight: '100vh', background: 'linear-gradient(135deg, #e8f4fd 0%, #f0f7ff 50%, #e3f0fc 100%)', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '24px 16px', fontFamily: "'Helvetica Neue', Helvetica, Arial, sans-serif", position: 'relative' },
  backBtn: { position: 'absolute', top: 24, left: 24, background: '#fff', border: '1px solid #dee2e6', borderRadius: 10, padding: '8px 14px', fontSize: 14, fontWeight: 500, cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 6, color: '#2D3436', fontFamily: 'inherit' },
  card: { background: '#fff', borderRadius: 20, padding: '36px 32px', width: '100%', maxWidth: 440, boxShadow: '0 8px 48px rgba(9,132,227,0.12)', border: '1px solid #e3f0fc' },
  logoRow: { display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10, marginBottom: 28 },
  logoMark: { width: 36, height: 36, background: '#0984e3', borderRadius: 10, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', fontWeight: 800, fontSize: 18 },
  logoText: { fontSize: 22, fontWeight: 800, color: '#2D3436', letterSpacing: '-0.5px' },
  title: { fontSize: 24, fontWeight: 800, textAlign: 'center', marginBottom: 6, color: '#2D3436', letterSpacing: '-0.5px' },
  subtitle: { fontSize: 14, color: '#636e72', textAlign: 'center', marginBottom: 24, lineHeight: 1.6 },
  roleRow: { display: 'flex', gap: 10, marginBottom: 24 },
  roleBtn: { flex: 1, background: '#f0f4f8', border: '2px solid #dee2e6', borderRadius: 12, padding: '12px 8px', fontSize: 14, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit', color: '#636e72', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6, transition: 'all 0.15s' },
  roleBtnActive: { background: '#e3f0fc', borderColor: '#0984e3', color: '#0984e3' },
  roleIcon: { fontSize: 18 },
  formGroup: { marginBottom: 16 },
  label: { display: 'block', fontSize: 13, fontWeight: 600, color: '#2D3436', marginBottom: 6 },
  labelRow: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 6 },
  forgotLink: { background: 'none', border: 'none', color: '#0984e3', fontSize: 13, cursor: 'pointer', fontFamily: 'inherit', fontWeight: 500 },
  inputWrapper: { position: 'relative' },
  input: { width: '100%', border: '1.5px solid #dee2e6', borderRadius: 10, padding: '12px 14px', fontSize: 15, color: '#2D3436', fontFamily: 'inherit', background: '#fff', boxSizing: 'border-box', outline: 'none', transition: 'border-color 0.15s' },
  inputError: { borderColor: '#dc3545' },
  eyeBtn: { position: 'absolute', right: 12, top: '50%', transform: 'translateY(-50%)', background: 'none', border: 'none', cursor: 'pointer', display: 'flex', alignItems: 'center', padding: 4 },
  fieldError: { fontSize: 12, color: '#dc3545', marginTop: 4, display: 'block' },
  errorBox: { background: '#f8d7da', border: '1px solid #f5c6cb', borderRadius: 8, padding: '10px 14px', fontSize: 13, color: '#721c24', marginBottom: 16 },
  strengthBar: { height: 4, background: '#e9ecef', borderRadius: 2, marginTop: 6, overflow: 'hidden' },
  strengthFill: { height: '100%', borderRadius: 2, transition: 'width 0.3s, background 0.3s' },
  checkRow: { display: 'flex', alignItems: 'flex-start', gap: 10, marginBottom: 16 },
  checkbox: { width: 20, height: 20, borderRadius: 6, border: '2px solid #dee2e6', cursor: 'pointer', flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', marginTop: 1, transition: 'all 0.15s' },
  checkboxChecked: { background: '#0984e3', borderColor: '#0984e3' },
  checkLabel: { fontSize: 13, color: '#636e72', lineHeight: 1.5 },
  termsLink: { background: 'none', border: 'none', color: '#0984e3', fontSize: 13, cursor: 'pointer', fontFamily: 'inherit', fontWeight: 500, padding: 0 },
  primaryBtn: { width: '100%', background: '#0984e3', color: '#fff', border: 'none', borderRadius: 12, padding: '14px', fontSize: 16, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit', transition: 'opacity 0.15s' },
  loadingRow: { display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10 },
  spinner: { width: 18, height: 18, border: '2px solid rgba(255,255,255,0.4)', borderTop: '2px solid #fff', borderRadius: '50%', animation: 'spin 0.8s linear infinite', display: 'inline-block' },
  bookingContext: { background: '#e3f0fc', border: '1px solid #b8d8f5', borderRadius: 12, padding: '12px 14px', display: 'flex', alignItems: 'center', gap: 12, marginBottom: 20 },
  bookingContextIcon: { fontSize: 24, flexShrink: 0 },
  bookingContextTitle: { fontSize: 13, fontWeight: 700, color: '#0984e3', marginBottom: 2 },
  bookingContextSub: { fontSize: 12, color: '#636e72', lineHeight: 1.4 },
  divider: { display: 'flex', alignItems: 'center', gap: 12, margin: '20px 0', color: '#adb5bd', fontSize: 13 },
  socialRow: { display: 'flex', gap: 10, marginBottom: 20 },
  socialBtn: { flex: 1, background: '#fff', border: '1.5px solid #dee2e6', borderRadius: 10, padding: '10px', fontSize: 14, fontWeight: 500, cursor: 'pointer', fontFamily: 'inherit', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, color: '#2D3436' },
  switchText: { textAlign: 'center', fontSize: 14, color: '#636e72', margin: '16px 0 0' },
  switchLink: { background: 'none', border: 'none', color: '#0984e3', fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit', fontSize: 14 },
  // Verify email
  verifyEmailIcon: { fontSize: 48, textAlign: 'center', marginBottom: 16 },
  otpRow: { display: 'flex', gap: 10, justifyContent: 'center', marginBottom: 24 },
  otpInput: { width: 46, height: 52, border: '2px solid #dee2e6', borderRadius: 12, textAlign: 'center', fontSize: 22, fontWeight: 700, fontFamily: 'inherit', outline: 'none', color: '#2D3436' },
  resendBtn: { width: '100%', background: 'none', border: 'none', color: '#0984e3', fontSize: 14, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit', marginTop: 12 },
};

window.AuthFlow = AuthFlow;
