/* FrameBuilder - Cliente (token -> gerar) */

async function fbFetchJson(url, opts={}){
  const res = await fetch(url, opts);
  const txt = await res.text();
  try { return JSON.parse(txt); } catch(e){ throw new Error('Resposta inválida do servidor'); }
}

function byId(id){ return document.getElementById(id); }

function getToken(){
  const p = new URLSearchParams(location.search);
  return p.get('token') || '';
}

function fmtDateBR(ymd){
  if (!ymd) return '';
  const s = String(ymd).trim();
  const d = s.slice(0,10);
  const m = d.match(/^(\d{4})-(\d{2})-(\d{2})$/);
  if (!m) return s;
  return `${m[3]}/${m[2]}/${m[1]}`;
 }

let EVENT_DATA = null;

async function init(){
  const token = getToken();
  if (!token){
    byId('clientNoToken').classList.remove('d-none');
    byId('clientFormWrap').classList.add('d-none');
    return;
  }

  const data = await fbFetchJson(`api/public_get_event.php?token=${encodeURIComponent(token)}`);
  if (!data.ok){
    byId('clientNoToken').classList.remove('d-none');
    byId('clientNoToken').innerHTML = `<div class="alert alert-danger">${data.error || 'Evento inválido.'}</div>`;
    byId('clientFormWrap').classList.add('d-none');
    return;
  }

  EVENT_DATA = data;
  const ev = data.event;
  byId('eventTitle').textContent = ev.nome_evento;
  byId('eventMeta').textContent = `${ev.destino} • ${fmtDateBR(ev.data_evento)}` + (ev.endereco ? ` • ${ev.endereco}` : '');

  const max = data.config?.constraints?.nome_max_chars ?? 26;
  byId('nome').setAttribute('maxlength', String(max));
  byId('nomeHelp').textContent = `Máx: ${max} caracteres`;

  // preview inicial
  await renderPreview();

  byId('foto').addEventListener('change', renderPreview);
  byId('nome').addEventListener('input', renderPreview);

  byId('btnGerar').addEventListener('click', onGerar);
}

async function renderPreview(){
  if (!EVENT_DATA) return;
  const canvas = byId('canvas');
  const name = (byId('nome').value || '').trim() || 'SEU NOME';
  const file = byId('foto').files?.[0] || null;
  await FBRenderer.render(canvas, EVENT_DATA.config, EVENT_DATA.assets, { name, photoFile: file });
  const dataUrl = FBRenderer.canvasToPngDataUrl(canvas);
  byId('previewImg').src = dataUrl;
  byId('downloadLink').href = dataUrl;
}

async function onGerar(){
  if (!EVENT_DATA) return;
  const token = getToken();
  const nome = (byId('nome').value || '').trim();
  const foto = byId('foto').files?.[0] || null;
  const max = EVENT_DATA.config?.constraints?.nome_max_chars ?? 26;

  if (!nome){
    alert('Informe seu nome.');
    return;
  }
  if (nome.length > max){
    alert(`Nome acima do limite (${max}).`);
    return;
  }
  if (!foto){
    alert('Envie sua foto.');
    return;
  }

  const canvas = byId('canvas');
  await FBRenderer.render(canvas, EVENT_DATA.config, EVENT_DATA.assets, { name: nome, photoFile: foto });
  const imagem_base64 = FBRenderer.canvasToPngDataUrl(canvas);

  byId('btnGerar').disabled = true;
  byId('btnGerar').textContent = 'Gerando...';

  try{
    const payload = { token, nome, imagem_base64 };
    const r = await fbFetchJson('api/public_generate_frame.php', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload)
    });

    if (!r.ok) throw new Error(r.error || 'Falha ao gerar');

    byId('serverLink').classList.remove('d-none');
    byId('serverLinkA').href = r.arquivo_url;
    byId('serverLinkA').textContent = 'Abrir imagem gerada';

  } catch(e){
    alert(e.message || 'Erro ao gerar.');
  } finally {
    byId('btnGerar').disabled = false;
    byId('btnGerar').textContent = 'Gerar e salvar';
  }
}

document.addEventListener('DOMContentLoaded', init);
