"use client"

import { useState, useEffect, useRef, useCallback } from "react"
import dynamic from "next/dynamic"
import Desktop from "@/components/Desktop"
import TopBar from "@/components/TopBar"
import Dock from "@/components/Dock"
import LoginScreen from "@/components/LoginScreen"
import Loader from "@/components/Loader"
import { allApps } from "@/data/apps"
import styles from "./page.module.css"
import { publish, AwarenessEvent } from '@/lib/awareness';

import { startSelfReflection, stopSelfReflection } from '@/lib/reflection';

/** ============================
 *  🔎 DEBUG FLAG & LOG HELPERS
 *  - تعطيل اللوجز تلقائيًا في الإنتاج
 *  - يمكن إجبار التفعيل/التعطيل عبر NEXT_PUBLIC_DEBUG
 * ============================ */
const DEBUG_ENV =
  (typeof process !== "undefined" &&
    typeof process.env !== "undefined" &&
    typeof process.env.NEXT_PUBLIC_DEBUG === "string" &&
    process.env.NEXT_PUBLIC_DEBUG.toLowerCase() === "true") ||
  (typeof process !== "undefined" && process.env.NODE_ENV !== "production")

const DEBUG: boolean = DEBUG_ENV

const log = (...args: any[]) => {
  if (DEBUG) console.log(...args)
}
const warn = (...args: any[]) => {
  if (DEBUG) console.warn(...args)
}
// نُبقي error دائمًا ظاهر لأنه مفيد في اكتشاف الأعطال
const err = (...args: any[]) => console.error(...args)

// Shared WindowState type used by window manager + Window components
export interface WindowState {
  position: { x: number; y: number }
  size: { width: number; height: number }
  isMaximized: boolean
}

// Lazy load heavy components (to optimize initial load)
const ActivitiesOverview = dynamic(() => import("@/components/ActivitiesOverview"), {
  loading: () => <div>Loading...</div>,
})

export default function Home() {
  // ===========================================
  // 🧠 STATE MANAGEMENT
  // ===========================================
  const [isLoggedIn, setIsLoggedIn] = useState(false)
  const [activitiesOpen, setActivitiesOpen] = useState(false)
  const [openWindows, setOpenWindows] = useState<any[]>([])
  const [activeWindow, setActiveWindow] = useState<string | null>(null)
  const [minimizedWindows, setMinimizedWindows] = useState<string[]>([])
  const [windowStates, setWindowStates] = useState<Record<string, WindowState>>({})
  const [loaderVisible, setLoaderVisible] = useState(true)
  const [loaderFading, setLoaderFading] = useState(false)
  const [showLoginScreen, setShowLoginScreen] = useState(false)
  const [isLoaded, setIsLoaded] = useState(false)
  const [isUnlocked, setIsUnlocked] = useState(false)
  const contentRef = useRef<HTMLElement>(null)

  interface WindowState {
    position: { x: number; y: number }
    size: { width: number; height: number }
    isMaximized: boolean
  }

  // ===========================================
  // 🚀 Self-Reflection System Initialization
  // ===========================================
  useEffect(() => {
    startSelfReflection();
    return () => {
      stopSelfReflection();
    };
  }, []);

  // ===========================================
  // 🪟 WINDOW OPERATIONS
  // ===========================================
  const openWindow = useCallback((app: any) => {
    if (!app || !app.id) {
      warn("⚠️ openWindow called with invalid app object:", app)
      return
    }
    if (DEBUG) console.log(`[UI] Opening window: ${app.id}`);
    publish({
        type: AwarenessEvent.WINDOW_OPENED,
        payload: {
            windowId: app.id,
            timestamp: performance.now(),
        }
    });

    log(`🪟 [DEBUG] Opening window: ${app.name || app.id}`)

    setMinimizedWindows((prevMinimized) => {
      if (prevMinimized.includes(app.id)) {
        setActiveWindow(app.id)
        return prevMinimized.filter((id) => id !== app.id)
      }
      return prevMinimized
    })

    setOpenWindows((prevWindows) => {
      const existingWindow = prevWindows.find((window) => window.id === app.id)
      if (!existingWindow) {
        setActiveWindow(app.id)
        setWindowStates((prevStates) => ({
          ...prevStates,
          [app.id]: {
            position: {
              x: 100 + Object.keys(prevStates).length * 20,
              y: 100 + Object.keys(prevStates).length * 20,
            },
            size: { width: 800, height: 600 },
            isMaximized: false,
          },
        }))
        return [...prevWindows, app]
      } else {
        setActiveWindow(app.id)
        return prevWindows
      }
    })
  }, [])

  const closeWindow = useCallback((id: string) => {
    setOpenWindows((prev) => prev.filter((window) => window.id !== id))
    setMinimizedWindows((prev) => prev.filter((windowId) => windowId !== id))
    setWindowStates((prevStates) => {
      const newStates = { ...prevStates }
      delete newStates[id]
      return newStates
    })
    setActiveWindow((prevActive) => (prevActive === id ? null : prevActive));
    publish({
        type: AwarenessEvent.WINDOW_CLOSED,
        payload: {
            windowId: id,
            timestamp: performance.now(),
        }
    });
  }, [])

  const focusWindow = useCallback((id: string) => {
    setMinimizedWindows((prev) => prev.filter((windowId) => windowId !== id))
    setActiveWindow(id)
  }, [])

  const minimizeWindow = useCallback((id: string) => {
    setMinimizedWindows((prev) => {
      if (!prev.includes(id)) return [...prev, id]
      return prev
    })
    setActiveWindow((prevActive) => (prevActive === id ? null : prevActive))
  }, [])

  const setWindowState = useCallback((id: string, newState: Partial<WindowState>) => {
    setWindowStates((prevStates) => ({
      ...prevStates,
      [id]: {
        ...prevStates[id],
        ...newState,
      },
    }))
  }, [])

  // ===========================================
  // 🔐 LOGIN & LOGOUT
  // ===========================================
  const handleLogin = useCallback(() => {
    setIsLoggedIn(true)
    setShowLoginScreen(false)
    setIsUnlocked(true)
    publish({
        type: AwarenessEvent.DESKTOP_LOADED,
        payload: {
            timestamp: performance.now(),
            openWindows: openWindows.length,
            activeWindow: activeWindow,
        }
    });
  }, [openWindows, activeWindow])

  const handleLogout = useCallback(() => {
    setIsLoggedIn(false)
    setShowLoginScreen(true)
    setIsUnlocked(false)
    setOpenWindows([])
    setActiveWindow(null)
    setMinimizedWindows([])
    setActivitiesOpen(false)
  }, [])

  const toggleActivities = useCallback(() => {
    setActivitiesOpen((prev) => !prev)
  }, [])

  const handleDesktopClick = useCallback(() => {
    if (activitiesOpen) setActivitiesOpen(false)
  }, [activitiesOpen])

  // ===========================================
  // 🌀 LOADER SEQUENCE
  // ===========================================
  useEffect(() => {
    const startTime = performance.now();
    const loaderTimer = setTimeout(() => {
      setLoaderFading(true)
      setTimeout(() => {
        setLoaderVisible(false)
        setShowLoginScreen(true)
        setIsLoaded(true)
        const endTime = performance.now();
        publish({
            type: AwarenessEvent.TELEMETRY_METRIC,
            payload: {
                name: 'desktop_render_ms',
                value: endTime - startTime,
            }
        });
      }, 800)
    }, 3000)
    return () => clearTimeout(loaderTimer)
  }, [])

  // ===========================================
  // 💾 LOCAL STORAGE — LOAD (with idleCallback)
  // ===========================================
  useEffect(() => {
    if (!isUnlocked) return

    const loadState = () => {
      try {
        const savedState = localStorage.getItem("portfolio-os-state")
        if (savedState) {
          const parsed = JSON.parse(savedState)
          setOpenWindows(parsed.openWindows || [])
          setActiveWindow(parsed.activeWindow || null)
          setMinimizedWindows(parsed.minimizedWindows || [])
          setWindowStates(parsed.windowStates || {})
          log("💾 [DEBUG] State loaded from localStorage.")
        }
      } catch (e) {
        err("Failed to load state:", e)
      }
    }

    if ("requestIdleCallback" in window) {
      ;(window as any).requestIdleCallback(loadState)
    } else {
      loadState()
    }
  }, [isUnlocked])

  // ===========================================
  // 💾 LOCAL STORAGE — SAVE (Debounced)
  // ===========================================
  useEffect(() => {
    if (!isUnlocked) return
    const timeout = setTimeout(() => {
      try {
        const stateToSave = { openWindows, activeWindow, minimizedWindows, windowStates }
        localStorage.setItem("portfolio-os-state", JSON.stringify(stateToSave))
        log("💾 [DEBUG] State saved to localStorage.")
      } catch (e) {
        err("Failed to save state:", e)
      }
    }, 300)
    return () => clearTimeout(timeout)
  }, [openWindows, activeWindow, minimizedWindows, windowStates, isUnlocked])

  // ===========================================
  // 🔗 DEEP LINKING (Safe & Guarded)
  // ===========================================
  useEffect(() => {
    if (isUnlocked && typeof window !== "undefined") {
      try {
        const urlParams = new URLSearchParams(window.location.search)
        const appToOpenId = urlParams.get("app")

        // Guard: if allApps not ready
        if (!allApps || !Array.isArray(allApps) || allApps.length === 0) {
          warn("⚠️ allApps not loaded yet, skipping deep link.")
          return
        }

        if (appToOpenId) {
          const appData = allApps.find((app) => app.id === appToOpenId)
          if (appData) {
            log(`🔗 [DEBUG] Deep link detected → Opening app: ${appToOpenId}`)
            openWindow(appData)
            window.history.replaceState({}, document.title, window.location.pathname)
          } else {
            warn(`⚠️ App with ID "${appToOpenId}" not found in allApps.`)
          }
        }
      } catch (e) {
        err("Error processing deep link:", e)
      }
    }
  }, [isUnlocked, openWindow])

  // ===========================================
  // 🖥️ RENDER
  // ===========================================
  return (
    <main className="relative w-full h-screen overflow-hidden" onClick={handleDesktopClick}>
      {/* Loader */}
      {loaderVisible && (
        <div className={`${styles.loaderOverlay} ${loaderFading ? styles.fadeOut : ""}`}>
          <Loader onLoaded={() => setIsLoaded(true)} />
        </div>
      )}

      {/* Lock Screen */}
      {isLoaded && !isUnlocked && <LoginScreen onUnlock={handleLogin} />}

      {/* Desktop Environment */}
      {isLoaded && isUnlocked && (
        <>
          <TopBar toggleActivities={toggleActivities} activitiesOpen={activitiesOpen} onLogout={handleLogout} />

          <Desktop
            openWindow={openWindow}
            openWindows={openWindows}
            closeWindow={closeWindow}
            activeWindow={activeWindow}
            setActiveWindow={setActiveWindow}
            minimizeWindow={minimizeWindow}
            minimizedWindows={minimizedWindows}
            windowStates={windowStates}
            setWindowState={setWindowState}
          />

          {activitiesOpen && (
            <ActivitiesOverview
              openWindow={(app: any) => {
                log(`🧭 [DEBUG] Opening from ActivitiesOverview → ${app?.id || "Unknown App"}`)
                openWindow(app)
                setActivitiesOpen(false)
              }}
              onLogout={handleLogout}
              openWindows={openWindows}
              focusWindow={focusWindow}
            />
          )}

          <Dock
            openWindows={openWindows}
            openWindow={openWindow}
            focusWindow={focusWindow}
            minimizedWindows={minimizedWindows}
          />
        </>
      )}
    </main>
  )
}
