"use client";

import type React from "react";
import { useState, useEffect, useMemo, useCallback, memo } from "react";
import { motion, AnimatePresence } from "framer-motion";
import DesktopIcon from "./DesktopIcon";
import Window from "./Window";
import styles from "./Desktop.module.css";
import { desktopApps } from "@/data/apps";
import { publish, AwarenessEvent } from '@/lib/awareness';

// Local WindowState type used by this component (matches fields accessed below)
interface WindowState {
  position?: {
    x: number;
    y: number;
  };
  size?: {
    width: number;
    height: number;
  };
  isMaximized?: boolean;
}

// ========================================
// 🧠 Debug Mode (safe console logger)
// ========================================
const DEBUG =
  (typeof process !== "undefined" &&
    process.env.NODE_ENV !== "production") ||
  (typeof process !== "undefined" &&
    process.env.NEXT_PUBLIC_DEBUG === "true");

const dlog = (...args: any[]) => {
  if (DEBUG) console.log("[Desktop]", ...args);
};

// ========================================
// 🧩 Interfaces
// ========================================
interface DesktopProps {
  openWindow: (app: any) => void;
  openWindows?: any[];
  closeWindow: (id: string) => void;
  minimizeWindow: (id: string) => void;
  minimizedWindows?: string[];
  activeWindow: string | null;
  setActiveWindow: (id: string | null) => void;
  windowStates?: Record<string, WindowState>;
  setWindowState: (id: string, newState: Partial<WindowState>) => void;
}

// ========================================
// ⚡ Memoized particle for performance
// ========================================
const Particle = memo(({ particle, index }: { particle: any; index: number }) => (
  <motion.div
    className={styles.particle}
    initial={{
      x: particle.x,
      y: particle.y,
      opacity: 0,
    }}
    animate={{
      x: [particle.x, particle.x + (Math.random() - 0.5) * 100],
      y: [particle.y, particle.y + (Math.random() - 0.5) * 100],
      opacity: [0, 0.6, 0],
    }}
    transition={{
      duration: 15 + Math.random() * 10,
      repeat: Number.POSITIVE_INFINITY,
      ease: "linear",
      delay: index * 0.5,
    }}
  />
));
Particle.displayName = "Particle";

// ========================================
// 🧱 Desktop Component
// ========================================
export default function Desktop({
  openWindow,
  openWindows = [],
  closeWindow,
  minimizeWindow,
  minimizedWindows = [],
  activeWindow,
  setActiveWindow,
  windowStates = {},
  setWindowState,
}: DesktopProps) {
  // 🧩 Safety
  const safeWindows = Array.isArray(openWindows) ? openWindows : [];
  const safeMinimized = Array.isArray(minimizedWindows)
    ? minimizedWindows
    : [];

  const [selectedIcon, setSelectedIcon] = useState<string | null>(null);
  const [windowZIndexes, setWindowZIndexes] = useState<
    Record<string, number>
  >({});

  // 🌀 Reduced background particles
  const particles = useMemo(
    () =>
      [...Array(8)].map((_, i) => ({
        id: i,
        x:
          Math.random() *
          (typeof window !== "undefined" ? window.innerWidth : 1000),
        y:
          Math.random() *
          (typeof window !== "undefined" ? window.innerHeight : 800),
      })),
    []
  );

  // 🧱 Initialize z-indexes safely
  useEffect(() => {
    if (!Array.isArray(safeWindows)) return;

    const newZIndexes: Record<string, number> = {};
    let hasNewWindows = false;

    safeWindows.forEach((window, index) => {
      if (window && window.id && !windowZIndexes[window.id]) {
        newZIndexes[window.id] = 100 + index;
        hasNewWindows = true;
        if (DEBUG) dlog(`🪟 Added z-index for ${window.id}`);
      }
    });

    if (hasNewWindows) {
      setWindowZIndexes((prev) => ({ ...prev, ...newZIndexes }));
    }
  }, [safeWindows, windowZIndexes]);
    useEffect(() => {
      publish({
        type: AwarenessEvent.DESKTOP_LOADED,
        payload: {
            timestamp: performance.now(),
            openWindows: safeWindows.length,
            activeWindow: activeWindow,
        }
    });
    }, []);

  // 🖱️ Desktop click logic
  const handleIconClick = useCallback((e: React.MouseEvent, app: any) => {
    e.stopPropagation();
    setSelectedIcon(app.id);
  }, []);

  const handleIconDoubleClick = useCallback(
    (app: any) => {
      dlog(`🚀 Opening app: ${app.id}`);
      openWindow(app);
    },
    [openWindow]
  );

  const handleDesktopClick = useCallback(() => {
    setSelectedIcon(null);
    setActiveWindow(null);
  }, [setActiveWindow]);

  // 🧭 Focus handler
  const focusWindow = useCallback(
    (id: string) => {
      setActiveWindow(id);
      setWindowZIndexes((prev) => {
        const maxZ = Math.max(...Object.values(prev), 100);
        return {
          ...prev,
          [id]: maxZ + 1,
        };
      });
      dlog(`🎯 Focused window: ${id}`);
      publish({
          type: AwarenessEvent.WINDOW_FOCUSED,
          payload: {
              windowId: id,
              timestamp: performance.now(),
          }
      });
    },
    [setActiveWindow]
  );

  return (
    <div className={`desktop ${styles.desktop}`} onClick={handleDesktopClick}>
      {/* Simplified background */}
      <div className={styles.backgroundLayer} />

      {/* Reduced particles */}
      <div className={styles.particles}>
        {particles.map((particle, index) => (
          <Particle key={particle.id} particle={particle} index={index} />
        ))}
      </div>

      {/* Desktop icons grid */}
      <div className={styles.desktopContent}>
        <div
          className={styles.iconsGrid}
          onClick={(e) => e.stopPropagation()}
        >
          {desktopApps.map((app, index) => (
            <motion.div
              key={app.id}
              initial={{ opacity: 0, scale: 0.8 }}
              animate={{ opacity: 1, scale: 1 }}
              transition={{
                duration: 0.3,
                delay: index * 0.05,
              }}
            >
              <DesktopIcon
                app={app}
                isSelected={selectedIcon === app.id}
                onClick={(e) => handleIconClick(e, app)}
                onDoubleClick={() => handleIconDoubleClick(app)}
              />
            </motion.div>
          ))}
        </div>

        {/* Welcome message */}
        <motion.div
          className={styles.welcomeMessage}
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5, delay: 0.5 }}
        >
          <h1>Welcome to Mohamed Gamal's Portfolio</h1>
          <p>Team Lead | Full Stack Engineer specializing in Laravel + Vue.js</p>
          <p>Double-click any icon to explore my work and experience</p>
        </motion.div>
      </div>

      {/* Windows rendering */}
      <AnimatePresence mode="popLayout">
        {safeWindows.map((window) => {
          if (!window || !window.id) return null;

          const windowWithOpenWindow = {
            ...window,
            openWindow,
          };

          return (
            <Window
              key={window.id}
              app={windowWithOpenWindow}
              onClose={() => closeWindow(window.id)}
              isActive={activeWindow === window.id}
              onFocus={() => focusWindow(window.id)}
              onMinimize={() => minimizeWindow(window.id)}
              zIndex={windowZIndexes[window.id] || 100}
              initialPosition={windowStates?.[window.id]?.position}
              initialSize={windowStates?.[window.id]?.size}
              isMaximized={windowStates?.[window.id]?.isMaximized}
              setWindowState={setWindowState}
            />
          );
        })}
      </AnimatePresence>
    </div>
  );
}
