'use client';
import { createContext, useContext, useState, useEffect, useCallback } from 'react';

interface User {
  id: string;
  email: string;
  role: string;
}

interface AuthContextValue {
  user: User | null;
  loading: boolean;
  login: (email: string, password: string) => Promise<{ ok: boolean; error?: string }>;
  register: (email: string, password: string) => Promise<{ ok: boolean; error?: string }>;
  logout: () => Promise<void>;
}

const AuthContext = createContext<AuthContextValue | null>(null);

export function AuthProvider({ children }: { children: React.ReactNode }) {
  const [user, setUser] = useState<User | null>(null);
  const [loading, setLoading] = useState(true);

  // FIX-198: must send credentials so the session cookie is included.
  // FIX-198: /auth/me returns {id,email,role} when authenticated, {user:null} when not.
  useEffect(() => {
    fetch('/api/auth/me', { credentials: 'include' })
      .then((r) => r.json())
      .then((data) => {
        // When authenticated: { id, email, role }. When not: { user: null }.
        setUser(data.user ?? (data.id ? data : null));
      })
      .catch(() => setUser(null))
      .finally(() => setLoading(false));
  }, []);

  const login = useCallback(async (email: string, password: string) => {
    const res = await fetch('/api/auth/login', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ email, password }),
      credentials: 'include',
    });
    const data = await res.json();
    if (!res.ok) {
      if (data.error?.code === 'EMAIL_NOT_CONFIRMED') {
        return { ok: false, error: 'Email no confirmado. Revisa tu correo o solicita un nuevo enlace de confirmación.' };
      }
      if (data.error?.code === 'EMAIL_ALREADY_REGISTERED') {
        return { ok: false, error: 'Este email ya está registrado. ¿Ya tienes cuenta? Inicia sesión.' };
      }
      return { ok: false, error: data.error?.message || 'Email o contraseña incorrectos' };
    }
    setUser(data);
    return { ok: true };
  }, []);

  const register = useCallback(async (email: string, password: string) => {
    const res = await fetch('/api/auth/register', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ email, password }),
      credentials: 'include',
    });
    const data = await res.json();
    if (!res.ok) {
      if (data.error?.code === 'EMAIL_ALREADY_REGISTERED') {
        return { ok: false, error: 'Este email ya está registrado. ¿Ya tienes cuenta? Inicia sesión.' };
      }
      return { ok: false, error: data.error?.message || 'Error de registro' };
    }
    setUser(data);
    return { ok: true };
  }, []);

  const logout = useCallback(async () => {
    await fetch('/api/auth/logout', { method: 'POST' });
    setUser(null);
  }, []);

  return (
    <AuthContext.Provider value={{ user, loading, login, register, logout }}>
      {children}
    </AuthContext.Provider>
  );
}

export function useAuth() {
  const ctx = useContext(AuthContext);
  if (!ctx) throw new Error('useAuth must be used within AuthProvider');
  return ctx;
}
