import * as THREE from 'three';
import { state } from '../state.js';
import tableTextureUrl from '/textures/wood.png';

export function createTable(x, y, z, rotY) {
    const woodMaterial = new THREE.MeshPhongMaterial({
        map: state.loader.load(tableTextureUrl),
        shininess: 10,
        specular: 0x222222
    });

    const tableTopGeo = new THREE.BoxGeometry(1.5, 0.1, 0.8);
    const tableTop = new THREE.Mesh(tableTopGeo, woodMaterial);
    tableTop.position.y = 0.5;
    tableTop.castShadow = true;
    tableTop.receiveShadow = true;

    // Table Legs
    const legThickness = 0.1;
    const legHeight = 0.5; // Same height as tableTop.position.y
    const legGeometry = new THREE.BoxGeometry(legThickness, legHeight, legThickness);

    const legOffset = (1.5 / 2) - (legThickness * 1.5); // Half table width - some margin
    const depthOffset = (0.8 / 2) - (legThickness * 1.5); // Half table depth - some margin

    const createLeg = (lx, lz) => {
        const leg = new THREE.Mesh(legGeometry, woodMaterial);
        leg.position.set(lx, legHeight / 2, lz);
        leg.castShadow = true;
        leg.receiveShadow = true;
        return leg;
    };

    const table = new THREE.Group();
    table.add(tableTop);
    // Add the four legs
    table.add(createLeg(-legOffset, depthOffset));
    table.add(createLeg(legOffset, depthOffset));
    table.add(createLeg(-legOffset, -depthOffset));
    table.add(createLeg(legOffset, -depthOffset));

    table.position.set(x, y, z);
    table.rotation.y = rotY;
    state.scene.add(table);

    return table;
}