/* ==========================================
   SHARED.JS - SMAN 1 PEMALANG QUEUE SYSTEM
   (LOCAL STORAGE VERSION)
   ========================================== */

const STATE_KEY = 'sman1_queue_state';

const DEFAULT_STATE = {
    tickets: [],
    counters: { 1: null, 2: null, 3: null, 4: null, 5: null, 6: null, 7: null, 8: null, 9: null, 10: null, 11: null },
    activeCall: null,
    settings: {
        runningText: "Selamat Datang di Penerimaan Peserta Didik Baru (PPDB) SMAN 01 Pemalang."
    }
};

function loadState() {
    const saved = localStorage.getItem(STATE_KEY);
    if (saved) {
        try {
            return JSON.parse(saved);
        } catch (e) {
            console.error('Error parsing state', e);
        }
    }
    return DEFAULT_STATE;
}

function saveState(state) {
    localStorage.setItem(STATE_KEY, JSON.stringify(state));
    // Trigger event manually for the current window (storage event only fires on OTHER tabs)
    window.dispatchEvent(new CustomEvent('localStateChanged', { detail: state }));
}

// Generate new ticket
function generateTicket(type) {
    const state = loadState();
    const typeTickets = state.tickets.filter(t => t.type === type);
    const maxNum = typeTickets.length > 0 ? Math.max(...typeTickets.map(t => parseInt(t.id.split('-')[1]))) : 0;
    const nextNum = maxNum + 1;
    
    const padded = String(nextNum).padStart(3, '0');
    const ticketId = `${type}-${padded}`;
    
    const newTicket = {
        id: ticketId,
        type: type,
        status: 'waiting',
        loket: null,
        timestamp: Date.now()
    };
    
    state.tickets.push(newTicket);
    saveState(state);
    
    return newTicket;
}

// Panggil antrian berikutnya
function callNext(loketId) {
    const state = loadState();
    const type = loketId === 11 ? 'B' : 'A';
    
    const waitingTicket = state.tickets.find(t => t.type === type && t.status === 'waiting');
    
    if (waitingTicket) {
        waitingTicket.status = 'calling';
        waitingTicket.loket = loketId;
        
        state.counters[loketId] = waitingTicket.id;
        state.activeCall = {
            ticketNumber: waitingTicket.id,
            counterNumber: loketId,
            timestamp: Date.now()
        };
        
        saveState(state);
        return true;
    }
    return false;
}

// Panggil ulang nomor yang sedang ada di loket
function recallCurrent(loketId) {
    const state = loadState();
    const currentId = state.counters[loketId];
    if (currentId) {
        state.activeCall = {
            ticketNumber: currentId,
            counterNumber: loketId,
            timestamp: Date.now()
        };
        saveState(state);
        return true;
    }
    return false;
}

// --- Text-to-Speech Engine Menggunakan Google Voice ---
function speakCall(ticketNumber, loketId, callback) {
    if (!ticketNumber) {
        if (callback) callback();
        return;
    }

    try {
        const type = ticketNumber.split('-')[0];
        const numStr = ticketNumber.split('-')[1];
        const num = parseInt(numStr, 10);
        
        let letterPhrase = type === 'A' ? "A" : "B";
        const numPhrase = isNaN(num) ? "" : spellIndonesianNumber(num);
        
        let destPhrase = loketId === 11 ? "loket pengaduan" : `loket, ${spellIndonesianNumber(loketId)}`;
        
        const fullText = `Nomor antrean, ${letterPhrase}, ${numPhrase}. Silakan menuju, ${destPhrase}.`;
        
        const lang = 'id';
        const audioUrl = `https://translate.google.com/translate_tts?ie=UTF-8&q=${encodeURIComponent(fullText)}&tl=${lang}&client=tw-ob`;
        
        const audio = new Audio(audioUrl);
        audio.onended = () => {
            if(callback) callback();
        };
        audio.onerror = () => {
            if(callback) callback();
        };
        audio.play().catch(e => {
            if(callback) callback();
        });
    } catch(err) {
        if(callback) callback();
    }
}

function spellIndonesianNumber(num) {
    const ones = ['', 'satu', 'dua', 'tiga', 'empat', 'lima', 'enam', 'tujuh', 'delapan', 'sembilan', 'sepuluh', 'sebelas'];
    if (num < 12) return ones[num];
    if (num < 20) return ones[num - 10] + ' belas';
    if (num < 100) return ones[Math.floor(num / 10)] + ' puluh ' + ones[num % 10];
    if (num < 200) return 'seratus ' + spellIndonesianNumber(num - 100);
    if (num < 1000) return ones[Math.floor(num / 100)] + ' ratus ' + spellIndonesianNumber(num % 100);
    return num.toString();
}
