import { useState, useEffect } from 'react';
import { usePage } from '@inertiajs/react';

const usePreloader = () => {
  const { props, url } = usePage();
  const [showPreloader, setShowPreloader] = useState(false);
  const [preloaderCompleted, setPreloaderCompleted] = useState(false);

  // Get settings from props
  const siteLogo = props.site_logo ?? "/logo.png";
  const siteName = props.site_settings?.site_name ?? "MySite";
  const preloaderEnabled = props.site_settings?.preloader_enabled === "1";
  const showOnHome = props.site_settings?.preloader_show_on_home === "1";
  const showOnFirstLogin = props.site_settings?.preloader_show_on_first_login === "1";
  const duration = parseInt(props.site_settings?.preloader_duration || "3000");
  const primaryColor = props.site_settings?.primary_color ?? "#667eea";
  const secondaryColor = props.site_settings?.secondary_color ?? "#764ba2";

  useEffect(() => {
    if (!preloaderEnabled) {
      setShowPreloader(false);
      return;
    }

    // Check if current route is home/dashboard
    const isHomeRoute = url === '/' || url.includes('/home') || url.includes('/dashboard');

    // Get device fingerprint
    const deviceFingerprint = getDeviceFingerprint();
    const sessionKey = `preloader_shown_${deviceFingerprint}`;
    const homePreloaderKey = `preloader_home_shown_${deviceFingerprint}`;

    // Check if this is first time on this device
    const isFirstDevice = !sessionStorage.getItem(sessionKey);

    // Check if preloader was already shown for home route in this session
    const homeAlreadyShown = sessionStorage.getItem(homePreloaderKey);

    let shouldShow = false;

    // Determine if preloader should be shown
    if (showOnFirstLogin && isFirstDevice) {
      // Show on first device login
      shouldShow = true;
      sessionStorage.setItem(sessionKey, 'true');
    } else if (showOnHome && isHomeRoute && !homeAlreadyShown) {
      // Show on home route if not already shown in this session
      shouldShow = true;
      sessionStorage.setItem(homePreloaderKey, 'true');
    }

    setShowPreloader(shouldShow);

    // Clear home preloader flag when navigating away from home
    if (!isHomeRoute) {
      sessionStorage.removeItem(homePreloaderKey);
    }
  }, [url, preloaderEnabled, showOnHome, showOnFirstLogin]);

  // Generate a device fingerprint based on browser characteristics
  const getDeviceFingerprint = () => {
    const nav = window.navigator;
    const screen = window.screen;

    const fingerprint = [
      nav.userAgent,
      nav.language,
      screen.colorDepth,
      screen.width + 'x' + screen.height,
      new Date().getTimezoneOffset(),
      nav.hardwareConcurrency,
      nav.platform
    ].join('|');

    // Simple hash function to create a shorter fingerprint
    let hash = 0;
    for (let i = 0; i < fingerprint.length; i++) {
      const char = fingerprint.charCodeAt(i);
      hash = ((hash << 5) - hash) + char;
      hash = hash & hash; // Convert to 32-bit integer
    }

    return 'device_' + Math.abs(hash).toString(36);
  };

  const handlePreloaderComplete = () => {
    setPreloaderCompleted(true);
    setShowPreloader(false);
  };

  return {
    showPreloader,
    siteName,
    siteLogo,
    duration,
    primaryColor,
    secondaryColor,
    onComplete: handlePreloaderComplete
  };
};

export default usePreloader;