'use client';

/**
 * Loading Provider
 * Enterprise FinTech Platform
 *
 * Global loading state management for the application.
 * Coordinates priority-based loading across all pages.
 */

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

interface LoadingState {
  global: boolean;
  priority: number;
  message?: string;
}

interface LoadingContextValue {
  state: LoadingState;
  showLoading: (priority?: number, message?: string) => void;
  hideLoading: () => void;
  updateProgress: (progress: number) => void;
}

const LoadingContext = createContext<LoadingContextValue | null>(null);

export function LoadingProvider({ children }: { children: React.ReactNode }) {
  const [state, setState] = useState<LoadingState>({
    global: false,
    priority: 0,
  });

  const showLoading = useCallback((priority = 1, message?: string) => {
    setState((prev) => {
      if (priority > prev.priority) {
        return { global: true, priority, message };
      }
      return prev;
    });
  }, []);

  const hideLoading = useCallback(() => {
    setState((prev) => {
      if (prev.priority <= 1) {
        return { global: false, priority: 0 };
      }
      return { ...prev, priority: prev.priority - 1 };
    });
  }, []);

  const updateProgress = useCallback((_progress: number) => {
    // Reserved for future progress bar implementation
  }, []);

  return (
    <LoadingContext.Provider value={{ state, showLoading, hideLoading, updateProgress }}>
      {children}
      {state.global && <GlobalLoadingIndicator message={state.message} />}
    </LoadingContext.Provider>
  );
}

export function useLoading() {
  const context = useContext(LoadingContext);
  if (!context) {
    return {
      state: { global: false, priority: 0 },
      showLoading: () => {},
      hideLoading: () => {},
      updateProgress: () => {},
    };
  }
  return context;
}

function GlobalLoadingIndicator({ message }: { message?: string }) {
  return (
    <div className="pointer-events-none fixed inset-x-0 top-0 z-50 h-1">
      <div className="h-full w-full animate-pulse bg-gradient-to-r from-primary-500 via-indigo-500 to-primary-500 opacity-80" />
    </div>
  );
}
