<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Summary</title>
  <style>
    :root { color-scheme: light; }
    html, body {
      margin: 0;
      padding: 0;
      font-family: "Segoe UI", Segoe, Tahoma, Arial, sans-serif;
      font-size: 13px;
      color: #242424;
      background: #fff;
    }
    #wrap { padding: 8px 4px 0; }
    #empty {
      color: #616161;
      padding: 12px 8px;
      font-style: italic;
    }
    /* Three responsive columns, matching the standard-calculator Summary panel.
       Each column holds one or more "panels" (a subhead + label/value rows). */
    #cols {
      display: grid;
      grid-template-columns: repeat(3, minmax(0, 1fr));
      gap: 8px 24px;
      align-items: start;
    }
    @media (max-width: 760px) { #cols { grid-template-columns: 1fr; } }
    .panel { break-inside: avoid; margin-bottom: 14px; }
    .panel:last-child { margin-bottom: 0; }
    .subhead {
      color: #242424;                 /* match the form's default text colour */
      font-weight: 700;
      text-transform: uppercase;
      letter-spacing: .02em;
      font-size: 12px;
      padding: 2px 0 4px;
      border-bottom: 1px solid #e1dfdd;
      margin-bottom: 4px;
    }
    .result-row {
      display: flex;
      justify-content: space-between;
      align-items: baseline;
      gap: 12px;
      padding: 5px 2px;
      border-bottom: 1px solid #f0f0f0;
    }
    .result-label { color: #3b3a39; }
    .result-value { font-weight: 600; text-align: right; white-space: nowrap; }
    .muted .result-value { font-weight: 400; color: #797775; }
  </style>
</head>
<body>
  <div id="wrap">
    <div id="empty">Run Calculate to see the summary.</div>
    <div id="cols" style="display:none;">
      <!-- Column 1: Summary -->
      <div>
        <div class="panel">
          <div class="subhead">Summary</div>
          <div id="summary-rows"></div>
        </div>
      </div>
      <!-- Column 2: Calculated Rates -->
      <div>
        <div class="panel">
          <div class="subhead">Calculated Rates</div>
          <div id="rates-rows"></div>
        </div>
      </div>
      <!-- Column 3: CCA Indicative Settlements + CCA Rights -->
      <div>
        <div class="panel" id="cca-settlements" style="display:none;">
          <div class="subhead">CCA Indicative Settlements</div>
          <div id="cca-settlements-rows"></div>
        </div>
        <div class="panel" id="cca-rights" style="display:none;">
          <div class="subhead">CCA Rights</div>
          <div id="cca-rights-rows"></div>
        </div>
      </div>
    </div>
  </div>

  <script>
    (function () {
      var CURRENCY = { style: "currency", currency: "GBP" };
      var last = null;

      function money(n) {
        if (n == null || isNaN(n)) return "";
        try { return Number(n).toLocaleString(undefined, CURRENCY); }
        catch (e) { return Number(n).toFixed(2); }
      }
      function pct(n, dp) {
        if (n == null || isNaN(n)) return "";
        return Number(n).toFixed(dp == null ? 4 : dp) + "%";
      }
      function fmtDate(s) {
        if (!s) return "";
        var p = String(s).split("T")[0].split("-");
        if (p.length === 3) return p[2] + "/" + p[1] + "/" + p[0];
        return s;
      }
      function row(label, value, muted) {
        return '<div class="result-row' + (muted ? ' muted' : '') +
          '"><span class="result-label">' + label +
          '</span><span class="result-value">' + (value || "&mdash;") + '</span></div>';
      }
      function el(id) { return document.getElementById(id); }

      // The result object is the Calcemy /calculate response (same shape the
      // form-side write-back consumes). Product: "LO" | "HP" | "OL".
      function render() {
        var empty = el("empty");
        var cols = el("cols");
        if (!last) {
          cols.style.display = "none";
          empty.style.display = "";
          return;
        }
        var r = last;
        var ct = r.contracttype || r.product || "";
        var isLease = (ct === "OL" || ct === "FL" || ct === "OL" || ct === "CH");
        var isCca = (ct === "HP" || ct === "LO");

        // Column 1 — Summary.
        var s = "";
        s += row("Term (months)", r.term != null ? String(r.term) : "");
        s += row("Sum All Payments", money(r.sumallpayments));
        if (isLease) s += row("Sum All Payments Inc VAT", money(r.sumallpaymentsincvat));
        s += row("Payments Plus Residual", money(r.paymentsplusresidual));
        s += row("Sum All Fees", money(r.sumallfees));
        s += row("Total Interest", money(r.totalinterest));
        s += row("NPV", money(r.npv));
        el("summary-rows").innerHTML = s;

        // Column 2 — Calculated Rates.
        var rr = "";
        rr += row("Cost of Funds", pct(r.cof));
        rr += row("Margin", pct(r.margin));
        rr += row("Yield", pct(r.yield));
        rr += row("Customer Nominal Rate", pct(r.customernominalrate));
        rr += row("Nominal Rate With Fees", pct(r.customernominalratewithfees));
        rr += row("Customer Flat Rate", pct(r.customerflatrate));
        rr += row("Flat Rate Actual", pct(r.customerflatrateactual));
        rr += row("APR", pct(r.apr, 1));
        el("rates-rows").innerHTML = rr;

        // Column 3 — CCA (HP / Loan only, mirroring the web app).
        var ccaSet = el("cca-settlements");
        var ccaRights = el("cca-rights");
        if (isCca) {
          var cs = "";
          [1, 2, 3].forEach(function (i) {
            var m = r["settlement" + i + "months"];
            if (m > 0) {
              var date = r["settlement" + i + "date"];
              var label = date ? fmtDate(date) : ("At " + m + " Months");
              cs += row(label, money(r["settlement" + i + "value"]));
            }
          });
          el("cca-settlements-rows").innerHTML = cs || row("No settlements", "", true);
          ccaSet.style.display = "";

          var cr = "";
          cr += row("Third Payable", money(r.thirdpayable));
          cr += row("Half Payable", money(r.halfpayable));
          cr += row("Total Payable", money(r.totalpayable));
          el("cca-rights-rows").innerHTML = cr;
          ccaRights.style.display = "";
        } else {
          ccaSet.style.display = "none";
          ccaRights.style.display = "none";
        }

        empty.style.display = "none";
        cols.style.display = "";
      }

      // The form-side JS posts { type: "calcemy-summary", result: {...} }.
      window.addEventListener("message", function (evt) {
        var data = evt.data;
        if (data && data.type === "calcemy-summary") {
          last = data.result || null;
          render();
        }
      });

      // Signal readiness so the parent can (re)send data after this frame loads.
      try {
        if (window.parent) {
          window.parent.postMessage({ type: "calcemy-summary-ready" }, "*");
        }
      } catch (e) { /* cross-origin: parent will push on next calc anyway */ }
    })();
  </script>
</body>
</html>
