/* FrameBuilder - Admin Builder */

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 num(v, d){
  const n = Number(v);
  return Number.isFinite(n) ? n : d;
}

function collectConfig(){
  const schema_version = '1.0';
  const constraints = {
    nome_max_chars: num(byId('cfg_nome_max_chars').value, 26),
    foto_formats: ['jpg','jpeg','png'],
    fundo_formats: ['jpg','jpeg','png','bmp']
  };

  // background
  const bgType = byId('bg_type').value;
  const background = { type: bgType };
  if (bgType === 'solid') {
    background.solid = { color: byId('bg_solid_color').value || '#ffffff' };
  }
  if (bgType === 'gradient') {
    background.gradient = {
      color_a: byId('bg_grad_a').value || '#0F172A',
      color_b: byId('bg_grad_b').value || '#2563EB',
      angle: num(byId('bg_grad_angle').value, 90)
    };
  }
  if (bgType === 'image') {
    background.image = {
      asset_id: num(byId('bg_asset_id').value, 0) || null,
      zoom: num(byId('bg_zoom').value, 1.0),
      x: num(byId('bg_x').value, 0),
      y: num(byId('bg_y').value, 0),
      rotate: num(byId('bg_rotate').value, 0),
      fit: byId('bg_fit').value
    };
  }

  // title
  const titleType = byId('title_type').value;
  const title = { type: titleType };
  if (titleType === 'text') {
    title.text = {
      value: byId('title_text_value').value || '',
      font_family: byId('title_font_family').value || 'Arial',
      font_size: num(byId('title_font_size').value, 72),
      font_weight: num(byId('title_font_weight').value, 700),
      color: byId('title_color').value || '#ffffff',
      align: byId('title_align').value,
      x: num(byId('title_x').value, 540),
      y: num(byId('title_y').value, 180),
      rotate: num(byId('title_rotate').value, 0)
    };
  } else {
    title.image = {
      asset_id: num(byId('title_asset_id').value, 0) || null,
      w: num(byId('title_w').value, 600),
      h: num(byId('title_h').value, 180),
      x: num(byId('title_img_x').value, 240),
      y: num(byId('title_img_y').value, 120),
      rotate: num(byId('title_img_rotate').value, 0)
    };
  }

  // photo
  const photo_slot = {
    x: num(byId('photo_x').value, 540),
    y: num(byId('photo_y').value, 840),
    radius: num(byId('photo_radius').value, 340),
    border: {
      enabled: byId('photo_border_enabled').checked,
      color: byId('photo_border_color').value || '#ffffff',
      width: num(byId('photo_border_width').value, 10)
    }
  };

  // name bar
  const name_bar = {
    x: num(byId('bar_x').value, 120),
    y: num(byId('bar_y').value, 1320),
    w: num(byId('bar_w').value, 840),
    h: num(byId('bar_h').value, 170),
    border_radius: num(byId('bar_radius').value, 18),
    fill: { color: byId('bar_color').value || '#ffffff', opacity: num(byId('bar_opacity').value, 0.92) },
    stroke: { enabled: byId('bar_stroke_enabled').checked, color: byId('bar_stroke_color').value || '#000000', width: num(byId('bar_stroke_width').value, 2) },
    shadow: { enabled: byId('bar_shadow_enabled').checked, blur: num(byId('bar_shadow_blur').value, 12), x: num(byId('bar_shadow_x').value, 0), y: num(byId('bar_shadow_y').value, 6), opacity: num(byId('bar_shadow_opacity').value, 0.25) }
  };

  // name text
  const name_text = {
    font_family: byId('name_font_family').value || 'Arial',
    font_size: num(byId('name_font_size').value, 64),
    font_weight: num(byId('name_font_weight').value, 800),
    color: byId('name_color').value || '#111111',
    align: byId('name_align').value,
    x: num(byId('name_x').value, 540),
    y: num(byId('name_y').value, 1435)
  };

  // subtitle (fixo do admin)
  const subtitle_text = {
    value: byId('sub_value').value || '',
    font_family: byId('sub_font_family').value || 'Arial',
    font_size: num(byId('sub_font_size').value, 36),
    font_weight: num(byId('sub_font_weight').value, 600),
    color: byId('sub_color').value || '#ffffff',
    align: byId('sub_align').value,
    x: num(byId('sub_x').value, 540),
    y: num(byId('sub_y').value, 1530)
  };

  // footer
  const footerType = byId('footer_type').value;
  const footer = { type: footerType, align: byId('footer_align').value };
  if (footerType === 'text') {
    footer.text = {
      value: byId('footer_text_value').value || '',
      font_family: byId('footer_font_family').value || 'Arial',
      font_size: num(byId('footer_font_size').value, 28),
      font_weight: num(byId('footer_font_weight').value, 600),
      color: byId('footer_color').value || '#ffffff',
      padding_x: num(byId('footer_padding_x').value, 80),
      y: num(byId('footer_y').value, 1860)
    };
  } else {
    footer.image = {
      asset_id: num(byId('footer_asset_id').value, 0) || null,
      w: num(byId('footer_w').value, 240),
      h: num(byId('footer_h').value, 80),
      padding_x: num(byId('footer_padding_x').value, 80),
      y: num(byId('footer_img_y').value, 1830)
    };
  }

  return {
    schema_version,
    canvas: { width: 1080, height: 1920 },
    constraints,
    layers: {
      background,
      title,
      photo_slot,
      name_bar,
      name_text,
      subtitle_text,
      footer
    }
  };
}

function applyConfigToForm(cfg){
  // defaults
  cfg = cfg || {};
  const c = cfg.constraints || {};
  byId('cfg_nome_max_chars').value = c.nome_max_chars ?? 26;

  const L = cfg.layers || {};

  // background
  const bg = L.background || {type:'solid', solid:{color:'#ffffff'}};
  byId('bg_type').value = bg.type || 'solid';
  byId('bg_solid_color').value = bg.solid?.color || '#ffffff';
  byId('bg_grad_a').value = bg.gradient?.color_a || '#0F172A';
  byId('bg_grad_b').value = bg.gradient?.color_b || '#2563EB';
  byId('bg_grad_angle').value = bg.gradient?.angle ?? 90;
  byId('bg_asset_id').value = bg.image?.asset_id || '';
  byId('bg_zoom').value = bg.image?.zoom ?? 1.0;
  byId('bg_x').value = bg.image?.x ?? 0;
  byId('bg_y').value = bg.image?.y ?? 0;
  byId('bg_rotate').value = bg.image?.rotate ?? 0;
  byId('bg_fit').value = bg.image?.fit || 'cover';

  // title
  const title = L.title || {type:'text', text:{value:''}};
  byId('title_type').value = title.type || 'text';
  byId('title_text_value').value = title.text?.value || '';
  byId('title_font_family').value = title.text?.font_family || 'Montserrat';
  byId('title_font_size').value = title.text?.font_size ?? 72;
  byId('title_font_weight').value = title.text?.font_weight ?? 700;
  byId('title_color').value = title.text?.color || '#ffffff';
  byId('title_align').value = title.text?.align || 'center';
  byId('title_x').value = title.text?.x ?? 540;
  byId('title_y').value = title.text?.y ?? 180;
  byId('title_rotate').value = title.text?.rotate ?? 0;

  byId('title_asset_id').value = title.image?.asset_id || '';
  byId('title_w').value = title.image?.w ?? 600;
  byId('title_h').value = title.image?.h ?? 180;
  byId('title_img_x').value = title.image?.x ?? 240;
  byId('title_img_y').value = title.image?.y ?? 120;
  byId('title_img_rotate').value = title.image?.rotate ?? 0;

  // photo
  const p = L.photo_slot || {};
  byId('photo_x').value = p.x ?? 540;
  byId('photo_y').value = p.y ?? 840;
  byId('photo_radius').value = p.radius ?? 340;
  byId('photo_border_enabled').checked = (p.border?.enabled ?? true);
  byId('photo_border_color').value = p.border?.color || '#ffffff';
  byId('photo_border_width').value = p.border?.width ?? 10;

  // bar
  const b = L.name_bar || {};
  byId('bar_x').value = b.x ?? 120;
  byId('bar_y').value = b.y ?? 1320;
  byId('bar_w').value = b.w ?? 840;
  byId('bar_h').value = b.h ?? 170;
  byId('bar_radius').value = b.border_radius ?? 18;
  byId('bar_color').value = b.fill?.color || '#ffffff';
  byId('bar_opacity').value = b.fill?.opacity ?? 0.92;

  byId('bar_stroke_enabled').checked = (b.stroke?.enabled ?? false);
  byId('bar_stroke_color').value = b.stroke?.color || '#000000';
  byId('bar_stroke_width').value = b.stroke?.width ?? 2;

  byId('bar_shadow_enabled').checked = (b.shadow?.enabled ?? false);
  byId('bar_shadow_blur').value = b.shadow?.blur ?? 12;
  byId('bar_shadow_x').value = b.shadow?.x ?? 0;
  byId('bar_shadow_y').value = b.shadow?.y ?? 6;
  byId('bar_shadow_opacity').value = b.shadow?.opacity ?? 0.25;

  // name text
  const nt = L.name_text || {};
  byId('name_font_family').value = nt.font_family || 'Montserrat';
  byId('name_font_size').value = nt.font_size ?? 64;
  byId('name_font_weight').value = nt.font_weight ?? 800;
  byId('name_color').value = nt.color || '#111111';
  byId('name_align').value = nt.align || 'center';
  byId('name_x').value = nt.x ?? 540;
  byId('name_y').value = nt.y ?? 1435;

  // subtitle
  const st = L.subtitle_text || {};
  byId('sub_value').value = st.value || '';
  byId('sub_font_family').value = st.font_family || 'Montserrat';
  byId('sub_font_size').value = st.font_size ?? 36;
  byId('sub_font_weight').value = st.font_weight ?? 600;
  byId('sub_color').value = st.color || '#ffffff';
  byId('sub_align').value = st.align || 'center';
  byId('sub_x').value = st.x ?? 540;
  byId('sub_y').value = st.y ?? 1530;

  // footer
  const ft = L.footer || {type:'text', align:'center'};
  byId('footer_type').value = ft.type || 'text';
  byId('footer_align').value = ft.align || 'center';
  byId('footer_text_value').value = ft.text?.value || '';
  byId('footer_font_family').value = ft.text?.font_family || 'Montserrat';
  byId('footer_font_size').value = ft.text?.font_size ?? 28;
  byId('footer_font_weight').value = ft.text?.font_weight ?? 600;
  byId('footer_color').value = ft.text?.color || '#ffffff';
  byId('footer_padding_x').value = (ft.text?.padding_x ?? ft.image?.padding_x ?? 80);
  byId('footer_y').value = ft.text?.y ?? 1860;

  byId('footer_asset_id').value = ft.image?.asset_id || '';
  byId('footer_w').value = ft.image?.w ?? 240;
  byId('footer_h').value = ft.image?.h ?? 80;
  byId('footer_img_y').value = ft.image?.y ?? 1830;

  toggleSections();
}

function toggleSections(){
  // background
  const bgType = byId('bg_type').value;
  byId('bg_solid_group').style.display = (bgType==='solid') ? '' : 'none';
  byId('bg_grad_group').style.display = (bgType==='gradient') ? '' : 'none';
  byId('bg_img_group').style.display = (bgType==='image') ? '' : 'none';

  // title
  const tType = byId('title_type').value;
  byId('title_text_group').style.display = (tType==='text') ? '' : 'none';
  byId('title_img_group').style.display = (tType==='image') ? '' : 'none';

  // footer
  const fType = byId('footer_type').value;
  byId('footer_text_group').style.display = (fType==='text') ? '' : 'none';
  byId('footer_img_group').style.display = (fType==='image') ? '' : 'none';
}

async function uploadAsset(inputEl, targetIdEl){
  if (!inputEl.files || !inputEl.files[0]) return null;
  const fd = new FormData();
  fd.append('file', inputEl.files[0]);
  const r = await fbFetchJson('../api/admin_upload_asset.php', { method:'POST', body: fd });
  if (!r.ok) throw new Error(r.error || 'Falha ao enviar asset');
  targetIdEl.value = r.asset.id;
  // limpa file
  inputEl.value = '';
  return r.asset;
}



let EVENT_ID = null;
let ASSETS = {};

function absUrl(rel){
  try { return new URL(rel, window.location.origin).toString(); } catch(e){ return rel; }
}

function setAssetThumb(assetIdInputId, imgId){
  const imgEl = byId(imgId);
  if (!imgEl) return;
  const id = String((byId(assetIdInputId)?.value || '')).trim();
  const rel = (id && ASSETS) ? ASSETS[id] : null;
  if (rel) {
    imgEl.src = absUrl(rel);
    imgEl.style.display = '';
  } else {
    imgEl.removeAttribute('src');
    imgEl.style.display = 'none';
  }
}


function absUrl(rel){
  try { return new URL(rel, window.location.origin).toString(); } catch(e){ return rel; }
}

function setAssetThumb(assetIdInputId, imgId){
  const imgEl = byId(imgId);
  if (!imgEl) return;
  const id = String(byId(assetIdInputId)?.value || "").trim();
  const rel = (id && ASSETS) ? ASSETS[id] : null;
  if (rel) {
    imgEl.src = absUrl(rel);
    imgEl.style.display = "";
  } else {
    imgEl.removeAttribute("src");
    imgEl.style.display = "none";
  }
}


async function loadEvent(){
  const r = await fbFetchJson('../api/admin_get_event.php?id=' + encodeURIComponent(EVENT_ID));
  if (!r.ok) throw new Error(r.error || 'Evento não encontrado');
  byId('evt_nome').textContent = r.event.nome_evento;
  byId('evt_data').textContent = r.event.data_evento;
  byId('evt_destino').textContent = r.event.destino;
  byId('evt_status').textContent = r.event.status;
  byId('evt_token').value = r.event.token_publico;

  const absLink = new URL('../index.php?token=' + r.event.token_publico, window.location.href).toString();
  const linkInput = byId('evt_link_input');
  if (linkInput) linkInput.value = absLink;
  byId('evt_link').href = absLink;

  ASSETS = r.assets || {};
  const cfg = r.config || {};
  applyConfigToForm(cfg);
  setAssetThumb('bg_asset_id','bg_asset_thumb');
  await renderPreview();
}

async function renderPreview(){
  const cfg = collectConfig();
  // usa placeholder de foto
  const canvas = byId('builderCanvas');
  await FBRenderer.render(canvas, cfg, ASSETS, { name: 'NOME DO CLIENTE' });
}

async function saveEvent(){
  const cfg = collectConfig();
  const r = await fbFetchJson('../api/admin_save_event.php', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ id: EVENT_ID, config: cfg })
  });
  if (!r.ok) throw new Error(r.error || 'Falha ao salvar');
  await loadEvent();
}

async function publishEvent(status){
  const r = await fbFetchJson('../api/admin_set_event_status.php', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ id: EVENT_ID, status })
  });
  if (!r.ok) throw new Error(r.error || 'Falha ao atualizar status');
  await loadEvent();
}

window.addEventListener('DOMContentLoaded', async ()=>{
  EVENT_ID = Number(document.body.dataset.eventId || 0);

  // Tooltips (Bootstrap)
  if (window.bootstrap && window.bootstrap.Tooltip) {
    document.querySelectorAll('[data-bs-toggle="tooltip"]').forEach(el=>{
      new bootstrap.Tooltip(el);
    });
  }

  // Copiar link do cliente
  const btnCopy = byId('btnCopyLink');
  if (btnCopy) {
    btnCopy.addEventListener('click', async ()=>{
      const v = byId('evt_link_input')?.value || '';
      if (!v) return;
      try {
        await navigator.clipboard.writeText(v);
        alert('Link copiado.');
      } catch(e) {
        alert('Não foi possível copiar.');
      }
    });
  }

  // Thumb do fundo
  const bgId = byId('bg_asset_id');
  if (bgId) {
    bgId.addEventListener('input', ()=> setAssetThumb('bg_asset_id','bg_asset_thumb'));
  }


  byId('bg_type').addEventListener('change', ()=>{ toggleSections(); setAssetThumb('bg_asset_id','bg_asset_thumb'); renderPreview(); });
  byId('title_type').addEventListener('change', ()=>{ toggleSections(); renderPreview(); });
  byId('footer_type').addEventListener('change', ()=>{ toggleSections(); renderPreview(); });

  // render preview em qualquer input (leve)
  document.querySelectorAll('input,select,textarea').forEach(el=>{
    el.addEventListener('input', ()=>{ /* só atualiza se for leve */ });
  });

  byId('btnPreview').addEventListener('click', async ()=>{
    try{ await renderPreview(); } catch(e){ alert(e.message); }
  });

  byId('btnSave').addEventListener('click', async ()=>{
    try{ await saveEvent(); alert('Salvo com sucesso.'); } catch(e){ alert(e.message); }
  });

  byId('btnPublish').addEventListener('click', async ()=>{
    try{ await publishEvent('published'); alert('Evento publicado.'); } catch(e){ alert(e.message); }
  });
  byId('btnArchive').addEventListener('click', async ()=>{
    try{ await publishEvent('archived'); alert('Evento arquivado.'); } catch(e){ alert(e.message); }
  });

  // uploads
  byId('bg_upload').addEventListener('change', async ()=>{
    try{ const a = await uploadAsset(byId('bg_upload'), byId('bg_asset_id')); if (a && a.id){ ASSETS[String(a.id)] = (a.url || a.arquivo); } byId('bg_type').value = 'image'; toggleSections(); setAssetThumb('bg_asset_id','bg_asset_thumb'); await renderPreview(); } catch(e){ alert(e.message); }
  });
  byId('title_upload').addEventListener('change', async ()=>{
    try{ const a = await uploadAsset(byId('title_upload'), byId('title_asset_id')); if (a && a.id){ ASSETS[String(a.id)] = (a.url || a.arquivo); } byId('title_type').value = 'image'; toggleSections(); await renderPreview(); } catch(e){ alert(e.message); }
  });
  byId('footer_upload').addEventListener('change', async ()=>{
    try{ const a = await uploadAsset(byId('footer_upload'), byId('footer_asset_id')); if (a && a.id){ ASSETS[String(a.id)] = (a.url || a.arquivo); } byId('footer_type').value = 'image'; toggleSections(); await renderPreview(); } catch(e){ alert(e.message); }
  });

  try {
    await loadEvent();
  } catch(e) {
    alert(e.message);
  }
});
