let dragging = false;
let offsetX = 0;
let offsetY = 0;

const phoneEl = document.getElementById('phone');

phoneEl.addEventListener('mousedown', e => {
    if (e.target.closest('.message-input') || e.target.closest('input') || e.target.closest('button')) return;
    dragging = true;
    phoneEl.classList.add('dragging');
    const rect = phoneEl.getBoundingClientRect();
    offsetX = e.clientX - rect.left;
    offsetY = e.clientY - rect.top;
});

window.addEventListener('mousemove', e => {
    if (!dragging) return;
    phoneEl.style.left = `${e.clientX - offsetX}px`;
    phoneEl.style.top = `${e.clientY - offsetY}px`;
});

window.addEventListener('mouseup', () => {
    if (!dragging) return;
    dragging = false;
    phoneEl.classList.remove('dragging');
});

window.addEventListener('message', function(event) {
    const d = event.data;
    if (!d) return;
    
    if (d.action === 'toggle') {
        const phone = document.getElementById('phone');
        if (d.open) {
            phone.classList.remove('hidden');
            updateTime();
        } else {
            phone.classList.add('hidden');
        }
    } else if (d.action === 'receiveMessage') {
        appendMessage(d.from, d.message, 'from');
    }
});

document.getElementById('closeBtn').addEventListener('click', function() {
    fetch(`https://${GetParentResourceName()}/close`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({})
    });
});

document.getElementById('messagesApp').addEventListener('click', function() {
    document.getElementById('home').style.display = 'none';
    document.getElementById('messages').style.display = 'flex';
});

document.getElementById('sendBtn').addEventListener('click', sendMessage);

document.getElementById('msgInput').addEventListener('keydown', function(e) {
    if (e.key === 'Enter') sendMessage();
});

function sendMessage() {
    const input = document.getElementById('msgInput');
    const v = input.value.trim();
    if (!v) return;
    
    appendMessage('You', v, 'me');
    
    fetch(`https://${GetParentResourceName()}/sendMessage`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ message: v })
    }).then(res => res.json()).then(() => {
        input.value = '';
    });
}

function appendMessage(sender, text, cls) {
    const list = document.getElementById('messagesList');
    const el = document.createElement('div');
    el.className = 'msg ' + (cls || '');
    el.innerText = sender + ': ' + text;
    list.appendChild(el);
    list.scrollTop = list.scrollHeight;
}

function updateTime() {
    const t = document.getElementById('time');
    const now = new Date();
    const hh = String(now.getHours()).padStart(2, '0');
    const mm = String(now.getMinutes()).padStart(2, '0');
    t.innerText = hh + ':' + mm;
}

function GetParentResourceName() {
    try {
        return new URL(document.location).searchParams.get('parent') || window.parentResource || 'gb-phone';
    } catch (e) {
        return 'gb-phone';
    }
}