<canvas id="tablet-canvas"></canvas>
<script>
    // @ts-ignore
    import * as THREE from "three";
    // @ts-ignore
    import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";

    // Three.js scene setup
    const canvas = document.getElementById(
        "tablet-canvas",
    ) as HTMLCanvasElement;
    const scene = new THREE.Scene();
    const camera = new THREE.PerspectiveCamera(
        75,
        canvas.clientWidth / canvas.clientHeight,
        0.1,
        1000,
    );
    const renderer = new THREE.WebGLRenderer({
        canvas,
        alpha: true,
        antialias: true,
    });

    renderer.setSize(canvas.clientWidth, canvas.clientHeight);
    renderer.setClearColor(0x000000, 0);

    // Create dashboard textures
    const createDashboardTexture = (type: string) => {
        const canvas = document.createElement("canvas");
        canvas.width = 512;
        canvas.height = 768;
        const ctx = canvas.getContext("2d")!;

        // Background
        ctx.fillStyle = "#f5f5f5";
        ctx.fillRect(0, 0, 512, 768);

        // Draw different dashboard layouts
        ctx.strokeStyle = "#000";
        ctx.fillStyle = "#000";
        ctx.lineWidth = 2;

        if (type === "grid") {
            // Detailed productivity dashboard
            ctx.font = "bold 20px Arial";
            ctx.fillText("My Dashboard", 30, 40);
            ctx.font = "12px Arial";
            ctx.fillStyle = "#666";
            ctx.fillText("Monday, Oct 14 • 12:34 PM", 30, 60);

            // TODO Widget
            ctx.fillStyle = "#000";
            ctx.strokeRect(30, 80, 220, 180);
            ctx.font = "bold 14px Arial";
            ctx.fillText("Today's Tasks", 40, 105);

            const todos = [
                { text: "Review PR #234", done: true },
                { text: "Deploy to prod", done: true },
                { text: "Team standup 2pm", done: false },
                { text: "Finish docs", done: false },
            ];

            todos.forEach((todo, i) => {
                const y = 130 + i * 30;
                // Checkbox
                ctx.strokeRect(45, y - 12, 14, 14);
                if (todo.done) {
                    ctx.fillStyle = "#000";
                    ctx.fillRect(48, y - 9, 8, 8);
                }
                // Text
                ctx.font = "12px Arial";
                ctx.fillStyle = todo.done ? "#999" : "#000";
                ctx.fillText(todo.text, 68, y);
            });

            // Monero Price Widget
            ctx.fillStyle = "#000";
            ctx.strokeRect(270, 80, 210, 180);
            ctx.font = "bold 14px Arial";
            ctx.fillText("Monero (XMR)", 280, 105);
            ctx.font = "bold 32px Arial";
            ctx.fillText("$168.42", 280, 150);
            ctx.font = "14px Arial";
            ctx.fillStyle = "#2ecc71";
            ctx.fillText("+5.2% (24h)", 280, 175);

            // Mini chart
            ctx.strokeStyle = "#2ecc71";
            ctx.lineWidth = 2;
            ctx.beginPath();
            const chartPoints = [0, -5, 3, -2, 8, 12, 15, 10, 18, 22, 20];
            chartPoints.forEach((val, i) => {
                const x = 280 + i * 18;
                const y = 220 - val;
                if (i === 0) ctx.moveTo(x, y);
                else ctx.lineTo(x, y);
            });
            ctx.stroke();
            ctx.lineWidth = 2;
            ctx.strokeStyle = "#000";

            // Notion Assignments Widget
            ctx.fillStyle = "#000";
            ctx.strokeRect(30, 280, 220, 160);
            ctx.font = "bold 14px Arial";
            ctx.fillText("Notion - Assignments", 40, 305);

            const assignments = [
                { title: "Q4 Roadmap", due: "Oct 18" },
                { title: "Design Review", due: "Oct 20" },
                { title: "API Spec Doc", due: "Oct 25" },
            ];

            assignments.forEach((item, i) => {
                const y = 335 + i * 35;
                ctx.font = "12px Arial";
                ctx.fillStyle = "#000";
                ctx.fillText("•", 45, y);
                ctx.fillText(item.title, 60, y);
                ctx.font = "10px Arial";
                ctx.fillStyle = "#999";
                ctx.fillText("Due " + item.due, 60, y + 15);
            });

            // Custom HTML Widget
            ctx.fillStyle = "#000";
            ctx.strokeRect(270, 280, 210, 160);
            ctx.font = "bold 14px Arial";
            ctx.fillText("</> Custom HTML", 280, 305);

            // Mock HTML code
            ctx.font = "10px monospace";
            ctx.fillStyle = "#666";
            ctx.fillText('<div class="widget">', 280, 330);
            ctx.fillText("  <h2>Hello</h2>", 280, 345);
            ctx.fillText("  <p>Custom</p>", 280, 360);
            ctx.fillText("  render()", 280, 375);
            ctx.fillText("</div>", 280, 390);

            // Quick Stats Widget
            ctx.fillStyle = "#000";
            ctx.strokeRect(30, 460, 450, 100);
            ctx.font = "bold 14px Arial";
            ctx.fillText("Quick Stats", 40, 485);

            // Three stat boxes
            const stats = [
                { label: "Tasks Done", value: "12/16" },
                { label: "Focus Time", value: "3.5h" },
                { label: "Streak", value: "7 days" },
            ];

            stats.forEach((stat, i) => {
                const x = 50 + i * 145;
                ctx.font = "bold 24px Arial";
                ctx.fillText(stat.value, x, 520);
                ctx.font = "11px Arial";
                ctx.fillStyle = "#888";
                ctx.fillText(stat.label, x, 540);
                ctx.fillStyle = "#000";
            });
        } else if (type === "weather") {
            // Weather-focused layout
            ctx.font = "bold 80px Arial";
            ctx.fillText("72°", 40, 180);
            ctx.font = "24px Arial";
            ctx.fillText("Partly Cloudy", 40, 220);

            // Draw simple sun icon
            ctx.beginPath();
            ctx.arc(400, 130, 40, 0, Math.PI * 2);
            ctx.stroke();

            // Week forecast
            const days = ["MON", "TUE", "WED", "THU", "FRI"];
            days.forEach((day, i) => {
                const x = 40 + i * 90;
                ctx.font = "12px Arial";
                ctx.fillText(day, x, 320);
                ctx.font = "20px Arial";
                ctx.fillText("7" + i, x, 360);
            });

            // Time widget
            ctx.strokeRect(40, 420, 430, 120);
            ctx.font = "bold 60px Arial";
            ctx.fillStyle = "#000";
            ctx.fillText("2:34 PM", 60, 490);
            ctx.font = "18px Arial";
            ctx.fillStyle = "#666";
            ctx.fillText("Monday, October 14", 60, 520);
        } else if (type === "crypto") {
            // Crypto dashboard
            ctx.font = "bold 20px Arial";
            ctx.fillText("Portfolio", 40, 60);

            const cryptos = [
                { name: "BTC", price: "$64,234", change: "+2.4%" },
                { name: "ETH", price: "$3,421", change: "+1.8%" },
                { name: "SOL", price: "$142", change: "-0.5%" },
            ];

            cryptos.forEach((crypto, i) => {
                const y = 120 + i * 100;
                ctx.font = "bold 18px Arial";
                ctx.fillText(crypto.name, 40, y);
                ctx.font = "24px Arial";
                ctx.fillText(crypto.price, 40, y + 35);
                ctx.font = "16px Arial";
                ctx.fillText(crypto.change, 40, y + 60);

                // Simple chart line
                ctx.beginPath();
                ctx.moveTo(250, y + 20);
                for (let j = 0; j < 10; j++) {
                    ctx.lineTo(250 + j * 22, y + 20 + Math.random() * 40 - 20);
                }
                ctx.stroke();
            });

            // Stoic quote widget
            ctx.fillStyle = "#000";
            ctx.strokeRect(40, 450, 430, 110);
            ctx.font = "italic 20px Arial";
            ctx.fillStyle = "#222";
            ctx.fillText('"You have power over', 60, 485);
            ctx.fillText('your mind, not outside events."', 60, 515);
            ctx.font = "16px Arial";
            ctx.fillStyle = "#666";
            ctx.fillText("— Marcus Aurelius", 60, 545);
        }

        return new THREE.CanvasTexture(canvas);
    };

    // Create tablet frame (improved 3-part design)
    const createTablet = () => {
        const group = new THREE.Group();

        // Create dashboard textures
        const dashboardTextures = [
            createDashboardTexture("grid"),
            createDashboardTexture("weather"),
            createDashboardTexture("crypto"),
        ];

        // Main screen (e-ink display) with dashboard texture
        const screenGeometry = new THREE.BoxGeometry(4, 6, 0.06);
        const screenMaterial = new THREE.MeshStandardMaterial({
            map: dashboardTextures[0],
            roughness: 0.9,
            metalness: 0.05,
        });
        const screen = new THREE.Mesh(screenGeometry, screenMaterial);
        screen.userData.textures = dashboardTextures;
        screen.userData.currentTexture = 0;
        screen.position.z = 0.04;
        group.add(screen);

        // Frame parts (3-part modular system with better detail)
        const frameMaterial = new THREE.MeshStandardMaterial({
            color: 0x0a0a0a,
            roughness: 0.6,
            metalness: 0.3,
        });

        // Top frame part - flush with screen
        const topFrame = new THREE.Mesh(
            new THREE.BoxGeometry(4.2, 0.2, 0.15),
            frameMaterial,
        );
        topFrame.position.y = 3.1;
        topFrame.position.z = 0.04;
        group.add(topFrame);

        // Side frames (left and right) - flush with screen
        const sideFrame = new THREE.Mesh(
            new THREE.BoxGeometry(0.1, 6, 0.15),
            frameMaterial,
        );
        sideFrame.position.x = -2.05;
        sideFrame.position.z = 0.04;
        group.add(sideFrame);

        const rightSideFrame = sideFrame.clone();
        rightSideFrame.position.x = 2.05;
        group.add(rightSideFrame);

        // Bottom frame part - flush with screen
        const bottomFrame = new THREE.Mesh(
            new THREE.BoxGeometry(4.2, 0.2, 0.15),
            frameMaterial,
        );
        bottomFrame.position.y = -3.1;
        bottomFrame.position.z = 0.04;
        group.add(bottomFrame);

        // Back plate with mounting points
        const backPlate = new THREE.Mesh(
            new THREE.BoxGeometry(4.5, 6.5, 0.12),
            frameMaterial,
        );
        backPlate.position.z = -0.18;
        group.add(backPlate);

        // Add modular connection indicators (small dots)
        const connectionMaterial = new THREE.MeshStandardMaterial({
            color: 0x333333,
            roughness: 0.5,
            metalness: 0.5,
        });

        for (let i = 0; i < 3; i++) {
            const dot = new THREE.Mesh(
                new THREE.SphereGeometry(0.04, 8, 8),
                connectionMaterial,
            );
            dot.position.set(-2.13, 2 - i * 2, 0.17);
            group.add(dot);

            const dotRight = dot.clone();
            dotRight.position.x = 2.13;
            group.add(dotRight);
        }

        return group;
    };

    const tablet = createTablet();
    scene.add(tablet);

    // Get screen for texture animation
    const screen = tablet.children.find(
        (child: any) => child.userData.textures,
    ) as THREE.Mesh;
    let lastTextureChange = Date.now();
    const textureChangeInterval = 4000; // 4 seconds

    // Lighting
    const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
    scene.add(ambientLight);

    const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
    directionalLight.position.set(5, 5, 5);
    scene.add(directionalLight);

    const rimLight = new THREE.DirectionalLight(0xff6b6b, 0.3);
    rimLight.position.set(-5, 0, -5);
    scene.add(rimLight);

    camera.position.set(0, 0, 6);

    // Add OrbitControls for user interaction
    const controls = new OrbitControls(camera, canvas);
    controls.enableDamping = true;
    controls.dampingFactor = 0.05;
    controls.enableZoom = true;
    controls.enablePan = false;
    controls.minDistance = 4;
    controls.maxDistance = 12;
    controls.autoRotate = true;
    controls.autoRotateSpeed = 0.5;

    const animate = () => {
        requestAnimationFrame(animate);

        // Update controls
        controls.update();

        // Handle dashboard texture transitions
        const now = Date.now();
        if (now - lastTextureChange > textureChangeInterval) {
            const material = screen.material as THREE.MeshStandardMaterial;
            const nextTexture =
                (screen.userData.currentTexture + 1) %
                screen.userData.textures.length;

            // Fade out/in effect via opacity
            const fadeProgress = Math.min(
                (now - lastTextureChange - textureChangeInterval) / 500,
                1,
            );

            if (fadeProgress >= 1) {
                // Switch texture
                material.map = screen.userData.textures[nextTexture];
                material.needsUpdate = true;
                screen.userData.currentTexture = nextTexture;
                lastTextureChange = now;
            }
        }

        renderer.render(scene, camera);
    };

    animate();

    // Handle window resize
    window.addEventListener("resize", () => {
        camera.aspect = canvas.clientWidth / canvas.clientHeight;
        camera.updateProjectionMatrix();
        renderer.setSize(canvas.clientWidth, canvas.clientHeight);
    });
</script>
