(() => {
  'use strict';
  const state={data:null,view:'overview'};
  const $=(s,p=document)=>p.querySelector(s), $$=(s,p=document)=>[...p.querySelectorAll(s)];
  document.addEventListener('DOMContentLoaded',init);
  async function init(){bind(); const ok=await checkSession(); if(ok) showDashboard();}
  function bind(){
    $('#loginForm').addEventListener('submit',login); $('#logoutBtn').addEventListener('click',logout); $('#refreshBtn').addEventListener('click',loadDashboard); $('#closeDetail').addEventListener('click',()=>$('#detailModal').close());
    $$('.side-link').forEach(b=>b.addEventListener('click',()=>switchView(b.dataset.view))); $$('[data-go]').forEach(b=>b.addEventListener('click',()=>switchView(b.dataset.go)));
    $('#bookingSearch').addEventListener('input',renderBookings); $('#bookingFilter').addEventListener('change',renderBookings); $('#leadSearch').addEventListener('input',renderLeads);
  }
  async function checkSession(){try{return (await fetch('/api/admin/me')).ok}catch{return false}}
  async function login(e){e.preventDefault();const form=e.currentTarget,status=$('.form-status',form),body=Object.fromEntries(new FormData(form));status.textContent='Logowanie...';try{const r=await fetch('/api/admin/login',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)});if(!r.ok)throw 0;status.textContent='';showDashboard()}catch{status.textContent='Nieprawidłowy e-mail lub hasło.'}}
  async function logout(){await fetch('/api/admin/logout',{method:'POST'});location.reload()}
  async function showDashboard(){$('#loginView').hidden=true;$('#dashboardView').hidden=false;await loadDashboard()}
  async function loadDashboard(){try{const r=await fetch('/api/admin/dashboard');if(r.status===401)return location.reload();state.data=await r.json();renderAll();toast('Dane odświeżone')}catch{toast('Nie udało się pobrać danych')}}
  function renderAll(){const {stats}=state.data;$('#statBookings').textContent=stats.bookings;$('#statPending').textContent=stats.pending;$('#statLeads').textContent=stats.leads;$('#statRevenue').textContent=formatMixedRevenue();renderRecent();renderBookings();renderLeads()}
  function formatMixedRevenue(){const b=state.data.bookings;const pl=b.filter(x=>x.quote?.currency==='PLN'&&x.status!=='cancelled').reduce((s,x)=>s+x.quote.total,0),us=b.filter(x=>x.quote?.currency==='USD'&&x.status!=='cancelled').reduce((s,x)=>s+x.quote.total,0);return `${pl.toLocaleString('pl-PL')} zł / $${us.toLocaleString('en-US')}`}
  function renderRecent(){renderActivity($('#recentBookings'),state.data.bookings.slice(0,6),'booking');renderActivity($('#recentLeads'),state.data.leads.slice(0,6),'lead')}
  function renderActivity(el,items,type){el.innerHTML=items.length?items.map(x=>`<button class="activity-item" data-detail="${type}" data-id="${x.id}" style="border-left:0;border-right:0;border-top:0;background:transparent;width:100%;text-align:left"><span class="activity-icon">${type==='booking'?'3D':'@'}</span><span><b>${esc(x.name)}</b><small>${type==='booking'?`${esc(x.reference)} • ${esc(x.address)}`:esc(x.email)}</small></span><span>${relative(x.createdAt)}</span></button>`).join(''):'<div class="empty">Brak danych</div>';bindDetails(el)}
  function renderBookings(){if(!state.data)return;const q=$('#bookingSearch').value.toLowerCase(),filter=$('#bookingFilter').value;const rows=state.data.bookings.filter(b=>(filter==='all'||b.status===filter)&&JSON.stringify(b).toLowerCase().includes(q));$('#bookingsTable').innerHTML=rows.length?rows.map(b=>`<tr><td><span class="market-badge">${b.market}</span><b>${esc(b.reference)}</b><small>${dateTime(b.createdAt)}</small></td><td><b>${esc(b.name)}</b><small>${esc(b.email)}<br>${esc(b.phone)}</small></td><td><b>${esc(b.date)} • ${esc(b.slot)}</b><small>${esc(b.city||'')}</small></td><td><b>${esc(b.address)}</b><small>${b.quote?.area||''} ${esc(b.quote?.unit||'')} • ${esc(b.quote?.type||'')}</small></td><td><b>${money(b.quote?.total,b.quote?.currency)}</b><small>base ${money(b.quote?.base,b.quote?.currency)}</small></td><td><select class="status-select" data-status-id="${b.id}">${['pending','confirmed','awaiting_payment','paid','completed','cancelled'].map(s=>`<option ${b.status===s?'selected':''}>${s}</option>`).join('')}</select></td><td><div class="row-actions"><button class="icon-btn" title="Szczegóły" data-detail="booking" data-id="${b.id}">•••</button><a class="icon-btn" title="Kalendarz" href="/api/bookings/${b.id}.ics">＋</a><a class="icon-btn" title="E-mail" href="mailto:${encodeURIComponent(b.email)}">✉</a></div></td></tr>`).join(''):'<tr><td colspan="7"><div class="empty">Brak pasujących rezerwacji</div></td></tr>';$$('[data-status-id]').forEach(s=>s.addEventListener('change',()=>updateStatus(s.dataset.statusId,s.value)));bindDetails($('#bookingsTable'))}
  function renderLeads(){if(!state.data)return;const q=$('#leadSearch').value.toLowerCase();const rows=state.data.leads.filter(l=>JSON.stringify(l).toLowerCase().includes(q));$('#leadsGrid').innerHTML=rows.length?rows.map(l=>`<article class="lead-card"><div class="lead-card-head"><div><span class="market-badge">${l.market}</span><h3>${esc(l.name)}</h3><small>${dateTime(l.createdAt)}</small></div><button class="icon-btn" data-detail="lead" data-id="${l.id}">•••</button></div><p>${esc(l.message)}</p><div class="lead-card-links"><a href="mailto:${encodeURIComponent(l.email)}">E-mail</a>${l.phone?`<a href="tel:${encodeURIComponent(l.phone)}">Telefon</a>`:''}</div></article>`).join(''):'<div class="empty">Brak pasujących leadów</div>';bindDetails($('#leadsGrid'))}
  function bindDetails(parent){$$('[data-detail]',parent).forEach(b=>b.addEventListener('click',()=>openDetail(b.dataset.detail,b.dataset.id)))}
  function openDetail(type,id){const item=(type==='booking'?state.data.bookings:state.data.leads).find(x=>x.id===id);if(!item)return;$('#detailContent').innerHTML=type==='booking'?bookingDetail(item):leadDetail(item);$('#detailModal').showModal()}
  function bookingDetail(b){return `<span class="kicker">${esc(b.reference)}</span><h2>${esc(b.name)}</h2><div class="detail-grid"><div class="detail-item"><span>STATUS</span><b>${esc(b.status)}</b></div><div class="detail-item"><span>MARKET</span><b>${esc(b.market)}</b></div><div class="detail-item"><span>DATE</span><b>${esc(b.date)} • ${esc(b.slot)}</b></div><div class="detail-item"><span>PRICE</span><b>${money(b.quote?.total,b.quote?.currency)}</b></div><div class="detail-item"><span>EMAIL</span><b>${esc(b.email)}</b></div><div class="detail-item"><span>PHONE</span><b>${esc(b.phone)}</b></div><div class="detail-item"><span>ADDRESS</span><b>${esc(b.address)}</b></div><div class="detail-item"><span>AREA</span><b>${b.quote?.area||''} ${esc(b.quote?.unit||'')}</b></div></div><div class="detail-notes">${esc(b.notes||'Brak dodatkowych informacji.')}</div>`}
  function leadDetail(l){return `<span class="kicker">LEAD • ${esc(l.market)}</span><h2>${esc(l.name)}</h2><div class="detail-grid"><div class="detail-item"><span>EMAIL</span><b>${esc(l.email)}</b></div><div class="detail-item"><span>PHONE</span><b>${esc(l.phone||'—')}</b></div><div class="detail-item"><span>COMPANY</span><b>${esc(l.company||'—')}</b></div><div class="detail-item"><span>DATE</span><b>${dateTime(l.createdAt)}</b></div></div><div class="detail-notes">${esc(l.message)}</div>`}
  async function updateStatus(id,status){try{const r=await fetch(`/api/admin/bookings/${id}`,{method:'PATCH',headers:{'Content-Type':'application/json'},body:JSON.stringify({status})});if(!r.ok)throw 0;const b=state.data.bookings.find(x=>x.id===id);b.status=status;renderAll();toast('Status zapisany')}catch{toast('Nie udało się zapisać statusu')}}
  function switchView(view){state.view=view;$$('.side-link').forEach(b=>b.classList.toggle('active',b.dataset.view===view));$$('.admin-view').forEach(v=>v.classList.toggle('active',v.dataset.adminView===view));$('#viewTitle').textContent={overview:'Overview',bookings:'Rezerwacje',leads:'Leady'}[view]}
  function money(v,c){if(v==null)return'—';return new Intl.NumberFormat(c==='PLN'?'pl-PL':'en-US',{style:'currency',currency:c||'USD',maximumFractionDigits:0}).format(v)}
  function dateTime(v){return new Intl.DateTimeFormat('pl-PL',{dateStyle:'medium',timeStyle:'short'}).format(new Date(v))}
  function relative(v){const h=Math.round((Date.now()-new Date(v))/36e5);return h<1?'teraz':h<24?`${h}h`:`${Math.round(h/24)}d`}
  function esc(v){return String(v??'').replace(/[&<>'"]/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;',"'":'&#39;','"':'&quot;'}[c]))}
  function toast(m){const el=$('#toast');el.textContent=m;el.classList.add('show');clearTimeout(toast.t);toast.t=setTimeout(()=>el.classList.remove('show'),2500)}
})();
