
"use client";

import React, { createContext, useState, useEffect } from 'react';
import type { User } from '@/lib/types';
import { users } from '@/lib/data';

export type AuthContextType = {
  user: User | null;
  login: (email: string, pass: string) => Promise<boolean>;
  logout: () => void;
};

export const AuthContext = createContext<AuthContextType | undefined>(undefined);

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

  useEffect(() => {
    // In a real app, you'd check a token from localStorage or a cookie
    const storedUser = sessionStorage.getItem('user');
    if (storedUser) {
      setUser(JSON.parse(storedUser));
    }
  }, []);

  const login = async (email: string, pass: string): Promise<boolean> => {
    // This is a mock login. In a real app, you'd make an API call.
    if (email === 'admin@example.com' && pass === 'password') {
      const adminUser = users.find(u => u.id === 'u1'); // Assuming u1 is an admin
      if (adminUser) {
        setUser(adminUser);
        sessionStorage.setItem('user', JSON.stringify(adminUser));
        return true;
      }
    }
    return false;
  };

  const logout = () => {
    setUser(null);
    sessionStorage.removeItem('user');
    // Forcing a reload to ensure all state is cleared.
    window.location.href = '/';
  };

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