'use client';

import React from 'react';

// Simple auth store without external dependencies
// In production, this would use Zustand or a proper auth library
interface AuthUser {
  id: string;
  email?: string;
  name?: string;
  did?: string;
  roles?: string[];
  accessToken?: string;
  refreshToken?: string;
}

interface AuthState {
  user: AuthUser | null;
  isAuthenticated: boolean;
  isLoading: boolean;
  login: (user: AuthUser) => void;
  logout: () => void;
  setUser: (user: AuthUser | null) => void;
}

// Simple in-memory store with localStorage persistence
class AuthStore {
  private state: AuthState = {
    user: null,
    isAuthenticated: false,
    isLoading: false,
    login: () => {},
    logout: () => {},
    setUser: () => {},
  };

  private listeners: Set<(state: AuthState) => void> = new Set();

  constructor() {
    this.loadFromStorage();
  }

  private loadFromStorage() {
    if (typeof window === 'undefined') return;
    try {
      const stored = localStorage.getItem('auth-storage');
      if (stored) {
        const parsed = JSON.parse(stored);
        this.state.user = parsed.user || null;
        this.state.isAuthenticated = !!this.state.user;
      }
    } catch {
      // Ignore parse errors
    }
  }

  private saveToStorage() {
    if (typeof window === 'undefined') return;
    try {
      localStorage.setItem('auth-storage', JSON.stringify({ user: this.state.user }));
    } catch {
      // Ignore storage errors
    }
  }

  private notify() {
    this.listeners.forEach((listener) => listener(this.state));
  }

  subscribe(listener: (state: AuthState) => void) {
    this.listeners.add(listener);
    return () => {
      this.listeners.delete(listener);
    };
  }

  getState() {
    return this.state;
  }

  setState(updates: Partial<AuthState>) {
    this.state = { ...this.state, ...updates };
    this.saveToStorage();
    this.notify();
  }
}

const authStore = typeof window !== 'undefined' ? new AuthStore() : null;

// React hook to use auth state
export function useAuth(): AuthState {
  const [state, setState] = React.useState<AuthState>(
    authStore?.getState() || {
      user: null,
      isAuthenticated: false,
      isLoading: false,
      login: () => {},
      logout: () => {},
      setUser: () => {},
    }
  );

  React.useEffect(() => {
    if (!authStore) return;

    const unsubscribe = authStore.subscribe(setState);
    return unsubscribe;
  }, []);

  return {
    ...state,
    login: (user: AuthUser) => {
      authStore?.setState({ user, isAuthenticated: true });
      if (user.accessToken) {
        localStorage.setItem('auth_token', user.accessToken);
      }
    },
    logout: () => {
      authStore?.setState({ user: null, isAuthenticated: false });
      localStorage.removeItem('auth_token');
    },
    setUser: (user: AuthUser | null) => {
      authStore?.setState({ user, isAuthenticated: !!user });
    },
  };
}
