<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Amortisation</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 16px; }
    #empty {
      color: #616161;
      padding: 12px 8px;
      font-style: italic;
    }
    #controls {
      display: none;
      align-items: center;
      gap: 8px;
      padding: 4px 8px 10px;
    }
    #controls label { color: #616161; }
    #mode {
      font: inherit;
      padding: 4px 8px;
      border: 1px solid #c8c6c4;
      border-radius: 4px;
      background: #fff;
      color: #242424;
      min-width: 130px;
    }
    table {
      width: 100%;
      border-collapse: collapse;
      table-layout: fixed;
    }
    /* Even column widths come from the <colgroup> generated in JS. */
    thead th, tbody td { overflow: hidden; text-overflow: ellipsis; }
    thead th {
      position: sticky;
      top: 0;
      background: #faf9f8;
      text-align: left;
      font-weight: 600;
      padding: 6px 10px;
      border-bottom: 2px solid #e1dfdd;
      white-space: nowrap;
    }
    tbody td {
      padding: 5px 10px;
      text-align: left;
      border-bottom: 1px solid #f0f0f0;
      white-space: nowrap;
    }
    tbody tr:hover { background: #f5f5f5; }
    tbody tr.special { background: #f8f8f8; }
  </style>
</head>
<body>
  <div id="wrap">
    <div id="empty">Run Calculate to see the payment schedule.</div>

    <div id="controls">
      <select id="mode">
        <option value="funder" selected>Funder Amortisation</option>
        <option value="nominal">Customer Amortisation</option>
        <option value="incfees">Customer Amortisation Including Fees</option>
      </select>
    </div>

    <table id="tbl" style="display:none; table-layout:fixed; width:100%;">
      <colgroup id="cols"></colgroup>
      <thead id="head"></thead>
      <tbody id="rows"></tbody>
    </table>
  </div>

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

      // Column layout per basis (mirrors the iOS app / standard calculator).
      // The Fee column only makes sense for the "Including Fees" basis.
      // The Drawdown column is inserted after Payment at render time, but only
      // when the profile actually contains a non-zero drawdown (see render()),
      // so the common zero-drawdown deal keeps the compact layout.
      var MODES = {
        funder: {
          columns: [
            { header: "Month",    field: "month",         type: "num",  left: true },
            { header: "Date",     field: "date",          type: "date", left: true },
            { header: "Payment",  field: "totalpayment",  type: "cash" },
            { header: "Interest", field: "interestfunder", type: "cash" },
            { header: "Balance",  field: "balancefunder",  type: "cash" }
          ]
        },
        nominal: {
          columns: [
            { header: "Month",    field: "month",          type: "num",  left: true },
            { header: "Date",     field: "date",           type: "date", left: true },
            { header: "Payment",  field: "totalpayment",   type: "cash" },
            { header: "Interest", field: "interestnominal", type: "cash" },
            { header: "Balance",  field: "balancenominal",  type: "cash" }
          ]
        },
        incfees: {
          columns: [
            { header: "Month",    field: "month",          type: "num",  left: true },
            { header: "Date",     field: "date",           type: "date", left: true },
            { header: "Payment",  field: "totalpayment",   type: "cash" },
            { header: "Fees",     field: "fee",            type: "cash" },
            { header: "Interest", field: "interestincfees", type: "cash" },
            { header: "Balance",  field: "balanceincfees",  type: "cash" }
          ]
        }
      };

      // The Drawdown column, inserted after Payment when any row draws down.
      var DRAWDOWN_COL = { header: "Drawdown", field: "drawdown", type: "cash" };

      // True when at least one profile row has a non-zero drawdown.
      function hasDrawdown(profile) {
        if (!profile) return false;
        for (var i = 0; i < profile.length; i++) {
          var d = profile[i] && profile[i].drawdown;
          if (d != null && !isNaN(d) && Number(d) !== 0) return true;
        }
        return false;
      }

      // Build the column list for a mode, inserting Drawdown right after the
      // Payment column when the profile has any drawdown.
      function columnsFor(mode, profile) {
        var base = mode.columns;
        if (!hasDrawdown(profile)) return base;
        var out = [];
        for (var i = 0; i < base.length; i++) {
          out.push(base[i]);
          if (base[i].field === "totalpayment") out.push(DRAWDOWN_COL);
        }
        return out;
      }

      var lastProfile = 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 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;
      }

      // Format a cell value based on its column type.
      function fmtCell(r, col) {
        if (col.type === "date") return fmtDate(r[col.field]);
        if (col.type === "num") {
          var m = r.month != null ? r.month : r[col.field];
          return m != null ? m : "";
        }
        // cash — Payment falls back to `payment` if `totalpayment` is absent.
        var v = r[col.field];
        if (col.field === "totalpayment" && (v == null || isNaN(v))) v = r.payment;
        return money(v);
      }

      function render() {
        var thead = document.getElementById("head");
        var tbody = document.getElementById("rows");
        var tbl = document.getElementById("tbl");
        var empty = document.getElementById("empty");
        var controls = document.getElementById("controls");
        thead.innerHTML = "";
        tbody.innerHTML = "";

        if (!lastProfile || !lastProfile.length) {
          tbl.style.display = "none";
          controls.style.display = "none";
          empty.style.display = "";
          return;
        }

        var mode = MODES[document.getElementById("mode").value] || MODES.funder;
        var cols = columnsFor(mode, lastProfile);
        // Equal share of the table width per column (varies with the basis and
        // whether the Drawdown column is shown).
        var colWidth = (100 / cols.length) + "%";

        // <colgroup> drives the widths under table-layout: fixed; these are
        // honoured even if the host form injects its own table CSS.
        var colgroup = document.getElementById("cols");
        colgroup.innerHTML = "";
        for (var g = 0; g < cols.length; g++) {
          var col = document.createElement("col");
          col.style.width = colWidth;
          colgroup.appendChild(col);
        }

        // Header row.
        var htr = document.createElement("tr");
        for (var h = 0; h < cols.length; h++) {
          var th = document.createElement("th");
          if (cols[h].left) th.className = "left";
          th.textContent = cols[h].header;
          htr.appendChild(th);
        }
        thead.appendChild(htr);

        // Body rows.
        for (var i = 0; i < lastProfile.length; i++) {
          var r = lastProfile[i];
          var tr = document.createElement("tr");
          // Subtle highlight on non-regular rows (Start / Balloon / Fees etc).
          if (r.rowtype && r.rowtype !== "Normal") tr.className = "special";

          for (var c = 0; c < cols.length; c++) {
            var td = document.createElement("td");
            if (cols[c].left) td.className = "left";
            td.textContent = fmtCell(r, cols[c]);
            tr.appendChild(td);
          }
          tbody.appendChild(tr);
        }

        empty.style.display = "none";
        controls.style.display = "flex";
        tbl.style.display = "";
      }

      // Re-render (same data) when the basis changes.
      document.getElementById("mode").addEventListener("change", render);

      // The form-side JS posts { type: "calcemy-amortisation", profile: [...] }.
      window.addEventListener("message", function (evt) {
        var data = evt.data;
        if (data && data.type === "calcemy-amortisation") {
          lastProfile = data.profile || null;
          render();
        }
      });

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