<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Variable Profile</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; }
    #msg { color: #616161; padding: 12px 8px; font-style: italic; }
    table { width: 100%; border-collapse: collapse; max-width: 640px; }
    thead th {
      text-align: left; font-weight: 600; padding: 6px 10px;
      border-bottom: 2px solid #e1dfdd; white-space: nowrap;
    }
    thead th.c { text-align: center; }
    thead th.r { text-align: right; }
    tbody td { padding: 5px 10px; border-bottom: 1px solid #f0f0f0; }
    tbody td.c { text-align: center; }
    tbody td.r { text-align: right; }
    tbody tr:hover { background: #f5f5f5; }
    input[type="text"] {
      font: inherit; width: 120px; text-align: right;
      padding: 4px 6px; border: 1px solid #c8c6c4; border-radius: 4px;
    }
    input[type="text"]:disabled { background: #f3f2f1; color: #797775; }
    input[type="checkbox"] { width: 16px; height: 16px; }
  </style>
</head>
<body>
  <div id="wrap">
    <div id="msg">Loading…</div>
    <div id="editor" style="display:none;">
      <table>
        <thead>
          <tr>
            <th class="c">Month</th>
            <th class="r">Additional</th>
            <th class="c">Fixed</th>
            <th class="r">Payment</th>
            <th class="r">Total</th>
          </tr>
        </thead>
        <tbody id="rows"></tbody>
      </table>
    </div>
  </div>

  <script>
    (function () {
      var CURRENCY = { style: "currency", currency: "GBP" };
      // rows = the schedule's Normal payment rows from the last response:
      //   [{ month, payment, additionalpayment, fixed, totalpayment }]
      var rows = [];

      function el(id) { return document.getElementById(id); }
      function fmtCash(n) {
        if (n == null || isNaN(n)) return "";
        try { return Number(n).toLocaleString(undefined, CURRENCY); }
        catch (e) { return Number(n).toFixed(2); }
      }
      function parseNum(s) {
        if (s == null) return 0;
        var v = parseFloat(String(s).replace(/[^0-9.\-]/g, ""));
        return isNaN(v) ? 0 : v;
      }

      // Collect the current edited state (what the form persists + sends).
      function collect() {
        return rows.map(function (r) {
          return {
            month: r.month,
            additionalpayment: r.additionalpayment || 0,
            fixed: !!r.fixed,
            payment: r.payment || 0,
            totalpayment: r.totalpayment
          };
        });
      }
      function postModel() {
        try {
          if (typeof window.onVariableChange === "function") {
            window.onVariableChange(collect());
          }
        } catch (e) { /* form pulls on Calculate anyway */ }
      }

      function render() {
        var msg = el("msg");
        var editor = el("editor");
        if (!rows.length) {
          editor.style.display = "none";
          msg.style.display = "";
          msg.textContent = "Calculate first — the payment schedule appears here " +
            "once it has been worked out.";
          return;
        }
        var tbody = el("rows");
        tbody.innerHTML = "";
        rows.forEach(function (r) {
          var tr = document.createElement("tr");

          var tdM = document.createElement("td"); tdM.className = "c";
          tdM.textContent = String(r.month); tr.appendChild(tdM);

          // Additional payment (always editable).
          var tdA = document.createElement("td"); tdA.className = "r";
          var addI = document.createElement("input"); addI.type = "text";
          addI.value = (r.additionalpayment && r.additionalpayment > 0) ? fmtCash(r.additionalpayment) : "";
          addI.placeholder = fmtCash(0);
          tdA.appendChild(addI); tr.appendChild(tdA);

          // Fixed.
          var tdF = document.createElement("td"); tdF.className = "c";
          var cb = document.createElement("input"); cb.type = "checkbox"; cb.checked = !!r.fixed;
          tdF.appendChild(cb); tr.appendChild(tdF);

          // Base payment (editable only when fixed).
          var tdP = document.createElement("td"); tdP.className = "r";
          var payI = document.createElement("input"); payI.type = "text";
          payI.value = fmtCash(r.payment); payI.disabled = !r.fixed;
          tdP.appendChild(payI); tr.appendChild(tdP);

          // Total (read-only).
          var tdT = document.createElement("td"); tdT.className = "r";
          tdT.textContent = fmtCash(r.totalpayment); tr.appendChild(tdT);

          addI.addEventListener("blur", function () {
            var v = parseNum(addI.value);
            addI.value = v > 0 ? fmtCash(v) : "";
            if (v === (r.additionalpayment || 0)) return;
            r.additionalpayment = v; postModel();
          });
          addI.addEventListener("keydown", function (e) { if (e.key === "Enter") addI.blur(); });

          cb.addEventListener("change", function () {
            r.fixed = cb.checked;
            payI.disabled = !cb.checked;
            if (cb.checked) { r.payment = 0; payI.value = ""; }
            postModel();
          });

          payI.addEventListener("blur", function () {
            if (!r.fixed) return;
            var v = parseNum(payI.value);
            payI.value = fmtCash(v);
            if (v === (r.payment || 0)) return;
            r.payment = v; postModel();
          });
          payI.addEventListener("keydown", function (e) { if (e.key === "Enter") payI.blur(); });

          tbody.appendChild(tr);
        });
        msg.style.display = "none";
        editor.style.display = "";
      }

      // Parent posts { type:"calcemy-variable", rows:[...] }.
      window.addEventListener("message", function (evt) {
        var d = evt.data;
        if (!d || d.type !== "calcemy-variable") return;
        rows = (d.rows || []).map(function (r) {
          return {
            month: r.month,
            payment: r.payment || 0,
            additionalpayment: r.additionalpayment || 0,
            fixed: !!r.fixed,
            totalpayment: r.totalpayment
          };
        });
        render();
      });

      try {
        if (window.parent) window.parent.postMessage({ type: "calcemy-variable-ready" }, "*");
      } catch (e) {}
    })();
  </script>
</body>
</html>
