document.addEventListener("DOMContentLoaded", async () => {
    // Get the hash from the URL, e.g., ?hash=abc123xyz
    const urlParams = new URLSearchParams(window.location.search);
    const magicHash = urlParams.get('hash');

    if (!magicHash) {
        document.getElementById('ui-greeting').innerText = "Invalid link.";
        document.getElementById('loading-state').style.display = 'none';
        return;
    }

    try {
        const response = await fetch(`../api/?r=guest&hash=${magicHash}`);
        const data = await response.json();

        if (!response.ok) throw new Error(data.error || 'Failed to load booking');

        const booking = data.data;

        // Populate the DOM
        document.getElementById('ui-greeting').innerText = `Welcome, ${booking.guest_name}!`;
        document.getElementById('ui-prop-name').innerText = booking.property_name;
        document.getElementById('ui-prop-address').innerText = `${booking.property_address}, ${booking.city}`;
        
        document.getElementById('ui-checkin').innerText = new Date(booking.check_in).toLocaleDateString();
        document.getElementById('ui-checkout').innerText = new Date(booking.check_out).toLocaleDateString();
        
        const totalGuests = parseInt(booking.adults || 1) + parseInt(booking.children || 0);
        document.getElementById('ui-guests').innerText = totalGuests;
        document.getElementById('ui-status').innerText = booking.status.toUpperCase();

        // Handle Wi-Fi visibility
        if (booking.wifi_network) {
            document.getElementById('ui-wifi-net').innerText = booking.wifi_network;
            document.getElementById('ui-wifi-pass').innerText = booking.wifi_password;
        } else {
            document.getElementById('wifi-card').style.display = 'none';
        }

        // Swap UI states
        document.getElementById('loading-state').style.display = 'none';
        document.getElementById('portal-content').style.display = 'block';

    } catch (error) {
        document.getElementById('ui-greeting').innerText = error.message;
        document.getElementById('loading-state').style.display = 'none';
    }
});