<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Seasonal 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: 520px; }
    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: 130px; 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>Month</th><th class="c">Fixed</th><th class="r">Payment</th></tr>
        </thead>
        <tbody id="rows"></tbody>
      </table>
    </div>
  </div>

  <script>
    (function () {
      var MONTHS = ["January", "February", "March", "April", "May", "June",
        "July", "August", "September", "October", "November", "December"];
      // model: 12 entries { monthofyear, payment, fixed }; applicable = whether
      // the current payment frequency allows seasonal (monthly/quarterly).
      var model = null;
      var applicable = false;

      function el(id) { return document.getElementById(id); }

      var CURRENCY = { style: "currency", currency: "GBP" };
      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;
      }

      function emptyModel() {
        var a = [];
        for (var i = 0; i < 12; i++) a.push({ monthofyear: i + 1, payment: 0, fixed: false, pays: false });
        return a;
      }

      // Normalise whatever we receive into exactly 12 ordered entries.
      function normalise(arr) {
        var base = emptyModel();
        if (arr && arr.length) {
          arr.forEach(function (e) {
            var idx = (e.monthofyear || 0) - 1;
            if (idx >= 0 && idx < 12) {
              // Preserve null (a no-payment month, e.g. off-quarter) distinct
              // from 0 (a fixed month set to zero by the user).
              base[idx].payment = (e.payment === undefined ? 0 : e.payment);
              base[idx].fixed = !!e.fixed;
              base[idx].pays = !!e.pays;   // month has a payment (from the engine)
            }
          });
        }
        return base;
      }

      // Expose the current model to the parent form. In the Unified Interface
      // the form JS runs in an inner app frame, not window.top, so a
      // postMessage to window.parent/top does NOT reach it. Instead the form JS
      // reads the model straight off this frame's contentWindow (it already
      // gets the frame via getContentWindow()), and persists it. So the source
      // of truth lives here and is pulled on demand.
      // On each edit, call the callback the form JS injected on this frame's
      // window (direct same-origin call — reliable across the inner-frame
      // nesting where postMessage-to-parent fails). The form persists the model.
      function postModel() {
        try {
          if (typeof window.onSeasonalChange === "function") {
            window.onSeasonalChange(model);
          }
        } catch (e) { /* form will still pull via getSeasonalModel at Calculate */ }
      }

      function render() {
        var msg = el("msg");
        var editor = el("editor");
        if (!applicable) {
          editor.style.display = "none";
          msg.style.display = "";
          msg.textContent =
            "Seasonal payments apply only to monthly or quarterly payment " +
            "frequencies. Change the frequency on the General tab to use them.";
          return;
        }
        if (!model) model = emptyModel();

        // Only show PAYMENT months — the ones the engine returned a payment for
        // (pays), plus any the user has already fixed. For quarterly this is the
        // 4 quarters; for monthly all 12. Before the first Calculate none pay,
        // so prompt the user to calculate.
        var payMonths = [];
        for (var k = 0; k < 12; k++) {
          if (model[k].pays || model[k].fixed) payMonths.push(k);
        }
        if (!payMonths.length) {
          editor.style.display = "none";
          msg.style.display = "";
          msg.textContent =
            "Calculate first — the payment months appear here once the schedule " +
            "has been worked out.";
          return;
        }

        var tbody = el("rows");
        tbody.innerHTML = "";
        payMonths.forEach(function (idx) {
          var entry = model[idx];
          var tr = document.createElement("tr");

          var tdM = document.createElement("td");
          tdM.textContent = MONTHS[idx];
          tr.appendChild(tdM);

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

          var tdP = document.createElement("td"); tdP.className = "r";
          var inp = document.createElement("input"); inp.type = "text";
          inp.value = (entry.payment == null) ? "" : fmtCash(entry.payment);
          inp.disabled = !entry.fixed;
          tdP.appendChild(inp); tr.appendChild(tdP);

          cb.addEventListener("change", function () {
            entry.fixed = cb.checked;
            if (cb.checked) { entry.payment = 0; inp.value = fmtCash(0); }
            inp.disabled = !cb.checked;
            postModel();
          });
          inp.addEventListener("blur", function () {
            if (!entry.fixed) return;
            var v = parseNum(inp.value);
            inp.value = fmtCash(v);
            if (v === entry.payment) return;
            entry.payment = v; postModel();
          });
          inp.addEventListener("keydown", function (e) {
            if (e.key === "Enter") inp.blur();
          });

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

      // Parent posts { type:"calcemy-seasonal", model:[...], applicable:bool }.
      window.addEventListener("message", function (evt) {
        var d = evt.data;
        if (!d || d.type !== "calcemy-seasonal") return;
        applicable = !!d.applicable;
        model = normalise(d.model);
        render();
      });

      // Signal readiness so the parent (re)sends state after the frame loads.
      try {
        if (window.parent) {
          window.parent.postMessage({ type: "calcemy-seasonal-ready" }, "*");
        }
      } catch (e) { /* parent will push on next calc/onload */ }
    })();
  </script>
</body>
</html>
