// src/components/GlobeCanvas.jsx
import React, { useRef, Suspense, useEffect, useCallback } from 'react';
import { Canvas, useLoader, useFrame, useThree } from '@react-three/fiber';
import { OrbitControls, Html, Sphere } from '@react-three/drei';
import { TextureLoader, LinearSRGBColorSpace, BackSide } from 'three';
import * as THREE from 'three'; // *** เพิ่มการ import THREE ที่นี่ ***

import EarthBody from './EarthBody';
import PointsOnGlobe from './PointsOnGlobe';
import ConnectionLines from './ConnectionLines';
import Satellite from './Satellite'; // *** Import Satellite ที่นี่ ***

// Helper function to convert 3D Cartesian coordinates to Lat/Lon
// Assumes globe radius of 1 (หรือตามขนาดจริงของ EarthBody ที่คุณใช้)
function cartesianToLatLon(vector) {
    const radius = 1; // *** ตรวจสอบค่านี้ให้ตรงกับขนาดจริงของโลกคุณ ***
    const lat = Math.asin(vector.y / radius) * (180 / Math.PI);
    let lon = Math.atan2(vector.z / radius, vector.x / radius) * (180 / Math.PI);
    if (lon > 180) lon -= 360;
    else if (lon < -180) lon += 360;
    return { lat, lon };
}

// StarfieldBackground เหมือนเดิม
function StarfieldBackground() {
    const starMap = useLoader(TextureLoader, '/textures/stars/my_starfield.png');
    starMap.colorSpace = LinearSRGBColorSpace;
    return (
        <Sphere args={[100, 64, 64]}>
            <meshBasicMaterial
                map={starMap}
                side={BackSide}
            />
        </Sphere>
    );
}

// CustomOrbitControls (ปรับปรุงเพื่อตรวจจับ Zoom และจัดการ Context)
function CustomOrbitControls({ controlsRef, onZoomChange, onExitLocalView, isLocalView }) {
    const { camera, gl } = useThree();
    const CAMERA_ZOOM_IN_THRESHOLD = 0.8;
    const CAMERA_ZOOM_OUT_THRESHOLD = 1.5;

    const currentViewMode = useRef(isLocalView);

    useEffect(() => {
        if (controlsRef.current) {
            controlsRef.current.enableDamping = true;
            controlsRef.current.dampingFactor = 0.05;

            controlsRef.current.enableRotate = false;
            controlsRef.current.enableZoom = true;
            controlsRef.current.enablePan = false;

            controlsRef.current.autoRotate = false;

            controlsRef.current.minPolarAngle = Math.PI / 3;
            controlsRef.current.maxPolarAngle = Math.PI - Math.PI / 3;

            controlsRef.current.target.set(0, 0, 0);
            controlsRef.current.update();

            controlsRef.current.enabled = true;

            console.log("CustomOrbitControls: Initialized. Controls enabled (zoom only).");
        }
    }, [controlsRef, camera, gl]);

    useEffect(() => {
        currentViewMode.current = isLocalView;
        console.log("CustomOrbitControls: isLocalView prop changed to:", isLocalView, " (currentViewMode.current updated)");
        if (controlsRef.current) {
            controlsRef.current.target.set(0, 0, 0);
            controlsRef.current.update();
            console.log("CustomOrbitControls: Reset OrbitControls target to (0,0,0) on isLocalView change.");
        }
    }, [isLocalView, controlsRef]);

    useFrame(() => {
        if (controlsRef.current) {
            const distance = camera.position.length();

            // console.log(`Debug: Distance=${distance.toFixed(3)}, currentViewMode=${currentViewMode.current ? 'Local' : 'Global'}`); // Debugging

            if (!currentViewMode.current) {
                if (distance < CAMERA_ZOOM_IN_THRESHOLD) {
                    if (onZoomChange) {
                        // *** CALCULATE THE LAT/LON OF THE CENTER OF THE SCREEN ***
                        const raycaster = new THREE.Raycaster();
                        const mouse = new THREE.Vector2(0, 0); // Center of the screen in normalized device coordinates (-1 to +1)
                        raycaster.setFromCamera(mouse, camera);

                        // Assuming your globe is a sphere at (0,0,0) with radius 1
                        // *** ตรวจสอบค่านี้ให้ตรงกับขนาดจริงของโลกคุณ ***
                        const globeRadius = 1;
                        const globeSphere = new THREE.Sphere(new THREE.Vector3(0, 0, 0), globeRadius);
                        const intersectionPoint = new THREE.Vector3();
                        const intersects = raycaster.ray.intersectSphere(globeSphere, intersectionPoint);

                        let lat = 0;
                        let lon = 0;

                        if (intersects) {
                            const coords = cartesianToLatLon(intersectionPoint);
                            lat = coords.lat;
                            lon = coords.lon;
                            console.log(`CustomOrbitControls: Intersected Globe at Lat: ${lat.toFixed(4)}, Lon: ${lon.toFixed(4)}`);
                        } else {
                            console.warn("CustomOrbitControls: Raycaster did not intersect the globe. Defaulting to 0,0 for Local View.");
                        }

                        console.log(`Action: Zoom IN detected (distance ${distance.toFixed(3)} < ${CAMERA_ZOOM_IN_THRESHOLD}). Switching to Local View.`);
                        currentViewMode.current = true;
                        onZoomChange({ lat, lon }); // *** ส่งค่า lat, lon ที่คำนวณได้ออกไป ***
                    }
                }
            } else {
                if (distance > CAMERA_ZOOM_OUT_THRESHOLD) {
                    if (onExitLocalView) {
                        console.log(`Action: Zoom OUT detected (distance ${distance.toFixed(3)} > ${CAMERA_ZOOM_OUT_THRESHOLD}). Switching to Global View.`);
                        currentViewMode.current = false;
                        onExitLocalView();
                    }
                }
            }
        }
    });

    return <OrbitControls ref={controlsRef} args={[camera, gl.domElement]} />;
}


// GlobeCanvas Component
export default function GlobeCanvas({ activePanel, isNewsMode, panelLocations, globePoints, globeConnections, onPointClick, onZoomToLocal, onExitLocalView, isLocalView }) {
    const earthBodyRef = useRef();
    const orbitControlsRef = useRef();

    const getPanelLocation = useCallback((panelId) => {
        return panelLocations[panelId] || { lat: 0, lon: 0 };
    }, [panelLocations]);

    useEffect(() => {
        const attemptRotate = () => {
            if (earthBodyRef.current && typeof earthBodyRef.current.rotateToLatLon === 'function') {
                const { lat, lon } = getPanelLocation(activePanel);
                if (lat !== undefined && lon !== undefined) {
                    console.log(`GlobeCanvas: Rotating to panel ${activePanel} at lat: ${lat}, lon: ${lon}`);
                    earthBodyRef.current.rotateToLatLon(lat, lon, 1.5);
                } else {
                    console.warn(`GlobeCanvas: panelLocation for ${activePanel} is missing lat/lon. Not rotating.`);
                }
                return true;
            }
            return false;
        };

        const isReadyImmediately = attemptRotate();
        if (!isReadyImmediately) {
            const timeoutId = setTimeout(() => {
                attemptRotate();
            }, 500);
            return () => clearTimeout(timeoutId);
        }

    }, [activePanel, getPanelLocation, isLocalView]);

    const handleZoomDetected = useCallback(({ lat, lon }) => {
        if (onZoomToLocal) {
            console.log("GlobeCanvas - handleZoomDetected: Triggered. Sending Lat/Lon to App:", lat, lon);
            onZoomToLocal({ lat, lon });
        }
    }, [onZoomToLocal]);

    return (
        <Canvas
            camera={{ position: [0, 0, 2.5], fov: 70 }}
            style={{
                position: 'absolute',
                top: 0,
                left: 0,
                width: '100%',
                height: '100%',
                zIndex: 0,
                backgroundColor: 'black'
            }}
        >
            <ambientLight intensity={0.5} />
            <pointLight position={[10, 10, 10]} intensity={1.5} />
            <pointLight position={[-10, -10, -10]} intensity={0.8} color={0x5555ff} />

            <Suspense fallback={<Html center>Loading Globe...</Html>}>
                <EarthBody
                    ref={earthBodyRef}
                    orbitControlsRef={orbitControlsRef}
                />
                <StarfieldBackground />

                <PointsOnGlobe
                    locations={globePoints ? globePoints.filter(p => (isNewsMode && p.type === 'news') || (!isNewsMode && p.type === 'stats')) : []}
                    onPointClick={onPointClick}
                />
                <ConnectionLines
                    connections={globeConnections}
                />

                {/* *** เพิ่มดาวเทียมที่นี่ *** */}
                <Satellite orbitRadius={1.1} orbitSpeed={0.05} orbitTiltDeg={25} />
                <Satellite orbitRadius={1.2} orbitSpeed={0.03} orbitTiltDeg={60} />
                <Satellite orbitRadius={1.3} orbitSpeed={0.07} orbitTiltDeg={-10} />

            </Suspense>

            <CustomOrbitControls
                controlsRef={orbitControlsRef}
                onZoomChange={handleZoomDetected}
                onExitLocalView={onExitLocalView}
                isLocalView={isLocalView}
            />
        </Canvas>
    );
}