import { Canvas } from "@react-three/fiber";
import { Experience } from "./components/Experience";
import { WelcomeUI } from "./components/WelcomeUI";
import AtomCursor from "./components/AtomCursor";
import { useState, useEffect, Suspense, lazy } from "react";
import './components/global.css';
import './components/Experience.css';

// Lazy load heavy components for better mobile performance
const LazyExperience = lazy(() => import("./components/Experience").then(module => ({ default: module.Experience })));

function App() {
  const [showMenu, setShowMenu] = useState(false);
  const [isInteractive, setIsInteractive] = useState(false);
  const [isMobile, setIsMobile] = useState(false);
  const [showAbout, setShowAbout] = useState(false);
  const [showContact, setShowContact] = useState(false);
  const [showHomeView, setShowHomeView] = useState(false);
  const [showIntro, setShowIntro] = useState(true);
  const [sceneReady, setSceneReady] = useState(false);
  const [viewportHeight, setViewportHeight] = useState('100vh');
  const [devicePerformance, setDevicePerformance] = useState('high');
  const [showCheckoutConfirm, setShowCheckoutConfirm] = useState(false);
  const initialCameraPosition = [0, 2, 5];

  useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    const sessionId = params.get('session_id');
    const fromStripeSession = sessionId?.startsWith('cs_');
    const fromCheckoutParam = params.get('checkout') === 'success';

    let fromPendingCheckout = false;
    try {
      const pending = sessionStorage.getItem('asxStripeCheckout');
      if (pending) {
        fromPendingCheckout = Date.now() - Number(pending) < 2 * 60 * 60 * 1000;
        sessionStorage.removeItem('asxStripeCheckout');
      }
    } catch {
      // sessionStorage unavailable
    }

    if (fromStripeSession || fromCheckoutParam || fromPendingCheckout) {
      const isMobileCheckoutReturn = window.innerWidth <= 768;

      setShowCheckoutConfirm(!isMobileCheckoutReturn);
      setShowIntro(false);
      setShowMenu(false);
      setShowHomeView(false);
      setIsInteractive(false);
      window.history.replaceState({}, '', window.location.pathname);
    }
  }, []);

  useEffect(() => {
    setIsInteractive(!showMenu);
    setIsMobile(window.innerWidth <= 768);

    // Detect device performance capabilities
    const detectPerformance = () => {
      const memory = navigator.deviceMemory || 4;
      const cores = navigator.hardwareConcurrency || 4;
      const connection = navigator.connection;
      
      let performance = 'high';
      if (memory < 2 || cores < 2 || (connection && connection.effectiveType === 'slow-2g')) {
        performance = 'low';
      } else if (memory < 4 || cores < 4 || (connection && connection.effectiveType === '2g')) {
        performance = 'medium';
      }
      
      setDevicePerformance(performance);
  
    };

    const handleResize = () => {
      setIsMobile(window.innerWidth <= 768);
      updateViewportHeight();
    };

    const updateViewportHeight = () => {
      if (isMobile) {
        // Use actual viewport height for mobile
        const vh = window.innerHeight * 0.01;
        document.documentElement.style.setProperty('--vh', `${vh}px`);
        setViewportHeight(`${window.innerHeight}px`);
      } else {
        setViewportHeight('100vh');
      }
    };

    // Initial setup
    updateViewportHeight();
    detectPerformance();

    // Handle mobile viewport changes (address bar show/hide)
    if (isMobile) {
      window.addEventListener('resize', handleResize);
      window.addEventListener('orientationchange', handleResize);
      
      // Handle visual viewport changes
      if (window.visualViewport) {
        window.visualViewport.addEventListener('resize', updateViewportHeight);
      }
    }

    window.addEventListener('resize', handleResize);
    return () => {
      window.removeEventListener('resize', handleResize);
      if (isMobile) {
        window.removeEventListener('orientationchange', handleResize);
        if (window.visualViewport) {
          window.visualViewport.removeEventListener('resize', updateViewportHeight);
        }
      }
    };
  }, [showMenu, isMobile]);

  useEffect(() => {
    // As a safety, hide after 1.5s even if ready flag missed
    const timer = setTimeout(() => setShowIntro(false), 1500);
    return () => clearTimeout(timer);
  }, []);

  // Dynamic Canvas settings based on device performance
  const getCanvasSettings = () => {
    const baseSettings = {
      shadows: devicePerformance !== 'low',
      camera: { position: initialCameraPosition, fov: isMobile ? 75 : 65 },
      gl: { 
        antialias: devicePerformance === 'high', 
        powerPreference: 'high-performance', 
        stencil: false, 
        depth: true, 
        preserveDrawingBuffer: false,
        alpha: false,
        logarithmicDepthBuffer: false
      },
      dpr: devicePerformance === 'low'
        ? [0.75, 1]
        : devicePerformance === 'medium'
          ? [1, 1.5]
          : isMobile
            ? [1, 2]
            : [1, 1.5],
      performance: { 
        min: devicePerformance === 'low' ? 0.5 : devicePerformance === 'medium' ? 0.7 : 0.8 
      },
      style: { 
        width: '100vw', 
        height: viewportHeight, 
        display: 'block',
        margin: 0,
        padding: 0,
        position: 'fixed',
        top: 0,
        left: 0,
        zIndex: 0
      }
    };

    return baseSettings;
  };

  return (
    <>
      <Canvas {...getCanvasSettings()}>
        <color attach="background" args={["#000000"]} />
        <Suspense fallback={null}>
          <LazyExperience 
            isInteractive={isInteractive} 
            isMobile={isMobile}
            showMenu={showMenu}
            showAbout={showAbout}
            showContact={showContact}
            showHomeView={showHomeView}
            devicePerformance={devicePerformance}
            onReady={() => setShowIntro(false)}
          />
        </Suspense>
      </Canvas>
      <div className={`intro-overlay ${showIntro ? '' : 'hide'}`}>
        <div className="intro-content">
          <img src="/textures/Asx.png" alt="@ASX" className="intro-logo" />
          <div className="loading-bar">
            <div className="loading-bar-fill"></div>
          </div>
        </div>
      </div>
      <WelcomeUI 
        setShowMenu={setShowMenu} 
        showMenu={showMenu} 
        setIsInteractive={setIsInteractive}
        isMobile={isMobile}
        setShowHomeView={setShowHomeView}
        showCheckoutConfirm={showCheckoutConfirm}
        onClearCheckoutConfirm={() => setShowCheckoutConfirm(false)}
      />
      {!isMobile && !showIntro && <AtomCursor />}
    </>
  );
}

export default App;