/**
 * ALGA ARENA — Fragment System
 * Scattered starting shards that transition into positions
 */

'use strict';

window.CinematicFragments = (() => {
    let fragments = [];
    const isReduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    const count = isReduced ? 5 : (window.innerWidth < 768 ? 10 : 35);

    const init = (scene) => {
        const fragMat = new THREE.MeshPhysicalMaterial({
            color: 0x00d4ff,
            roughness: 0.1,
            metalness: 0.2,
            transmission: 0.8,
            transparent: true,
            opacity: 0.8,
            flatShading: true
        });

        for (let i = 0; i < count; i++) {
            const size = 0.08 + Math.random() * 0.2;
            const geom = new THREE.TetrahedronGeometry(size);
            const mesh = new THREE.Mesh(geom, fragMat);

            const angle = Math.random() * Math.PI * 2;
            const radius = 3.5 + Math.random() * 4.5;

            mesh.userData = {
                originalPos: new THREE.Vector3(
                    Math.cos(angle) * radius,
                    (Math.random() - 0.5) * 5.0,
                    Math.sin(angle) * radius
                ),
                targetPos: new THREE.Vector3(
                    Math.cos(angle) * (1.2 + Math.random() * 0.3),
                    (Math.random() - 0.5) * 1.2,
                    Math.sin(angle) * (1.2 + Math.random() * 0.3)
                ),
                rotSpeed: new THREE.Vector3(
                    (Math.random() - 0.5) * 1.5,
                    (Math.random() - 0.5) * 1.5,
                    0
                )
            };

            mesh.position.copy(mesh.userData.originalPos);
            mesh.rotation.set(Math.random() * Math.PI, Math.random() * Math.PI, 0);

            scene.add(mesh);
            fragments.push(mesh);
        }
    };

    const update = (delta, time) => {
        fragments.forEach(frag => {
            frag.rotation.x += frag.userData.rotSpeed.x * delta * 0.2;
            frag.rotation.y += frag.userData.rotSpeed.y * delta * 0.2;
        });
    };

    const getFragments = () => fragments;

    return { init, update, getFragments };
})();
