import { io, Socket } from 'socket.io-client';
import { authStore } from './auth.svelte';

export interface RaisedHand {
	userId: number;
	username: string;
	type: 'normal' | 'question';
	raisedAt: string; // Date string from JSON
}

export interface ActiveStudent {
	userId: number;
	username: string;
}

class ClassroomStore {
	socket: Socket | null = null;
	raisedHands = $state<RaisedHand[]>([]);
	activeStudent = $state<ActiveStudent | null>(null);
	isConnected = $state(false);

	constructor() {
		// Auto-connect logic could go here if we wanted it global, 
		// but better to call connect() from component mount or check auth
	}

	connect() {
		if (this.socket?.connected) return;
		if (!authStore.user) return;

		this.socket = io('http://localhost:3000/api/classroom', {
			withCredentials: true,
			transports: ['websocket'],
		});

		this.socket.on('connect', () => {
			this.isConnected = true;
			console.log('Connected to classroom');
		});

		this.socket.on('disconnect', () => {
			this.isConnected = false;
			console.log('Disconnected from classroom');
		});

		this.socket.on('state-update', (data: { raisedHands: RaisedHand[]; activeStudent: ActiveStudent | null }) => {
			this.raisedHands = data.raisedHands;
			this.activeStudent = data.activeStudent;
		});
	}

	disconnect() {
		if (this.socket) {
			this.socket.disconnect();
			this.socket = null;
			this.isConnected = false;
		}
	}

	raiseHand(type: 'normal' | 'question') {
		this.socket?.emit('raise-hand', { type });
	}

	lowerHand() {
		this.socket?.emit('lower-hand');
	}

	lowerAllHands() {
		this.socket?.emit('lower-all-hands');
	}

	pickStudent(userId: number) {
		this.socket?.emit('pick-student', { userId });
	}

	pickRandom() {
		this.socket?.emit('pick-random');
	}

	resetActive() {
		this.socket?.emit('reset-active');
	}

	endTurn() {
		this.socket?.emit('reset-active');
	}
	
	get myHand() {
		if (!authStore.user) return undefined;
		return this.raisedHands.find(h => h.userId === authStore.user?.id);
	}
}

export const classroomStore = new ClassroomStore();
