// PDF-Export: Score mit Markierungen, Kommentare, Checkliste, Probenplan

async function exportAnalysisPdf(piece, annotations) {
  const { jsPDF } = window.jspdf;
  const pdf = new jsPDF('p', 'mm', 'a4');
  const W = 210, H = 297, M = 15;
  const CW = W - 2 * M; // content width
  let y = M;

  // Farben als RGB-Arrays
  const phaseRgb = {
    V1: [124, 58, 237],
    V2: [8, 145, 178],
    V3: [217, 119, 6],
    V4: [5, 150, 105],
  };
  const black = [28, 25, 23];
  const gray = [120, 113, 108];
  const lightGray = [231, 229, 228];

  function checkPage(needed) {
    if (y + needed > H - M) {
      pdf.addPage();
      y = M;
    }
  }

  function drawLine() {
    pdf.setDrawColor(...lightGray);
    pdf.setLineWidth(0.3);
    pdf.line(M, y, W - M, y);
    y += 4;
  }

  // ============ TITELSEITE ============

  // Farbiger Header-Balken
  pdf.setFillColor(...phaseRgb.V1);
  pdf.rect(0, 0, W, 6, 'F');
  // Gradient-Effekt: 4 Streifen
  const stripeW = W / 4;
  window.PHASE_ORDER.forEach((p, i) => {
    pdf.setFillColor(...phaseRgb[p]);
    pdf.rect(i * stripeW, 0, stripeW, 5, 'F');
  });

  y = 30;

  // Logo
  pdf.setFontSize(11);
  pdf.setTextColor(255, 255, 255);
  pdf.setFillColor(...black);
  pdf.roundedRect(M, y - 6, 18, 9, 2, 2, 'F');
  pdf.text('4V', M + 9, y, { align: 'center' });

  pdf.setTextColor(...gray);
  pdf.setFontSize(10);
  pdf.text('4-V Methode', M + 22, y);
  y += 16;

  // Titel
  pdf.setTextColor(...black);
  pdf.setFontSize(26);
  pdf.setFont('helvetica', 'bold');
  const titleLines = pdf.splitTextToSize(piece.title || 'Ohne Titel', CW);
  pdf.text(titleLines, M, y);
  y += titleLines.length * 10 + 2;

  if (piece.composer) {
    pdf.setFontSize(14);
    pdf.setFont('helvetica', 'normal');
    pdf.setTextColor(...gray);
    pdf.text(piece.composer, M, y);
    y += 8;
  }

  pdf.setFontSize(10);
  pdf.setTextColor(...gray);
  pdf.text('4-V Analyse — exportiert am ' + new Date().toLocaleDateString('de-DE', {
    day: '2-digit', month: 'long', year: 'numeric',
  }), M, y);
  y += 6;

  // Kurzstatistik
  y += 6;
  drawLine();
  const pins = annotations.pins || [];
  const rehearsals = annotations.rehearsals || [];
  const checklist = annotations.checklist || {};

  const totalChecks = window.PHASE_ORDER.reduce((s, p) => {
    const naCount = window.CHECKLISTS[p].filter((_, i) => checklist[`${p}-${i}-na`]).length;
    return s + window.CHECKLISTS[p].length - naCount;
  }, 0);
  const doneChecks = window.PHASE_ORDER.reduce((s, p) =>
    s + window.CHECKLISTS[p].filter((_, i) => checklist[`${p}-${i}`]).length, 0);

  pdf.setFontSize(10);
  pdf.setFont('helvetica', 'bold');
  pdf.setTextColor(...black);

  const stats = [
    `${pins.length} Kommentar${pins.length === 1 ? '' : 'e'}`,
    `${doneChecks}/${totalChecks} Checkliste`,
    `${rehearsals.length} Probe${rehearsals.length === 1 ? '' : 'n'}`,
  ];
  pdf.text(stats.join('   |   '), M, y);
  y += 4;

  // Phase-Balken
  y += 4;
  const barH = 4, barGap = 3;
  window.PHASE_ORDER.forEach(p => {
    const items = window.CHECKLISTS[p];
    const naCount = items.filter((_, i) => checklist[`${p}-${i}-na`]).length;
    const relevant = items.length - naCount;
    const done = items.filter((_, i) => checklist[`${p}-${i}`]).length;
    const pct = relevant ? done / relevant : 0;

    pdf.setFillColor(240, 240, 238);
    pdf.roundedRect(M + 20, y - 3, CW - 20, barH, 1, 1, 'F');

    if (pct > 0) {
      pdf.setFillColor(...phaseRgb[p]);
      pdf.roundedRect(M + 20, y - 3, Math.max(2, (CW - 20) * pct), barH, 1, 1, 'F');
    }

    pdf.setFontSize(9);
    pdf.setFont('helvetica', 'bold');
    pdf.setTextColor(...phaseRgb[p]);
    pdf.text(p, M, y);
    pdf.setFont('helvetica', 'normal');
    pdf.setTextColor(...gray);
    pdf.text(`${Math.round(pct * 100)}%`, M + 8, y);

    y += barH + barGap;
  });

  // ============ NOTEN MIT MARKIERUNGEN ============

  const pageWraps = document.querySelectorAll('.page-wrap');
  if (pageWraps.length > 0) {
    pdf.addPage();
    y = M;

    pdf.setFontSize(16);
    pdf.setFont('helvetica', 'bold');
    pdf.setTextColor(...black);
    pdf.text('Noten mit Markierungen', M, y);
    y += 10;

    for (const wrap of pageWraps) {
      try {
        const canvas = await html2canvas(wrap, {
          scale: 2,
          useCORS: true,
          backgroundColor: '#ffffff',
          logging: false,
        });

        const imgData = canvas.toDataURL('image/jpeg', 0.92);
        const ratio = canvas.height / canvas.width;
        const imgW = CW;
        const imgH = imgW * ratio;

        checkPage(imgH + 5);
        pdf.addImage(imgData, 'JPEG', M, y, imgW, imgH);
        y += imgH + 8;
      } catch (err) {
        console.error('Score capture failed:', err);
      }
    }
  }

  // ============ KOMMENTARE ============

  if (pins.length > 0) {
    pdf.addPage();
    y = M;

    pdf.setFontSize(16);
    pdf.setFont('helvetica', 'bold');
    pdf.setTextColor(...black);
    pdf.text('Kommentare', M, y);
    y += 10;

    window.PHASE_ORDER.forEach(phase => {
      const phasePins = pins.filter(p => p.phase === phase);
      if (phasePins.length === 0) return;

      const meta = window.PHASES[phase];
      checkPage(20);

      // Phase-Header
      pdf.setFillColor(...phaseRgb[phase]);
      pdf.roundedRect(M, y - 4, 14, 6, 1.5, 1.5, 'F');
      pdf.setFontSize(8);
      pdf.setFont('helvetica', 'bold');
      pdf.setTextColor(255, 255, 255);
      pdf.text(phase, M + 7, y, { align: 'center' });

      pdf.setFontSize(12);
      pdf.setTextColor(...black);
      pdf.text(meta.name, M + 18, y);

      pdf.setFontSize(9);
      pdf.setTextColor(...gray);
      pdf.text(`(${phasePins.length})`, M + 18 + pdf.getTextWidth(meta.name) + 3, y);
      y += 8;

      // Einzelne Kommentare
      phasePins.forEach((pin, idx) => {
        const num = pins.indexOf(pin) + 1;
        checkPage(22);

        // Pin-Nummer
        pdf.setFillColor(...phaseRgb[phase]);
        pdf.circle(M + 3, y - 1.5, 3, 'F');
        pdf.setFontSize(7);
        pdf.setFont('helvetica', 'bold');
        pdf.setTextColor(255, 255, 255);
        pdf.text(String(num), M + 3, y, { align: 'center' });

        // Kommentar-Text
        pdf.setFontSize(10);
        pdf.setFont('helvetica', 'normal');
        pdf.setTextColor(...black);
        const text = pin.text || '(leer)';
        const lines = pdf.splitTextToSize(text, CW - 14);
        pdf.text(lines, M + 10, y);
        y += lines.length * 4.5 + 1;

        // Sub-Tags
        if (pin.subtags && pin.subtags.length > 0) {
          pdf.setFontSize(8);
          pdf.setTextColor(...gray);
          pdf.text(pin.subtags.join('  ·  '), M + 10, y);
          y += 4;
        }

        // Datum
        if (pin.createdAt) {
          pdf.setFontSize(7);
          pdf.setTextColor(180, 180, 180);
          pdf.text(window.formatDate(pin.createdAt), M + 10, y);
          y += 3;
        }

        y += 3;
      });

      y += 3;
    });
  }

  // ============ CHECKLISTE ============

  checkPage(30);
  if (y > M + 10) {
    pdf.addPage();
    y = M;
  }

  pdf.setFontSize(16);
  pdf.setFont('helvetica', 'bold');
  pdf.setTextColor(...black);
  pdf.text('Checkliste', M, y);
  y += 10;

  window.PHASE_ORDER.forEach(phase => {
    const items = window.CHECKLISTS[phase];
    const meta = window.PHASES[phase];
    const naCount = items.filter((_, i) => checklist[`${phase}-${i}-na`]).length;
    const relevant = items.length - naCount;
    const done = items.filter((_, i) => checklist[`${phase}-${i}`]).length;

    checkPage(12 + items.length * 5);

    // Phase-Header
    pdf.setFillColor(...phaseRgb[phase]);
    pdf.roundedRect(M, y - 4, 14, 6, 1.5, 1.5, 'F');
    pdf.setFontSize(8);
    pdf.setFont('helvetica', 'bold');
    pdf.setTextColor(255, 255, 255);
    pdf.text(phase, M + 7, y, { align: 'center' });

    pdf.setFontSize(11);
    pdf.setTextColor(...black);
    pdf.text(meta.name, M + 18, y);

    pdf.setFontSize(9);
    pdf.setTextColor(...gray);
    pdf.text(`${done}/${relevant}${naCount ? ` (${naCount} n/r)` : ''}`, W - M, y, { align: 'right' });
    y += 7;

    items.forEach((item, i) => {
      const key = `${phase}-${i}`;
      const checked = !!checklist[key];
      const isNa = !!checklist[key + '-na'];

      checkPage(6);

      // Checkbox
      if (isNa) {
        pdf.setFillColor(220, 220, 220);
        pdf.roundedRect(M + 2, y - 3, 3.5, 3.5, 0.5, 0.5, 'F');
        pdf.setFontSize(7);
        pdf.setTextColor(140, 140, 140);
        pdf.text('\u2013', M + 3.75, y - 0.3, { align: 'center' });
      } else if (checked) {
        pdf.setFillColor(...phaseRgb[phase]);
        pdf.roundedRect(M + 2, y - 3, 3.5, 3.5, 0.5, 0.5, 'F');
        pdf.setFontSize(6);
        pdf.setTextColor(255, 255, 255);
        pdf.text('\u2713', M + 3.75, y - 0.5, { align: 'center' });
      } else {
        pdf.setDrawColor(...lightGray);
        pdf.setLineWidth(0.3);
        pdf.roundedRect(M + 2, y - 3, 3.5, 3.5, 0.5, 0.5, 'S');
      }

      // Text
      pdf.setFontSize(9);
      pdf.setFont('helvetica', 'normal');
      const dimmed = checked || isNa;
      pdf.setTextColor(dimmed ? 160 : 28, dimmed ? 160 : 25, dimmed ? 160 : 23);
      const lines = pdf.splitTextToSize(item, CW - 12);
      pdf.text(lines, M + 9, y);
      y += lines.length * 4 + 2;
    });

    y += 5;
  });

  // ============ PROBENPLAN ============

  if (rehearsals.length > 0) {
    checkPage(30);
    if (y > H - 60) {
      pdf.addPage();
      y = M;
    }

    pdf.setFontSize(16);
    pdf.setFont('helvetica', 'bold');
    pdf.setTextColor(...black);
    pdf.text('Probenplan', M, y);
    y += 10;

    const sorted = [...rehearsals].sort((a, b) => a.date - b.date);

    sorted.forEach(r => {
      checkPage(25);

      // Datum
      pdf.setFontSize(9);
      pdf.setFont('helvetica', 'normal');
      pdf.setTextColor(...gray);
      pdf.text(window.formatDate(r.date), M, y);
      y += 5;

      // Titel
      pdf.setFontSize(11);
      pdf.setFont('helvetica', 'bold');
      pdf.setTextColor(...black);
      pdf.text(r.title || '(ohne Titel)', M, y);
      y += 5;

      // Phasen-Tags
      if (r.phases && r.phases.length > 0) {
        let tagX = M;
        r.phases.forEach(p => {
          const label = `${p} ${window.PHASES[p].name}`;
          const tw = pdf.getTextWidth(label) + 4;
          pdf.setFillColor(...phaseRgb[p]);
          pdf.roundedRect(tagX, y - 3.5, tw + 2, 5, 1.2, 1.2, 'F');
          pdf.setFontSize(7);
          pdf.setFont('helvetica', 'bold');
          pdf.setTextColor(255, 255, 255);
          pdf.text(label, tagX + (tw + 2) / 2, y, { align: 'center' });
          tagX += tw + 5;
        });
        y += 5;
      }

      // Notizen
      if (r.notes) {
        pdf.setFontSize(9);
        pdf.setFont('helvetica', 'normal');
        pdf.setTextColor(...gray);
        const lines = pdf.splitTextToSize(r.notes, CW);
        checkPage(lines.length * 4);
        pdf.text(lines, M, y);
        y += lines.length * 4 + 2;
      }

      y += 4;
      drawLine();
    });
  }

  // ============ FOOTER auf jeder Seite ============

  const totalPages = pdf.internal.getNumberOfPages();
  for (let i = 1; i <= totalPages; i++) {
    pdf.setPage(i);
    pdf.setFontSize(7);
    pdf.setFont('helvetica', 'normal');
    pdf.setTextColor(180, 180, 180);
    pdf.text(
      `${piece.title} — 4-V Analyse  |  Seite ${i} von ${totalPages}`,
      W / 2, H - 8,
      { align: 'center' }
    );
  }

  // Download
  const filename = (piece.title || 'analyse').replace(/[^a-zA-Z0-9äöüÄÖÜß\-_ ]/g, '') + '_4V-Analyse.pdf';
  pdf.save(filename);
}

window.exportAnalysisPdf = exportAnalysisPdf;
