/* ============================================================
   TotaalDakConcept demo - step 5 results + PDF
   ============================================================ */
(function () {
  "use strict";
  if (!window.TDC) return;

  var AREA = 500; // demo project roof area in m2
  var s = window.TDC.getState();

  /* ---------- helpers ---------- */
  function esc(t) {
    return String(t == null ? "" : t)
      .replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
  }
  function orDash(v) { return (v && String(v).trim()) ? v : "\u2014"; }
  function fmt(n) { return String(n).replace(/\B(?=(\d{3})+(?!\d))/g, "."); }
  function refNo() {
    var d = new Date();
    var p = function (x) { return ("0" + x).slice(-2); };
    return "TDC-" + d.getFullYear() + p(d.getMonth() + 1) + p(d.getDate()) + "-" +
           p(d.getHours()) + p(d.getMinutes());
  }
  function today() {
    return new Date().toLocaleDateString("nl-NL", { day: "numeric", month: "long", year: "numeric" });
  }
  var REF = refNo();

  /* ---------- product generator (fictional but coherent) ---------- */
  function buildProducts(s) {
    var items = [];
    var thickMap = { "4,5": 110, "6,0": 150, "8,0": 200 };
    var rc = (s.thermische || "").split(" ")[0];
    var thick = thickMap[rc] || 150;

    var vapor = {
      "Beton": "TDC VaporSeal BIT zelfklevende dampremmer",
      "Hout": "TDC VaporSeal PE dampremmende folie",
      "Staal": "TDC VaporSeal AL aluminium dampremmer"
    }[s.ondergrond] || "TDC VaporSeal dampremmende laag";
    items.push({ p: vapor, t: "Dampremmende laag", spec: s.ondergrond + " ondergrond", qty: AREA, u: "m\u00b2" });

    var isoName = {
      "PIR": "TDC ThermaPIR", "EPS": "TDC ThermaEPS",
      "Steenwol": "TDC ThermaRock", "Resol": "TDC ThermaResol"
    }[s.isolatie] || "TDC Therma";
    items.push({
      p: isoName + " " + thick + " isolatieplaat", t: "Thermische isolatie",
      spec: s.isolatie + ", " + thick + " mm (Rc " + rc + ")", qty: AREA, u: "m\u00b2"
    });

    if (s.afschot && s.afschot.indexOf("Geen") === -1) {
      items.push({
        p: "TDC SlopePIR afschotpakket", t: "Afschotisolatie",
        spec: s.afschot, qty: Math.round(AREA * 0.6), u: "m\u00b2"
      });
    }

    var layers = (s.typeToplaag || "").indexOf("2") !== -1 ? 2 : 1;
    if (s.toplaagMat === "Bitumen" && layers === 2) {
      items.push({ p: "TDC BituBASE onderlaag", t: "Toplaag (onderlaag)", spec: "2-laags systeem", qty: AREA, u: "m\u00b2" });
    }
    var memName = {
      "Bitumen": "TDC BituTOP APP toplaag", "EPDM": "TDC FlexDEK EPDM 1.5 dakbaan",
      "TPO": "TDC FlexDEK TPO 1.5 dakbaan", "PVC": "TDC FlexDEK PVC 1.5 dakbaan"
    }[s.toplaagMat] || "TDC FlexDEK dakbaan";
    items.push({
      p: memName, t: "Toplaag (afdichting)",
      spec: s.toplaagMat + ", " + s.typeToplaag,
      qty: (layers === 2 && s.toplaagMat !== "Bitumen") ? AREA * 2 : AREA, u: "m\u00b2"
    });

    if (s.bevestiging === "Mechanisch bevestigd") {
      items.push({ p: "TDC FixTec teleschroef + drukverdeelplaat", t: "Bevestiging", spec: "Mechanisch bevestigd", qty: Math.round(AREA * 6), u: "st" });
    } else if (s.bevestiging === "Volledig gekleefd") {
      items.push({ p: "TDC BondTec PU koudlijm", t: "Bevestiging", spec: "Volledig gekleefd", qty: Math.round(AREA * 0.3), u: "kg" });
    } else if (s.bevestiging === "Geballast") {
      items.push({ p: "TDC SepaFleece scheidingslaag", t: "Bevestiging", spec: "Geballast systeem", qty: AREA, u: "m\u00b2" });
    }

    if (s.ballast === "Grind") {
      items.push({ p: "TDC BallastGrind 16/32", t: "Ballastlaag", spec: "Grind", qty: AREA, u: "m\u00b2" });
    } else if (s.ballast === "Tegels") {
      items.push({ p: "TDC TerraTile betontegel 50\u00d750", t: "Ballast / verharding", spec: "Tegels op tegeldragers", qty: Math.round(AREA * 4), u: "st" });
    }

    items.push({ p: "TDC EdgeTrim aluminium daktrim", t: "Randafwerking", spec: "Dakranden, omtrek", qty: Math.round(4 * Math.sqrt(AREA)), u: "m" });

    if ((s.beloopbaarheid || "").indexOf("Goed") !== -1) {
      items.push({ p: "TDC WalkGuard looppadtegel", t: "Beloopbaarheid", spec: s.beloopbaarheid, qty: Math.round(Math.sqrt(AREA)), u: "m" });
    }
    return items;
  }

  var products = buildProducts(s);

  /* ---------- render: gegevens ---------- */
  var gegevens = [
    ["Naam", orDash(s.naam)],
    ["Organisatie", orDash(s.organisatie)],
    ["E-mailadres", orDash(s.mail)],
    ["Referentie", REF],
    ["Datum", today()]
  ];
  document.getElementById("gegevens-list").innerHTML = gegevens.map(function (r) {
    return '<div class="spec-row"><span class="k">' + esc(r[0]) + '</span><span class="v">' + esc(r[1]) + "</span></div>";
  }).join("");

  /* ---------- render: configuratie ---------- */
  var config = [
    ["Daktype", s.roof],
    ["Ondergrond", s.ondergrond],
    ["Thermische prestatie", s.thermische],
    ["Klimaatklasse", s.klimaatklasse],
    ["Beloopbaarheid", s.beloopbaarheid],
    ["Afschot", s.afschot],
    ["Isolatie materiaal", s.isolatie],
    ["Bevestiging daksysteem", s.bevestiging],
    ["Ballastlaag / dak verharding", s.ballast],
    ["Toplaag materiaal", s.toplaagMat],
    ["Type toplaag", s.typeToplaag]
  ];
  document.getElementById("config-list").innerHTML = config.map(function (r) {
    return '<div class="spec-row"><span class="k">' + esc(r[0]) + '</span><span class="v">' + esc(orDash(r[1])) + "</span></div>";
  }).join("");

  /* ---------- render: products ---------- */
  document.getElementById("products-intro").textContent =
    "Indicatieve hoeveelheden op basis van een voorbeeldoppervlak van " + AREA + " m\u00b2.";
  document.getElementById("products-body").innerHTML = products.map(function (it) {
    return "<tr>" +
      '<td><span class="prod-name">' + esc(it.p) + '</span><br><span class="prod-type">' + esc(it.t) + "</span></td>" +
      "<td>" + esc(it.spec) + "</td>" +
      '<td class="num">' + fmt(it.qty) + " " + it.u + "</td>" +
      "</tr>";
  }).join("");

  /* ---------- PDF download ---------- */
  function buildPDF() {
    var jsPDF = (window.jspdf && window.jspdf.jsPDF) ? window.jspdf.jsPDF : window.jsPDF;
    var doc = new jsPDF({ unit: "pt", format: "a4" });
    var W = doc.internal.pageSize.getWidth();
    var navy = [30, 46, 80], orange = [244, 172, 52], muted = [110, 120, 138];
    var M = 48;

    // header band
    doc.setFillColor(navy[0], navy[1], navy[2]);
    doc.rect(0, 0, W, 92, "F");
    // small puzzle mark
    doc.setFillColor(orange[0], orange[1], orange[2]); doc.roundedRect(M, 30, 13, 13, 2, 2, "F");
    doc.setFillColor(255, 255, 255); doc.roundedRect(M + 16, 30, 13, 13, 2, 2, "F");
    doc.setFillColor(155, 163, 178); doc.roundedRect(M, 46, 13, 13, 2, 2, "F");
    doc.setFillColor(255, 255, 255); doc.roundedRect(M + 16, 46, 13, 13, 2, 2, "F");
    doc.setTextColor(255, 255, 255);
    doc.setFont("helvetica", "bold"); doc.setFontSize(16);
    doc.text("TOTAALDAKCONCEPT", M + 42, 44);
    doc.setFont("helvetica", "normal"); doc.setFontSize(10.5);
    doc.setTextColor(210, 216, 226);
    doc.text("Bestekoverzicht platdakconstructie", M + 42, 62);
    doc.setTextColor(255, 255, 255); doc.setFontSize(9);
    doc.text(REF, W - M, 40, { align: "right" });
    doc.setTextColor(210, 216, 226);
    doc.text(today(), W - M, 56, { align: "right" });

    var y = 128;
    doc.setTextColor(navy[0], navy[1], navy[2]);
    doc.setFont("helvetica", "bold"); doc.setFontSize(13);
    doc.text("Projectgegevens", M, y);
    y += 6;
    doc.autoTable({
      startY: y + 6, margin: { left: M, right: M }, theme: "plain",
      styles: { fontSize: 10, cellPadding: 3, textColor: navy },
      columnStyles: { 0: { textColor: muted, cellWidth: 150 }, 1: { fontStyle: "bold" } },
      body: [
        ["Naam", String(orDash(s.naam))],
        ["Organisatie", String(orDash(s.organisatie))],
        ["E-mailadres", String(orDash(s.mail))],
        ["Voorbeeldoppervlak", AREA + " m2"]
      ]
    });

    y = doc.lastAutoTable.finalY + 24;
    doc.setFont("helvetica", "bold"); doc.setFontSize(13);
    doc.setTextColor(navy[0], navy[1], navy[2]);
    doc.text("Dakopbouw configuratie", M, y);
    doc.autoTable({
      startY: y + 12, margin: { left: M, right: M },
      headStyles: { fillColor: navy, textColor: 255, fontStyle: "bold", fontSize: 10 },
      styles: { fontSize: 9.5, cellPadding: 5, textColor: navy, lineColor: [235, 238, 242], lineWidth: 0.5 },
      alternateRowStyles: { fillColor: [247, 248, 250] },
      head: [["Onderdeel", "Keuze"]],
      columnStyles: { 0: { cellWidth: 200, textColor: muted } },
      body: config.map(function (r) { return [String(r[0]), String(orDash(r[1]))]; })
    });

    y = doc.lastAutoTable.finalY + 24;
    doc.setFont("helvetica", "bold"); doc.setFontSize(13);
    doc.setTextColor(navy[0], navy[1], navy[2]);
    doc.text("Benodigde producten", M, y);
    doc.setFont("helvetica", "normal"); doc.setFontSize(8.5);
    doc.setTextColor(muted[0], muted[1], muted[2]);
    doc.text("Indicatieve hoeveelheden o.b.v. " + AREA + " m2.", M, y + 14);
    doc.autoTable({
      startY: y + 24, margin: { left: M, right: M },
      headStyles: { fillColor: navy, textColor: 255, fontStyle: "bold", fontSize: 9.5 },
      styles: { fontSize: 9, cellPadding: 5, textColor: navy, lineColor: [235, 238, 242], lineWidth: 0.5 },
      alternateRowStyles: { fillColor: [247, 248, 250] },
      head: [["Product", "Type", "Specificatie", "Aantal"]],
      columnStyles: { 3: { halign: "right", cellWidth: 64 }, 1: { textColor: muted, cellWidth: 96 } },
      body: products.map(function (it) {
        return [String(it.p), String(it.t), String(it.spec), (fmt(it.qty) + " " + it.u).replace(/\u00b2/g, "2")];
      }),
      didDrawPage: function () {
        var ph = doc.internal.pageSize.getHeight();
        doc.setDrawColor(225, 229, 235); doc.setLineWidth(0.5);
        doc.line(M, ph - 46, W - M, ph - 46);
        doc.setFont("helvetica", "normal"); doc.setFontSize(8);
        doc.setTextColor(150, 158, 172);
        doc.text("TotaalDakConcept  |  info@totaaldakconcept.nl  |  06 - 293 286 48", M, ph - 30);
        doc.text("Demo-overzicht \u2013 getoonde producten en hoeveelheden zijn fictief.", M, ph - 18);
      }
    });

    doc.save("TotaalDakConcept-bestek-" + REF + ".pdf");
  }

  var btn = document.getElementById("download-pdf");
  if (btn) btn.addEventListener("click", function () {
    try { buildPDF(); }
    catch (e) { alert("Kon de PDF niet genereren: " + e.message); }
  });
})();
