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

const closeBtn = document.getElementById('closeBtn');
const phone = document.getElementById('phone');
const topbar = document.getElementById('topbar');

phone.classList.add('absolute', 'top-20', 'left-20');
topbar.classList.add('cursor-grab');

topbar.addEventListener('mousedown', e => {
  if (e.target.closest('button') || e.target.closest('span')) return;
  dragging = true;
  topbar.classList.add('cursor-grabbing');
  topbar.classList.remove('cursor-grab');

  const rect = phone.getBoundingClientRect();
  offsetX = e.clientX - rect.left;
  offsetY = e.clientY - rect.top;
});

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

window.addEventListener('mouseup', () => {
  if (!dragging) return;
  dragging = false;
  topbar.classList.remove('cursor-grabbing');
  topbar.classList.add('cursor-grab');
});

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

closeBtn?.addEventListener('click', () => {
  phone.classList.add('hidden');

  const parentResource = getParentResourceName();
  fetch(`https://${parentResource}/close`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({})
  });
});

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 {
    return 'gb-phone';
  }
}
