// Tidal — Geração de Crachá · Evolis Primacy · 638x1012px

// ─── Layout do crachá (fundo desenhado em canvas, sem marca de empresa) ───
const CARD_W = 638;
const CARD_H = 1012;

// Cores por papel
const ROLE_COLORS = {
  admin:        { bg: '#1F5755', text: '#FFFFFF', label: 'Administrador' },
  staff:        { bg: '#5C8AB8', text: '#FFFFFF', label: 'Staff'         },
  crew:         { bg: '#5C7E4F', text: '#FFFFFF', label: 'Tripulação'    },
  ops:          { bg: '#5C8DAE', text: '#FFFFFF', label: 'Operações'     },
  catering:     { bg: '#7A6EA6', text: '#FFFFFF', label: 'Catering'      },
  terceirizada: { bg: '#5F7A8C', text: '#FFFFFF', label: 'Terceirizada'  },
  guest:        { bg: '#C68A1F', text: '#FFFFFF', label: 'Visitante'     },
};

// Primeiros dois nomes
const twoNames = (nome) => {
  if (!nome) return '';
  const parts = nome.trim().split(/\s+/);
  return parts.slice(0, 2).join(' ').toUpperCase();
};

// Iniciais (2 letras)
const initials = (nome) => {
  if (!nome) return '?';
  const parts = nome.trim().split(/\s+/);
  return parts.slice(0, 2).map(p => p[0]).join('').toUpperCase();
};


// ─── Render do crachá em CANVAS (tudo embutido: fundo, foto, textos e QR como pixels) ───

const _loadImage = (src) => new Promise((resolve, reject) => {
  const img = new Image();
  img.onload = () => resolve(img);
  img.onerror = () => reject(new Error('img falhou'));
  img.src = src;
});

// Garante a lib de QR (qrcode-generator) carregada — arquivo LOCAL, sem depender de CDN/internet
// (o CDN jsdelivr falhava em rede restrita e o crachá saía sem QR, em silêncio)
const ensureQRLib = () => new Promise((resolve, reject) => {
  if (window._qrgen) { resolve(); return; }
  const s = document.createElement('script');
  s.src = 'vendor/qrcode.js';
  s.onload = () => {
    window._qrgen = window.qrcode;
    window._qrgen ? resolve() : reject(new Error('lib de QR inválida'));
  };
  s.onerror = () => reject(new Error('vendor/qrcode.js não encontrado'));
  document.head.appendChild(s);
});

// Garante a fonte Inter carregada (pro texto sair certo no canvas)
const ensureFont = async () => {
  try {
    if (!document.getElementById('cracha-inter-font')) {
      const l = document.createElement('link');
      l.id = 'cracha-inter-font'; l.rel = 'stylesheet';
      l.href = 'https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap';
      document.head.appendChild(l);
    }
    if (document.fonts && document.fonts.load) {
      await Promise.all([
        document.fonts.load('700 32px Inter'),
        document.fonts.load('600 18px Inter'),
        document.fonts.load('400 20px Inter'),
      ]);
    }
  } catch (e) {}
};

const _roundRect = (ctx, x, y, w, h, r) => {
  ctx.beginPath(); ctx.moveTo(x+r, y);
  ctx.arcTo(x+w, y, x+w, y+h, r); ctx.arcTo(x+w, y+h, x, y+h, r);
  ctx.arcTo(x, y+h, x, y, r); ctx.arcTo(x, y, x+w, y, r); ctx.closePath();
};

// desenha imagem em "cover" dentro de um quadrado
const _drawCover = (ctx, img, dx, dy, dsize) => {
  const iw = img.naturalWidth, ih = img.naturalHeight;
  const scale = Math.max(dsize/iw, dsize/ih);
  const sw = dsize/scale, sh = dsize/scale;
  ctx.drawImage(img, (iw-sw)/2, (ih-sh)/2, sw, sh, dx, dy, dsize, dsize);
};

// Fundo do crachá desenhado em canvas — identidade Genesis, sem logo de empresa
const drawCardBackground = (ctx) => {
  // base creme
  ctx.fillStyle = '#FBF7F0'; ctx.fillRect(0, 0, CARD_W, CARD_H);

  // faixa superior teal
  const gTop = ctx.createLinearGradient(0, 0, CARD_W, 0);
  gTop.addColorStop(0, '#1F5755'); gTop.addColorStop(1, '#173F3E');
  ctx.fillStyle = gTop; ctx.fillRect(0, 0, CARD_W, 96);
  ctx.fillStyle = '#D9694B'; ctx.fillRect(0, 96, CARD_W, 5);

  // marca + título
  ctx.textBaseline = 'middle';
  ctx.fillStyle = 'rgba(255,255,255,0.16)';
  _roundRect(ctx, 24, 24, 48, 48, 10); ctx.fill();
  ctx.fillStyle = '#FFFFFF'; ctx.font = '600 26px Georgia, serif'; ctx.textAlign = 'center';
  ctx.fillText('G', 48, 51);
  ctx.textAlign = 'left';
  try { ctx.letterSpacing = '4px'; } catch(e) {}
  ctx.font = '600 22px Inter, sans-serif';
  ctx.fillText('PORTAL GENESIS', 92, 42);
  try { ctx.letterSpacing = '2px'; } catch(e) {}
  ctx.font = '400 13px Inter, sans-serif'; ctx.fillStyle = 'rgba(255,255,255,0.75)';
  ctx.fillText('MPSV GENESIS I', 92, 66);
  try { ctx.letterSpacing = '0px'; } catch(e) {}

  // faixa inferior
  ctx.fillStyle = gTop; ctx.fillRect(0, CARD_H-40, CARD_W, 40);
  ctx.fillStyle = '#D9694B'; ctx.fillRect(0, CARD_H-45, CARD_W, 5);
  ctx.fillStyle = 'rgba(255,255,255,0.85)'; ctx.font = '400 12px Inter, sans-serif'; ctx.textAlign = 'center';
  try { ctx.letterSpacing = '2px'; } catch(e) {}
  ctx.fillText('IDENTIFICAÇÃO DE BORDO', CARD_W/2, CARD_H-24);
  try { ctx.letterSpacing = '0px'; } catch(e) {}
  ctx.textBaseline = 'top';
};

const getQRHost = () => {
  try {
    const cfg = JSON.parse(localStorage.getItem('genesis_cracha_qr') || '{}');
    if (cfg.host && String(cfg.host).trim()) return cfg.host.trim();
  } catch(e) {}
  return window.location.host;
};

const renderCardCanvas = async (user) => {
  const role = ROLE_COLORS[user.role] || ROLE_COLORS.crew;
  const nome = twoNames(user.nome);
  const gid = user.genesis_id || '—';
  const funcao = (user.funcao || '').toUpperCase();
  const empresa = (user.empresa || '').toUpperCase();
  const ini = initials(user.nome);
  const scanUrl = `${window.location.protocol}//${getQRHost()}/gangway-scan.html?scan=${gid}`;

  const canvas = document.createElement('canvas');
  canvas.width = CARD_W; canvas.height = CARD_H;
  const ctx = canvas.getContext('2d');

  // 1) Fundo (desenhado — sem imagem externa)
  drawCardBackground(ctx);

  let y = 155;
  // 2) Foto (ou iniciais)
  const px = (CARD_W - 400)/2;
  ctx.save(); _roundRect(ctx, px, y, 400, 400, 6); ctx.clip();
  let drew = false;
  if (user.foto_url) { try { const ph = await _loadImage(user.foto_url); _drawCover(ctx, ph, px, y, 400); drew = true; } catch(e) {} }
  if (!drew) {
    ctx.fillStyle = role.bg; ctx.fillRect(px, y, 400, 400);
    ctx.fillStyle = 'rgba(255,255,255,0.85)';
    ctx.font = '700 140px Inter, sans-serif'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
    ctx.fillText(ini, CARD_W/2, y+200);
  }
  ctx.restore();
  y += 400;

  ctx.textAlign = 'center'; ctx.textBaseline = 'top';

  // 3) Badge de papel
  y += 10;
  ctx.font = '600 18px Inter, sans-serif';
  try { ctx.letterSpacing = '2px'; } catch(e) {}
  const labelUp = role.label.toUpperCase();
  const bw = ctx.measureText(labelUp).width + 44, bh = 30;
  _roundRect(ctx, (CARD_W-bw)/2, y, bw, bh, 4); ctx.fillStyle = role.bg; ctx.fill();
  ctx.fillStyle = role.text; ctx.fillText(labelUp, CARD_W/2, y+7);
  try { ctx.letterSpacing = '0px'; } catch(e) {}
  y += bh;

  // 4) Nome
  y += 14; ctx.fillStyle = '#1a3a1a'; ctx.font = '700 32px Inter, sans-serif';
  try { ctx.letterSpacing = '1px'; } catch(e) {}
  ctx.fillText(nome, CARD_W/2, y);
  try { ctx.letterSpacing = '0px'; } catch(e) {}
  y += 36;

  // 5) Função
  if (funcao) { y += 8; ctx.font = '600 22px Inter, sans-serif'; ctx.fillText(funcao, CARD_W/2, y); y += 25; }
  // 6) Empresa
  if (empresa) { y += 4; ctx.fillStyle = '#3a5a3a'; ctx.font = '400 20px Inter, sans-serif'; ctx.fillText(empresa, CARD_W/2, y); y += 22; }

  // 7) QR (pixels — embutido de vez)
  y += 18;
  const qrBox = 200, qrInner = 188, qrPad = 6, qx = (CARD_W - qrBox)/2;
  ctx.fillStyle = '#ffffff'; ctx.fillRect(qx, y, qrBox, qrBox);
  ctx.strokeStyle = '#cccccc'; ctx.lineWidth = 1; ctx.strokeRect(qx+0.5, y+0.5, qrBox-1, qrBox-1);
  try {
    if (window._qrgen) {
      const qr = window._qrgen(0, 'M'); qr.addData(scanUrl); qr.make();
      const n = qr.getModuleCount(), cell = qrInner / n;
      ctx.fillStyle = '#000000';
      for (let r=0;r<n;r++) for (let c=0;c<n;c++)
        if (qr.isDark(r,c)) ctx.fillRect(qx+qrPad + c*cell, y+qrPad + r*cell, cell+0.6, cell+0.6);
    } else { ctx.fillStyle = '#666'; ctx.font = '400 12px Inter, sans-serif'; ctx.fillText(gid, CARD_W/2, y+94); }
  } catch(e) {}
  y += qrBox;

  // 8) Genesis ID
  y += 10; ctx.fillStyle = '#1a3a1a'; ctx.font = '400 20px Inter, sans-serif';
  try { ctx.letterSpacing = '2px'; } catch(e) {}
  ctx.fillText(gid, CARD_W/2, y);
  try { ctx.letterSpacing = '0px'; } catch(e) {}

  return canvas;
};

const _canvasToBlob = (canvas) => new Promise((resolve) => canvas.toBlob((b) => resolve(b), 'image/png'));
const _safe = (s, fb) => String(s||fb).replace(/[^a-zA-Z0-9À-ÿ\s]/g,'').trim().replace(/\s+/g,'_');

// ─── Abrir/baixar 1 crachá como PNG ───
const printCracha = async (user) => {
  try { await ensureQRLib(); }
  catch (e) { alert('Não foi possível carregar o gerador de QR Code (vendor/qrcode.js). Recarregue a página e tente de novo.'); return; }
  await ensureFont();
  const canvas = await renderCardCanvas(user);
  const dataUrl = canvas.toDataURL('image/png');
  const w = window.open('', '_blank');
  if (w) { w.document.write(`<title>Cracha ${user.genesis_id||''}</title><body style="margin:0;background:#222;display:flex;justify-content:center"><img src="${dataUrl}" style="max-height:100vh"/></body>`); w.document.close(); }
  else { const a = document.createElement('a'); a.href = dataUrl; a.download = `cracha_${_safe(user.nome, user.genesis_id||'crew')}.png`; a.click(); }
};

// ─── Exportar ZIP — cada crachá um PNG, QR embutido ───
const exportCrachasZip = async (users, toast) => {
  if (!window.JSZip) { toast.push({icon:'x', title:'JSZip não carregado', body:'Recarregue a página e tente de novo.'}); return; }
  toast.push({icon:'check', title:`Gerando ${users.length} crachá(s)…`, body:'Renderizando as imagens, aguarde.'});
  try { await ensureQRLib(); }
  catch (e) { toast.push({icon:'x', title:'Gerador de QR não carregado', body:'vendor/qrcode.js ausente — recarregue a página.'}); return; }
  await ensureFont();
  const zip = new window.JSZip();
  let ok = 0;
  for (let i=0;i<users.length;i++) {
    try {
      const canvas = await renderCardCanvas(users[i]);
      const blob = await _canvasToBlob(canvas);
      zip.file(`${_safe(users[i].empresa,'SEM_EMPRESA')}__${_safe(users[i].nome, users[i].genesis_id||('user_'+(i+1)))}.png`, blob);
      ok++;
    } catch(e) {}
  }
  const blob = await zip.generateAsync({type:'blob'});
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a'); a.href = url;
  a.download = `crachas_genesis_${new Date().toISOString().slice(0,10)}.zip`; a.click();
  URL.revokeObjectURL(url);
  toast.push({icon:'check', title:`ZIP com ${ok} crachá(s) em PNG baixado!`});
};

Object.assign(window, { printCracha, exportCrachasZip, renderCardCanvas, twoNames });
