/* Turns a CrawlieEngine report object into downloadable files: a real PDF (jsPDF)
   and a self-contained HTML snapshot. Loaded on report.html and competitor-comparison.html. */
(function (global) {

  var CAT_LABELS = {
    onpage: 'On-Page SEO', content: 'Content', technical: 'Technical & Indexability',
    mobile: 'Mobile Friendliness', performance: 'Performance', social: 'Social Sharing'
  };

  function grade(score) {
    if (score >= 90) return 'A'; if (score >= 80) return 'B'; if (score >= 70) return 'C';
    if (score >= 60) return 'D'; return 'F';
  }

  function fmtDate(d) {
    return d.toLocaleDateString(undefined, { year: 'numeric', month: 'long', day: 'numeric' }) + ' at ' +
      d.toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' });
  }

  function downloadPdf(report) {
    if (!global.jspdf || !global.jspdf.jsPDF) { alert('PDF library did not load — check your internet connection and try again.'); return; }
    var doc = new global.jspdf.jsPDF({ unit: 'pt', format: 'a4' });
    var m = report.metrics, pageW = doc.internal.pageSize.getWidth(), margin = 48, y = 0;
    var purple = [90, 50, 240], ink = [27, 20, 48], muted = [107, 101, 128];

    function line(gap) { y += gap || 16; if (y > 760) { doc.addPage(); y = margin; } }
    function text(str, size, opts) {
      opts = opts || {};
      doc.setFont('helvetica', opts.bold ? 'bold' : 'normal');
      doc.setFontSize(size);
      doc.setTextColor.apply(doc, opts.color || ink);
      var maxW = pageW - margin * 2;
      var lines = doc.splitTextToSize(str, opts.maxW || maxW);
      doc.text(lines, margin, y);
      line((lines.length * (size * 1.28)) + (opts.extra || 6));
    }

    y = margin;
    doc.setFillColor.apply(doc, purple); doc.rect(0, 0, pageW, 6, 'F');
    y = margin + 14;
    text('Crawlie SEO Audit Report', 20, { bold: true });
    text(m.url, 11, { color: muted });
    text('Generated ' + fmtDate(report.generatedAt), 9.5, { color: muted, extra: 18 });

    doc.setFillColor.apply(doc, purple);
    doc.circle(margin + 34, y + 20, 34, 'F');
    doc.setTextColor(255, 255, 255); doc.setFont('helvetica', 'bold'); doc.setFontSize(22);
    doc.text(String(report.overall), margin + 34, y + 26, { align: 'center' });
    doc.setFontSize(8); doc.text('/ 100', margin + 34, y + 38, { align: 'center' });
    doc.setFontSize(13); doc.setTextColor.apply(doc, ink);
    doc.text('Overall score — grade ' + grade(report.overall), margin + 82, y + 16);
    doc.setFontSize(10); doc.setTextColor.apply(doc, muted); doc.setFont('helvetica', 'normal');
    doc.text('Weighted across on-page, content, technical, mobile, performance and social signals.', margin + 82, y + 32, { maxWidth: pageW - margin * 2 - 82 });
    y += 70;

    text('Category scores', 13, { bold: true, extra: 10 });
    Object.keys(CAT_LABELS).forEach(function (k) {
      var c = report.categories[k];
      doc.setFontSize(10.5); doc.setTextColor.apply(doc, ink); doc.setFont('helvetica', 'bold');
      doc.text(CAT_LABELS[k], margin, y);
      doc.setFont('helvetica', 'normal'); doc.setTextColor.apply(doc, muted);
      doc.text(c.score + ' / 100', pageW - margin, y, { align: 'right' });
      line(8);
      var barW = pageW - margin * 2;
      doc.setFillColor(238, 234, 255); doc.roundedRect(margin, y, barW, 6, 3, 3, 'F');
      var col = c.score >= 80 ? [24, 168, 119] : c.score >= 60 ? [239, 157, 29] : [245, 71, 107];
      doc.setFillColor.apply(doc, col); doc.roundedRect(margin, y, barW * (c.score / 100), 6, 3, 3, 'F');
      line(20);
    });

    line(8);
    text('Issues found (' + report.issues.length + ') — ranked by impact', 13, { bold: true, extra: 10 });
    if (!report.issues.length) {
      text('No issues detected — nice work.', 10.5, { color: muted });
    }
    report.issues.forEach(function (iss, i) {
      var tag = iss.severity === 'critical' ? 'CRITICAL' : iss.severity === 'warning' ? 'WARNING' : 'GOOD';
      var col = iss.severity === 'critical' ? [245, 71, 107] : iss.severity === 'warning' ? [239, 157, 29] : [24, 168, 119];
      doc.setFontSize(10.5); doc.setFont('helvetica', 'bold'); doc.setTextColor.apply(doc, col);
      doc.text('[' + tag + ']', margin, y);
      doc.setTextColor.apply(doc, ink);
      doc.text((i + 1) + '. ' + iss.title, margin + 62, y);
      line(14);
      doc.setFont('helvetica', 'normal'); doc.setFontSize(9.5); doc.setTextColor.apply(doc, muted);
      var lines = doc.splitTextToSize(iss.category + ' — ' + iss.detail, pageW - margin * 2 - 10);
      doc.text(lines, margin + 10, y);
      line(lines.length * 12 + 10);
    });

    line(10);
    text('Key metrics', 13, { bold: true, extra: 10 });
    var rows = [
      ['Word count', m.wordCount], ['Title length', m.titleLen + ' chars'],
      ['Meta description length', m.descLen + ' chars'], ['H1 tags', m.h1Count],
      ['Images missing alt text', m.imgsMissingAlt + ' / ' + m.imgCount],
      ['Internal links', m.linkInternal], ['External links', m.linkExternal],
      ['HTTPS', m.isHttps ? 'Yes' : 'No'], ['Structured data blocks', m.structuredDataCount],
      ['Readability (Flesch)', m.readability.flesch + ' — ' + m.readability.grade]
    ];
    rows.forEach(function (r) {
      doc.setFontSize(10); doc.setFont('helvetica', 'bold'); doc.setTextColor.apply(doc, ink);
      doc.text(String(r[0]), margin, y);
      doc.setFont('helvetica', 'normal'); doc.setTextColor.apply(doc, muted);
      doc.text(String(r[1]), pageW - margin, y, { align: 'right' });
      line(16);
    });

    doc.save('crawlie-seo-audit-' + (m.host || 'report') + '.pdf');
  }

  function downloadHtml(report) {
    var m = report.metrics;
    var rowsIssues = report.issues.map(function (iss, i) {
      var color = iss.severity === 'critical' ? '#f5476b' : iss.severity === 'warning' ? '#ef9d1d' : '#18a877';
      return '<tr><td style="padding:10px;border-bottom:1px solid #ece7f7;color:' + color + ';font-weight:700;white-space:nowrap;">' + iss.severity.toUpperCase() + '</td>' +
        '<td style="padding:10px;border-bottom:1px solid #ece7f7;"><strong>' + (i + 1) + '. ' + escapeHtml(iss.title) + '</strong><br><span style="color:#6b6580;font-size:13px;">' + escapeHtml(iss.category) + ' — ' + escapeHtml(iss.detail) + '</span></td></tr>';
    }).join('');

    var rowsCats = Object.keys(CAT_LABELS).map(function (k) {
      var c = report.categories[k];
      var col = c.score >= 80 ? '#18a877' : c.score >= 60 ? '#ef9d1d' : '#f5476b';
      return '<div style="margin-bottom:14px;"><div style="display:flex;justify-content:space-between;font-weight:600;font-size:14px;margin-bottom:6px;"><span>' + CAT_LABELS[k] + '</span><span style="color:' + col + '">' + c.score + '</span></div>' +
        '<div style="height:8px;background:#efeaff;border-radius:999px;"><div style="width:' + c.score + '%;height:100%;background:' + col + ';border-radius:999px;"></div></div></div>';
    }).join('');

    var html = '<!DOCTYPE html><html><head><meta charset="utf-8"><title>SEO Audit — ' + escapeHtml(m.host || m.url) + '</title>' +
      '<style>body{font-family:-apple-system,Segoe UI,Roboto,sans-serif;background:#f5f3fb;color:#1b1430;margin:0;padding:40px;}' +
      '.wrap{max-width:820px;margin:0 auto;background:#fff;border:1px solid #ece7f7;border-radius:20px;padding:40px;}' +
      'table{width:100%;border-collapse:collapse;} h1{font-size:26px;} h2{font-size:18px;margin-top:36px;}</style></head><body>' +
      '<div class="wrap"><div style="color:#8b6bff;font-weight:700;font-size:13px;text-transform:uppercase;letter-spacing:.04em;">Crawlie SEO Audit Report</div>' +
      '<h1>' + escapeHtml(m.url) + '</h1><div style="color:#6b6580;font-size:13px;">Generated ' + fmtDate(report.generatedAt) + '</div>' +
      '<div style="display:flex;align-items:center;gap:20px;margin-top:26px;">' +
      '<div style="width:96px;height:96px;border-radius:50%;background:conic-gradient(#6d4aff ' + (report.overall * 3.6) + 'deg,#ece7f7 0);display:grid;place-items:center;">' +
      '<div style="width:74px;height:74px;border-radius:50%;background:#fff;display:grid;place-items:center;font-weight:800;font-size:24px;">' + report.overall + '</div></div>' +
      '<div><div style="font-weight:800;font-size:18px;">Overall score — grade ' + grade(report.overall) + '</div><div style="color:#6b6580;font-size:14px;max-width:420px;">Weighted across on-page, content, technical, mobile, performance and social signals.</div></div></div>' +
      '<h2>Category scores</h2>' + rowsCats +
      '<h2>Issues found (' + report.issues.length + ')</h2><table>' + (rowsIssues || '<tr><td style="padding:10px;">No issues detected.</td></tr>') + '</table>' +
      '<h2>Key metrics</h2><table>' +
      metricRow('Word count', m.wordCount) + metricRow('Title length', m.titleLen + ' chars') +
      metricRow('Meta description length', m.descLen + ' chars') + metricRow('H1 tags', m.h1Count) +
      metricRow('Images missing alt text', m.imgsMissingAlt + ' / ' + m.imgCount) +
      metricRow('Internal links', m.linkInternal) + metricRow('External links', m.linkExternal) +
      metricRow('HTTPS', m.isHttps ? 'Yes' : 'No') + metricRow('Structured data blocks', m.structuredDataCount) +
      metricRow('Readability (Flesch)', m.readability.flesch + ' — ' + m.readability.grade) +
      '</table><div style="margin-top:30px;color:#a79fc2;font-size:12px;">Generated by Crawlie — free SEO audit &amp; tools.</div></div></body></html>';

    global.crawlieDownload('crawlie-seo-audit-' + (m.host || 'report') + '.html', html, 'text/html');
  }

  function metricRow(k, v) {
    return '<tr><td style="padding:8px 10px;border-bottom:1px solid #f1edfa;font-weight:600;">' + k + '</td><td style="padding:8px 10px;border-bottom:1px solid #f1edfa;text-align:right;color:#6b6580;">' + v + '</td></tr>';
  }
  function escapeHtml(s) { return String(s == null ? '' : s).replace(/[&<>"']/g, function (c) { return { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]; }); }

  global.CrawlieExport = { downloadPdf: downloadPdf, downloadHtml: downloadHtml, grade: grade, CAT_LABELS: CAT_LABELS };
})(window);

