(function () {
// window.DrillPanel — the unified, period-aware drill-through overlay.
//
// One intermediate analytics view shown whenever a user clicks a number /
// account / row anywhere on the platform. It replaces the two disjoint drill
// systems (the Account Detail panel + the direct Data Room jump) with a single
// analytics subpage that:
//   • respects the globally selected period (globalPeriod.resolved),
//   • shows a monthly breakdown + an account/memo breakdown + recent txns,
//   • offers a "View all in Data Room →" link at the bottom (raw txns).
//
// Data model note: GL txns are { id, posted_date, account_code, account_name,
// amount, memo, reference, canonical_category }. There is NO vendor/contact
// field on the GL stream, so the secondary breakdown groups by account_name
// (or memo when a single account is in scope) — never a fabricated vendor.
const h = React.createElement;

// "YYYY-MM" keys for the selected period. resolved.months elements are
// { year, month1, ... } — month1 is 1-based (NOT `month`). Falls back to the
// window mirror set by app.jsx, then to empty (⇒ no period filter).
function periodMonthKeys(globalPeriod) {
  const resolved = (globalPeriod && globalPeriod.resolved) || null;
  if (resolved && Array.isArray(resolved.months) && resolved.months.length) {
    return resolved.months.map((m) => m.year + "-" + String(m.month1).padStart(2, "0"));
  }
  return (window.__periodMonths || []).slice();
}

// txns are dated on posted_date (date is a legacy fallback). Return "YYYY-MM".
function txMonth(t) { return (t.posted_date || t.date || "").slice(0, 7); }

// Match a transaction to the clicked item. Prefer an exact account_code, then
// fuzzy account_name (same word-boundary logic as AccountDetailPanel so "Rent"
// never bleeds into "Rent Deposit"), then canonical_category.
function makeMatcher(drill) {
  const code = drill.account || drill.account_code || null;
  const name = (drill.name || "").toLowerCase().trim();
  const cat  = (drill.category || "").toLowerCase().trim();
  return function (t) {
    if (code && t.account_code) return String(t.account_code) === String(code);
    const a = (t.account_name || "").toLowerCase().trim();
    const c = (t.canonical_category || "").toLowerCase().trim();
    if (name) {
      return a === name || a.startsWith(name) || name.startsWith(a) ||
             a.includes(" " + name) || name.includes(" " + a);
    }
    if (cat) return c === cat || c.includes(cat);
    return false;
  };
}

function DrillPanel({ drill, data, globalPeriod, onClose, onViewTransactions }) {
  if (!drill) return null;

  const { account, name, category, pageType } = drill;
  const periodMonths = periodMonthKeys(globalPeriod);
  const resolved     = (globalPeriod && globalPeriod.resolved) || {};
  const periodLabel  = resolved.label || window.__globalPeriod || "LTM";
  const hasPeriod    = periodMonths.length > 0;

  const F = window.PerduraFormat;
  const fmt = (v) => F ? F.money(Math.abs(v), { compact: true })
    : (Math.abs(v) >= 1e6 ? "$" + (Math.abs(v) / 1e6).toFixed(2) + "M"
      : Math.abs(v) >= 1e3 ? "$" + Math.round(Math.abs(v) / 1e3) + "K"
      : "$" + Math.round(Math.abs(v)));
  const fmtYM = (ym) => { try { const [y, m] = ym.split("-"); return new Date(+y, +m - 1, 1).toLocaleDateString("en-US", { month: "short", year: "2-digit" }); } catch (e) { return ym; } };

  // Filter to this account/category, within the selected period.
  const matches = makeMatcher(drill);
  const txns = (data && data.txns || []).filter((t) => {
    if (!matches(t)) return false;
    if (!hasPeriod) return true;
    return periodMonths.includes(txMonth(t));
  });

  // Monthly totals — one bucket per period month (0-filled so gaps show as —).
  const byMonth = {};
  if (hasPeriod) periodMonths.forEach((ym) => { byMonth[ym] = 0; });
  txns.forEach((t) => {
    const ym = txMonth(t);
    if (!ym) return;
    if (!hasPeriod && byMonth[ym] === undefined) byMonth[ym] = 0;
    if (byMonth[ym] !== undefined) byMonth[ym] += Math.abs(parseFloat(t.amount || 0));
  });
  const monthCols = hasPeriod ? periodMonths.slice() : Object.keys(byMonth).sort().slice(-13);
  const maxMonth = Math.max.apply(null, monthCols.map((ym) => byMonth[ym] || 0).concat([1]));

  const total = txns.reduce((s, t) => s + Math.abs(parseFloat(t.amount || 0)), 0);

  // Secondary breakdown. GL txns carry no vendor/contact — so group by
  // account_name; if the drill is already a single account, group by memo.
  const distinctAccts = new Set(txns.map((t) => t.account_name || "").filter(Boolean));
  const groupByMemo = distinctAccts.size <= 1;
  const groupLabel = groupByMemo ? "Breakdown by Memo / Reference" : "Breakdown by Account";
  const groups = {};
  txns.forEach((t) => {
    const key = (groupByMemo ? (t.memo || t.reference) : t.account_name) || "Unspecified";
    groups[key] = (groups[key] || 0) + Math.abs(parseFloat(t.amount || 0));
  });
  const topGroups = Object.entries(groups).sort((a, b) => b[1] - a[1]).slice(0, 10);

  const th = { padding: "8px 12px", fontSize: "10px", fontWeight: "700", color: "#6475a0", textTransform: "uppercase", letterSpacing: "0.5px", borderBottom: "2px solid #e9ecef" };
  const sectionLabel = { fontSize: "12px", fontWeight: "700", color: "#0d2040", textTransform: "uppercase", letterSpacing: "0.5px", marginBottom: "12px" };

  return h("div", { style: { position: "fixed", inset: 0, zIndex: 1000, background: "rgba(13,32,64,0.6)", display: "flex", alignItems: "flex-start", justifyContent: "flex-end" }, onClick: onClose },
    h("div", { style: { width: "720px", maxWidth: "92vw", height: "100vh", background: "white", overflowY: "auto", boxShadow: "-8px 0 40px rgba(0,0,0,.2)", display: "flex", flexDirection: "column" }, onClick: (e) => e.stopPropagation() },

      // Header
      h("div", { style: { padding: "24px 28px", borderBottom: "1px solid #f0f0f0", background: "#0d2040", color: "white", flexShrink: 0 } },
        h("div", { style: { display: "flex", justifyContent: "space-between", alignItems: "flex-start" } },
          h("div", null,
            h("div", { style: { fontSize: "11px", color: "#00b894", fontWeight: "700", textTransform: "uppercase", letterSpacing: "1px", marginBottom: "6px" } }, category || pageType || "Account Detail"),
            h("div", { style: { fontSize: "20px", fontWeight: "800", marginBottom: "4px" } }, name || account || "Detail View"),
            h("div", { style: { fontSize: "13px", color: "rgba(255,255,255,0.6)" } }, periodLabel + " · " + txns.length + " transactions · " + fmt(total))
          ),
          h("button", { onClick: onClose, style: { background: "none", border: "none", color: "rgba(255,255,255,0.6)", fontSize: "24px", cursor: "pointer", padding: "0", lineHeight: 1 } }, "×")
        )
      ),

      // Empty state — computed rows (Gross Profit, EBITDA, ratios) have no GL posting.
      txns.length === 0
        ? h("div", { style: { padding: "48px 28px", textAlign: "center", flex: 1 } },
            h("div", { style: { fontSize: "32px", marginBottom: "16px" } }, "🔍"),
            h("div", { style: { fontSize: "14px", fontWeight: "700", color: "#0d2040", marginBottom: "8px" } }, "No transactions found"),
            h("div", { style: { fontSize: "12px", color: "#6475a0", lineHeight: "1.6", maxWidth: "420px", margin: "0 auto" } },
              "No individual transactions match \"" + (name || account || "this item") + "\" in " + periodLabel + ". This may be a computed metric (like Gross Profit or EBITDA) derived from multiple accounts rather than a direct GL posting.")
          )
        : h("div", { style: { padding: "24px 28px", flex: 1 } },

            // Monthly breakdown bars + values
            monthCols.length > 0 && h("div", { style: { marginBottom: "28px" } },
              h("div", { style: sectionLabel }, "Monthly Breakdown — " + periodLabel),
              h("div", { style: { display: "flex", gap: "4px", alignItems: "flex-end", height: "80px" } },
                monthCols.map((ym) => {
                  const v = byMonth[ym] || 0;
                  const pct = (v / maxMonth) * 100;
                  return h("div", { key: ym, style: { flex: 1, display: "flex", flexDirection: "column", alignItems: "center", gap: "4px" } },
                    h("div", { style: { width: "100%", background: pct > 0 ? "#00b894" : "#f0f4ff", height: Math.max(pct * 0.7, 2) + "px", borderRadius: "3px 3px 0 0", transition: "height 0.3s ease" } }),
                    h("div", { style: { fontSize: "9px", color: "#9aacbf", textAlign: "center", whiteSpace: "nowrap", overflow: "hidden" } }, fmtYM(ym))
                  );
                })
              ),
              h("div", { style: { overflowX: "auto", marginTop: "8px" } },
                h("table", { style: { width: "100%", fontSize: "11px", borderCollapse: "collapse" } },
                  h("tbody", null,
                    h("tr", null,
                      monthCols.map((ym) =>
                        h("td", { key: ym, style: { textAlign: "center", padding: "4px 2px", color: byMonth[ym] ? "#0d2040" : "#ccc", fontVariantNumeric: "tabular-nums" } }, byMonth[ym] ? fmt(byMonth[ym]) : "—")
                      )
                    )
                  )
                )
              )
            ),

            // Account / memo breakdown
            topGroups.length > 0 && h("div", { style: { marginBottom: "28px" } },
              h("div", { style: sectionLabel }, groupLabel),
              topGroups.map(([label, amount], i) => {
                const pct = total > 0 ? (amount / total * 100) : 0;
                return h("div", { key: i, style: { marginBottom: "8px" } },
                  h("div", { style: { display: "flex", justifyContent: "space-between", marginBottom: "3px", fontSize: "12px" } },
                    h("span", { style: { color: "#0d2040", fontWeight: "500" } }, label),
                    h("div", { style: { display: "flex", gap: "12px", alignItems: "center" } },
                      h("span", { style: { color: "#6475a0" } }, pct.toFixed(1) + "%"),
                      h("span", { style: { color: "#0d2040", fontWeight: "600", fontVariantNumeric: "tabular-nums" } }, fmt(amount))
                    )
                  ),
                  h("div", { style: { height: "4px", background: "#f0f4ff", borderRadius: "2px" } },
                    h("div", { style: { width: pct + "%", height: "100%", background: "#00b894", borderRadius: "2px", transition: "width 0.4s ease" } })
                  )
                );
              })
            ),

            // Recent transactions preview
            h("div", { style: { marginBottom: "24px" } },
              h("div", { style: sectionLabel }, "Recent Transactions"),
              h("div", { style: { overflowX: "auto" } },
                h("table", { style: { width: "100%", borderCollapse: "collapse", fontSize: "12px", minWidth: "500px" } },
                  h("thead", null,
                    h("tr", { style: { background: "#f8faff" } },
                      ["Date", "Description", "Reference", "Amount"].map((col) =>
                        h("th", { key: col, style: Object.assign({}, th, { textAlign: col === "Amount" ? "right" : "left" }) }, col)
                      )
                    )
                  ),
                  h("tbody", null,
                    txns.slice()
                      .sort((a, b) => (b.posted_date || "").localeCompare(a.posted_date || ""))
                      .slice(0, 20)
                      .map((t, i) =>
                        h("tr", { key: i, style: { borderBottom: "1px solid #f5f7fa" } },
                          h("td", { style: { padding: "8px 12px", color: "#6475a0" } }, (t.posted_date || t.date || "").slice(0, 10) || "—"),
                          h("td", { style: { padding: "8px 12px", color: "#0d2040" } }, t.memo || t.account_name || "—"),
                          h("td", { style: { padding: "8px 12px", color: "#9aacbf" } }, t.reference || "—"),
                          h("td", { style: { padding: "8px 12px", textAlign: "right", fontWeight: "600", fontVariantNumeric: "tabular-nums", color: (parseFloat(t.amount) || 0) < 0 ? "#ef4444" : "#0d2040" } }, fmt(t.amount))
                        )
                      ),
                    txns.length > 20 && h("tr", null,
                      h("td", { colSpan: 4, style: { padding: "12px", textAlign: "center", color: "#6475a0", fontSize: "12px" } }, "+ " + (txns.length - 20) + " more transactions")
                    )
                  )
                )
              )
            )
          ),

      // Footer — View in Data Room (secondary link, not the primary CTA)
      h("div", { style: { borderTop: "1px solid #f0f0f0", padding: "16px 28px", display: "flex", justifyContent: "space-between", alignItems: "center", flexShrink: 0 } },
        h("div", { style: { fontSize: "12px", color: "#9aacbf" } }, "Showing " + Math.min(txns.length, 20) + " of " + txns.length + " transactions"),
        h("button", {
          onClick: () => { if (onViewTransactions) onViewTransactions(drill); if (onClose) onClose(); },
          style: { padding: "8px 16px", background: "none", border: "1px solid #e9ecef", borderRadius: "8px", cursor: "pointer", fontSize: "12px", color: "#6475a0", display: "flex", alignItems: "center", gap: "6px" }
        }, "📊 View all in Data Room →")
      )
    )
  );
}

window.DrillPanel = DrillPanel;
})();
