// Helpers for actually downloading and printing a coloring page.
// Strategy:
//  - Render an A4-shaped <svg> with the chosen ColoringArt embedded.
//  - Download: serialize the SVG and trigger a download as .svg (works everywhere, scales perfectly).
//  - Print: open a tiny print-only page in a new window that auto-fires window.print().

const _renderArtToHTML = (artKey, title) => {
  // Mount a hidden React tree to get the SVG markup, then serialize it.
  const host = document.createElement('div');
  host.style.cssText = 'position:fixed;left:-9999px;top:-9999px;width:600px;height:600px;';
  document.body.appendChild(host);
  const root = ReactDOM.createRoot(host);
  root.render(<ColoringArt artKey={artKey} className="w-full h-full"/>);
  // Render is async, but createRoot.render with a sync tree commits in this microtask.
  // We resolve on next animation frame to be safe.
  return new Promise((resolve) => {
    requestAnimationFrame(() => {
      requestAnimationFrame(() => {
        const svg = host.querySelector('svg');
        const inner = svg ? svg.innerHTML : '';
        const viewBox = svg ? svg.getAttribute('viewBox') || '0 0 200 200' : '0 0 200 200';
        root.unmount();
        host.remove();
        resolve({ inner, viewBox });
      });
    });
  });
};

const _buildA4Svg = ({ inner, viewBox, title, footer = 'Malfino.de', options = {} }) => {
  // A4 portrait at 96dpi-ish: 794 x 1123. We pad it.
  const W = 794, H = 1123;
  const pad = 60;
  const showTitle    = options.showTitle !== false;
  const showBranding = options.showBranding !== false;
  const showFooter   = options.showFooter !== false;
  const headerH = showTitle ? 70 : 0;
  const footerH = (showBranding || showFooter) ? 40 : 0;
  const artBoxX = pad, artBoxY = pad + headerH;
  const artBoxW = W - pad * 2;
  const artBoxH = H - pad * 2 - headerH - footerH;
  // Fit viewBox into artBox preserving aspect ratio.
  const [vbX, vbY, vbW, vbH] = viewBox.split(/\s+/).map(Number);
  const scale = Math.min(artBoxW / vbW, artBoxH / vbH);
  const drawW = vbW * scale, drawH = vbH * scale;
  const drawX = artBoxX + (artBoxW - drawW) / 2;
  const drawY = artBoxY + (artBoxH - drawH) / 2;

  let titleSvg = '';
  if (showTitle) {
    titleSvg = `
  <text x="${pad}" y="${pad + 32}" font-family="'Baloo 2', system-ui, sans-serif" font-size="28" font-weight="700" fill="#1F2A44">${_xmlEsc(title)}</text>
  <line x1="${pad}" y1="${pad + 50}" x2="${W - pad}" y2="${pad + 50}" stroke="#E7E0CE" stroke-width="2"/>`;
  }
  let footSvg = '';
  if (showBranding) {
    footSvg += `<text x="${pad}" y="${H - pad + 10}" font-family="system-ui, sans-serif" font-size="13" fill="#465069">${_xmlEsc(footer)}</text>`;
  }
  if (showFooter) {
    footSvg += `<text x="${W - pad}" y="${H - pad + 10}" text-anchor="end" font-family="system-ui, sans-serif" font-size="13" fill="#465069">Kostenlos zum Ausmalen</text>`;
  }

  return `<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}">
  <rect width="${W}" height="${H}" fill="white"/>
  ${titleSvg}
  <g transform="translate(${drawX} ${drawY}) scale(${scale}) translate(${-vbX} ${-vbY})">
    ${inner}
  </g>
  ${footSvg}
</svg>`;
};

const _xmlEsc = (s) => String(s).replace(/[<>&"']/g, c => ({'<':'&lt;','>':'&gt;','&':'&amp;','"':'&quot;',"'":'&apos;'}[c]));

const _slugify = (s) => String(s).toLowerCase()
  .replace(/ä/g,'ae').replace(/ö/g,'oe').replace(/ü/g,'ue').replace(/ß/g,'ss')
  .replace(/[^a-z0-9]+/g,'-').replace(/^-+|-+$/g,'');

// Resolve print options from settings + user premium status.
const _printOptions = () => {
  try {
    const s = loadSettings ? loadSettings() : null;
    const u = JSON.parse(localStorage.getItem('aw.user') || 'null');
    const isPrem = !!(u && u.premium && u.premium.active);
    const f = (s && s.premium && s.premium.features) || {};
    return {
      showTitle:    isPrem && f.noPrintTitle    ? false : true,
      showBranding: isPrem && f.noPrintBranding ? false : true,
      showFooter:   isPrem && f.noPrintFooter   ? false : true,
    };
  } catch { return { showTitle: true, showBranding: true, showFooter: true }; }
};

// Public API: download a single coloring as SVG.
const downloadColoring = async (item) => {
  const { inner, viewBox } = await _renderArtToHTML(item.art);
  const svg = _buildA4Svg({ inner, viewBox, title: item.title, options: _printOptions() });
  const blob = new Blob([svg], { type: 'image/svg+xml' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url; a.download = `${_slugify(item.title)}.svg`;
  document.body.appendChild(a); a.click(); a.remove();
  setTimeout(() => URL.revokeObjectURL(url), 1000);
  if (typeof bumpUserActivity === 'function') bumpUserActivity('downloads');
};

// Public API: open a print window for one coloring.
const printColoring = async (item) => {
  const { inner, viewBox } = await _renderArtToHTML(item.art);
  const svg = _buildA4Svg({ inner, viewBox, title: item.title, options: _printOptions() });
  _openPrintWindow([{ title: item.title, svg }]);
  if (typeof bumpUserActivity === 'function') bumpUserActivity('prints');
};

// Public API: print many (used by Sammelmappe "Alle drucken").
const printColoringList = async (items) => {
  const pages = [];
  const opts = _printOptions();
  for (const it of items) {
    const { inner, viewBox } = await _renderArtToHTML(it.art);
    pages.push({ title: it.title, svg: _buildA4Svg({ inner, viewBox, title: it.title, options: opts }) });
  }
  _openPrintWindow(pages);
  if (typeof bumpUserActivity === 'function') {
    for (let i = 0; i < items.length; i++) bumpUserActivity('prints');
  }
};

const _openPrintWindow = (pages) => {
  const w = window.open('', '_blank', 'width=900,height=1100');
  if (!w) {
    alert('Bitte erlaube Pop-ups, damit der Druckdialog erscheinen kann.');
    return;
  }
  const doc = w.document;
  doc.open();
  doc.write(`<!DOCTYPE html>
<html lang="de"><head><meta charset="UTF-8"/>
<title>Drucken, Malfino.de</title>
<style>
  * { box-sizing: border-box; }
  html, body { margin: 0; padding: 0; background: #f3efe4; font-family: system-ui, sans-serif; }
  .toolbar { position: sticky; top: 0; background: #1F2A44; color: white; padding: 12px 18px; display: flex; gap: 12px; align-items: center; z-index: 10; }
  .toolbar h1 { font-size: 16px; margin: 0; flex: 1; font-weight: 600; }
  .toolbar button { background: #FF8A7A; color: white; border: 0; padding: 10px 18px; border-radius: 999px; font-weight: 700; cursor: pointer; font-size: 14px; }
  .pages { padding: 24px; display: grid; gap: 24px; justify-items: center; }
  .page { background: white; box-shadow: 0 8px 24px -12px rgba(31,42,68,0.2); width: 794px; max-width: 100%; }
  .page svg { width: 100%; height: auto; display: block; }
  @media print {
    @page { size: A4 portrait; margin: 0; }
    body { background: white; }
    .toolbar { display: none; }
    .pages { padding: 0; gap: 0; }
    .page { box-shadow: none; width: 100%; page-break-after: always; }
    .page:last-child { page-break-after: auto; }
  }
</style>
</head><body>
<div class="toolbar">
  <h1>${pages.length === 1 ? 'Druckvorschau' : pages.length + ' Bilder bereit'}</h1>
  <button onclick="window.print()">🖨️ Jetzt drucken</button>
  <button onclick="window.close()" style="background:transparent;border:1px solid rgba(255,255,255,0.3);">Schließen</button>
</div>
<div class="pages">
  ${pages.map(p => `<div class="page">${p.svg}</div>`).join('')}
</div>
<script>
  window.addEventListener('load', () => setTimeout(() => window.print(), 400));
</script>
</body></html>`);
  doc.close();
};

Object.assign(window, { downloadColoring, printColoring, printColoringList });
