import { Canvas } from '@react-three/fiber';
import { Environment, OrthographicCamera } from '@react-three/drei';
import { GelDigit } from './GelDigit';
import { GelColon } from './GelColon';
import { Suspense } from 'react';
import { format } from 'date-fns';

function Scene({ time }: { time: Date }) {
    const hours = format(time, 'HH');
    const minutes = format(time, 'mm');

    const aspect = window.innerWidth / window.innerHeight;
    const isPortrait = aspect < 1;

    let layout;
    if (isPortrait) {
        layout = {
            // Tight overlap for portrait
            h1: [-1.4, 1.4, 0], // Moved closer to center (2.0 -> 1.4)
            h2: [0.6, 1.4, 0.5],
            colon: [0, 0, 0],
            m1: [-1.4, -1.4, 0], // Moved closer to center (-2.0 -> -1.4)
            m2: [0.6, -1.4, 0.5],
            scale: 1.6,
        }
    } else {
        layout = {
            // Tight overlap for landscape
            h1: [-2.5, 0, 0],
            h2: [-1.0, 0, 0.5],
            colon: [0, 0, 0],
            m1: [1.0, 0, 0],
            m2: [2.5, 0, 0.5],
            scale: 2.0,
        }
    }

    // Colors from reference: Blue/Cyan for digits
    const cBlue1 = "#29B6F6";
    const cBlue2 = "#4FC3F7";

    return (
        <group scale={layout.scale}>
            <GelDigit value={hours[0]} position={layout.h1 as any} color={cBlue1} />
            <GelDigit value={hours[1]} position={layout.h2 as any} color={cBlue2} />

            <GelColon position={layout.colon as any} />

            <GelDigit value={minutes[0]} position={layout.m1 as any} color={cBlue1} />
            <GelDigit value={minutes[1]} position={layout.m2 as any} color={cBlue2} />
        </group>
    );
}

export default function ClockCanvas({ time }: { time: Date }) {
    return (
        <div style={{ width: '100%', height: '100%' }}>
            <Canvas style={{ background: 'black' }}>
                <Suspense fallback={null}>
                    <OrthographicCamera makeDefault position={[0, 0, 10]} zoom={40} />

                    <ambientLight intensity={0.5} />
                    <pointLight position={[10, 10, 10]} intensity={1} />
                    <pointLight position={[-10, -10, -10]} intensity={0.5} />

                    <Environment preset="city" />

                    <Scene time={time} />
                </Suspense>
            </Canvas>
        </div>
    );
}
