// Liability detail — full-screen view of a single mortgage / loan / credit card.
// Shows paydown progress, debt metrics, and a debt-optimization CTA that hands
// the user to Himma.

const LIABILITY_KIND_LABELS = {
  mortgage: "Mortgage",
  loan: "Loan",
  card: "Credit card",
};

function findLiability(kind, id) {
  if (kind === "mortgage")
    return LIABILITIES.mortgages.find((m) => m.id === id);
  if (kind === "loan") return LIABILITIES.loans.find((l) => l.id === id);
  if (kind === "card") return LIABILITIES.credit_cards.find((c) => c.id === id);
  return null;
}

// Build a paydown trajectory from the beginning of the debt, through today,
// and out to zero so the midpoint of the chart is the current balance.
function buildPaydown(item, kind) {
  const balance = Number(item.currentBalance ?? item.balance ?? 0);
  const original = Number(item.originalAmount ?? balance);
  if (kind === "card") return [balance];

  const steps = 12;
  const alreadyPaid = Math.max(0, original - balance);
  const history = Array.from(
    { length: steps + 1 },
    (_, i) => original - alreadyPaid * (i / steps),
  );
  const future = Array.from(
    { length: steps + 1 },
    (_, i) => balance * (1 - i / steps),
  );
  return [...history, ...future.slice(1)];
}

function termMonths(term) {
  if (!term) return null;
  const years = /(\d+(?:\.\d+)?)\s*year/i.exec(term);
  const months = /(\d+(?:\.\d+)?)\s*month/i.exec(term);
  const y = years ? Number(years[1]) * 12 : 0;
  const m = months ? Number(months[1]) : 0;
  return y + m || null;
}

function monthDiff(start, end) {
  return (
    (end.getFullYear() - start.getFullYear()) * 12 +
    (end.getMonth() - start.getMonth())
  );
}

function formatDurationMonths(totalMonths) {
  if (totalMonths == null) return "—";
  const months = Math.max(0, Math.round(totalMonths));
  const y = Math.floor(months / 12);
  const m = months % 12;
  if (y && m) return `${y}y ${m}m`;
  if (y) return `${y}y`;
  return `${m}m`;
}

function parseLiabilityDate(value) {
  if (!value) return null;
  if (value instanceof Date && !isNaN(value)) return value;

  const str = String(value).trim();
  const iso = /^(\d{4})-(\d{1,2})(?:-(\d{1,2}))?/.exec(str);
  if (iso) {
    return new Date(Number(iso[1]), Number(iso[2]) - 1, Number(iso[3] || 1));
  }
  return parseMonthYear(str);
}

function getDemoToday() {
  return new Date(TODAY.year, TODAY.month - 1, TODAY.day);
}

function getTermStartDate(item) {
  return parseLiabilityDate(item.startDate || item.originationDate);
}

function getElapsedInstallments(item) {
  const start = getTermStartDate(item);
  if (!start) return null;
  const total = termMonths(item.term);
  const elapsed = Math.max(0, monthDiff(start, getDemoToday()));
  return total ? Math.min(total, elapsed) : elapsed;
}

function getPaymentDay(item) {
  const raw = item.paymentDay || item.nextPaymentDay || item.statementDate;
  const match = raw != null ? String(raw).match(/\d{1,2}/) : null;
  if (match) return Math.max(1, Math.min(31, Number(match[0])));

  const start = getTermStartDate(item);
  return start ? start.getDate() : 1;
}

function formatDetailDate(date) {
  if (!date) return "—";
  return `${date.getDate()} ${MONTH_NAMES_SHORT[date.getMonth()]} ${date.getFullYear()}`;
}

function getNextPaymentDate(item) {
  if (item.nextPaymentDate) return item.nextPaymentDate;

  const today = getDemoToday();
  const day = getPaymentDay(item);
  let year = today.getFullYear();
  let month = today.getMonth();
  let next = new Date(
    year,
    month,
    Math.min(day, new Date(year, month + 1, 0).getDate()),
  );

  if (next < today) {
    month += 1;
    if (month > 11) {
      month = 0;
      year += 1;
    }
    next = new Date(
      year,
      month,
      Math.min(day, new Date(year, month + 1, 0).getDate()),
    );
  }

  return formatDetailDate(next);
}

function calculateScheduledMonthlyPayment(originalAmount, apr, totalMonths) {
  const principal = Number(originalAmount) || 0;
  const annualApr = Number(apr) || 0;
  const months = Number(totalMonths) || 0;
  if (!principal || !months) return 0;

  const monthlyRate = annualApr / 100 / 12;
  if (!monthlyRate) return principal / months;

  const factor = Math.pow(1 + monthlyRate, months);
  return principal * ((monthlyRate * factor) / (factor - 1));
}

function getEstimatedTotalInterest(item) {
  if (item.estimatedTotalInterest != null)
    return Number(item.estimatedTotalInterest) || 0;

  const original = Number(item.originalAmount || item.balance) || 0;
  const total = termMonths(item.term);
  if (!original || !total) return 0;

  const scheduledPayment = calculateScheduledMonthlyPayment(
    original,
    item.apr,
    total,
  );
  return Math.max(0, scheduledPayment * total - original);
}

function getMortgageProgress(item) {
  const total = termMonths(item.term);
  const elapsed = getElapsedInstallments(item);
  if (!total || elapsed == null) {
    return {
      total,
      elapsed,
      installmentLabel: item.term || "—",
      remainingLabel: getTermOutstanding(item),
      pct: 0,
    };
  }

  const currentInstallment = Math.min(total, Math.max(1, elapsed + 1));
  const remaining = Math.max(0, total - elapsed);
  return {
    total,
    elapsed,
    installmentLabel: `Installment ${currentInstallment} of ${total}`,
    remainingLabel: `${formatDurationMonths(remaining)} remaining`,
    pct: Math.max(0, Math.min(100, (elapsed / total) * 100)),
  };
}

function getTermOutstanding(item) {
  const total = termMonths(item.term);
  const start = getTermStartDate(item);
  if (!total || !start) return item.term || "—";
  const now = getDemoToday();
  return formatDurationMonths(total - monthDiff(start, now));
}

function getPayoffLabel(item) {
  if (item.payoffDate) return item.payoffDate;
  const total = termMonths(item.term);
  const start = getTermStartDate(item);
  if (!total || !start) return "Payoff";
  return fmtMonthYear(addMonths(start, total));
}

function LiabilityDetailScreen({
  theme,
  accent,
  liabilityKind,
  liabilityId,
  liabilityItem,
  onBack,
  onAskHimma,
}) {
  const kind =
    liabilityKind && LIABILITY_KIND_LABELS[liabilityKind]
      ? liabilityKind
      : "mortgage";
  const sourceItem =
    liabilityItem ||
    findLiability(kind, liabilityId) ||
    LIABILITIES.mortgages[0]; // sensible fallback for the prototype
  const [item, setItem] = React.useState(() => ({ ...sourceItem }));
  const [editingMortgage, setEditingMortgage] = React.useState(false);
  const [confirmMortgageDelete, setConfirmMortgageDelete] =
    React.useState(false);

  React.useEffect(() => {
    setItem({ ...sourceItem });
    setEditingMortgage(false);
    setConfirmMortgageDelete(false);
  }, [liabilityKind, liabilityId]);

  const isCard = kind === "card";
  const usesPaydownDetail = kind === "mortgage" || kind === "loan";
  const title = item.lender || item.issuer || item.name;

  const currentBalance = Number(item.currentBalance ?? item.balance ?? 0);
  const balance = currentBalance;
  const original = Number(
    item.originalAmount ?? (isCard ? item.limit : item.balance) ?? 0,
  );
  const paid = isCard ? 0 : Math.max(0, original - balance);
  const paidPct = original ? (paid / original) * 100 : 0;
  const monthly = Number(item.monthlyPayment ?? item.minPayment ?? 0);
  const apr = Number(item.apr || 0);
  const payoff = getPayoffLabel(item);
  const termStartDate = getTermStartDate(item);
  const startLabel = termStartDate
    ? fmtMonthYear(termStartDate)
    : item.originationDate || "Start";
  const trajectory = buildPaydown(item, kind);
  const recentCardTxs = isCard ? getCardRecentTransactions(item) : [];
  const elapsedInstallments = usesPaydownDetail
    ? getElapsedInstallments(item)
    : null;
  const totalPrincipalPaid = usesPaydownDetail ? paid : 0;
  const totalInterestPaid = usesPaydownDetail
    ? Math.max(0, monthly * (elapsedInstallments || 0) - totalPrincipalPaid)
    : 0;
  const estimatedTotalInterest = usesPaydownDetail
    ? getEstimatedTotalInterest(item)
    : 0;
  const estimatedTotalCost = usesPaydownDetail
    ? original + estimatedTotalInterest
    : 0;
  const debtProgress = usesPaydownDetail ? getMortgageProgress(item) : null;
  const persistMortgageEdit = (updated) => {
    const idx = LIABILITIES.mortgages.findIndex((m) => m.id === updated.id);
    if (idx >= 0)
      LIABILITIES.mortgages[idx] = {
        ...LIABILITIES.mortgages[idx],
        ...updated,
      };
    setItem(updated);
  };
  const deleteMortgageAndReturn = () => {
    const idx = LIABILITIES.mortgages.findIndex((m) => m.id === item.id);
    if (idx >= 0) LIABILITIES.mortgages.splice(idx, 1);
    onBack();
  };

  return (
    <Screen theme={theme} padBottom={40}>
      {/* Header */}
      <div
        style={{
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          padding: "18px 20px 12px",
        }}
      >
        <button
          onClick={onBack}
          style={{
            width: 36,
            height: 36,
            borderRadius: 18,
            background: "transparent",
            border: `0.5px solid ${theme.line2}`,
            color: theme.text,
            cursor: "pointer",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
          }}
        >
          <Ico.chevL size={14} />
        </button>
        <div
          style={{
            fontFamily: FONTS.mono,
            fontSize: 10,
            letterSpacing: 1.5,
            textTransform: "uppercase",
            color: theme.textMute,
          }}
        >
          {LIABILITY_KIND_LABELS[kind]}
        </div>
        <div style={{ width: 36 }} />
      </div>

      {/* Title */}
      <div style={{ padding: "0 22px 16px" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div
              style={{
                fontFamily: FONTS.display,
                fontSize: 24,
                color: theme.text,
                letterSpacing: -0.5,
                lineHeight: 1.1,
              }}
            >
              {title}
            </div>
          </div>
          {kind === "mortgage" && (
            <MortgageDetailActions
              theme={theme}
              onEdit={() => setEditingMortgage(true)}
              onDelete={() => setConfirmMortgageDelete(true)}
            />
          )}
        </div>
      </div>

      {usesPaydownDetail ? (
        <>
          {/* Section 1: The Hero */}
          <div style={{ padding: "0 16px 14px" }}>
            <Card
              theme={theme}
              style={{
                padding: "0 6px 2px",
                background: "transparent",
                border: "none",
                borderRadius: 0,
              }}
            >
              <div
                style={{
                  display: "flex",
                  alignItems: "flex-start",
                  justifyContent: "space-between",
                  gap: 12,
                }}
              >
                <div style={{ flex: 1, minWidth: 0 }}>
                  <SectionLabel theme={theme}>Current balance</SectionLabel>
                  <BigNumber
                    value={currentBalance}
                    theme={theme}
                    accent={theme.text}
                    size={32}
                  />
                  <div
                    style={{
                      marginTop: 6,
                      fontFamily: FONTS.mono,
                      fontSize: 11,
                      color: theme.textDim,
                    }}
                  >
                    of <Dh />{" "}
                    {fmtAED(original, { compact: original >= 100_000 })}{" "}
                    original amount
                  </div>
                </div>
                <div
                  style={{
                    flexShrink: 0,
                    fontFamily: FONTS.mono,
                    fontSize: 10,
                    color: theme.positive,
                    padding: "6px 8px",
                    borderRadius: 999,
                    background: `${theme.positive}10`,
                    border: `0.5px solid ${theme.positive}30`,
                    marginTop: 2,
                  }}
                >
                  {paidPct.toFixed(0)}% paid
                </div>
              </div>

              <div
                style={{
                  marginTop: 16,
                  display: "grid",
                  gridTemplateColumns: "1fr 1fr",
                  border: `0.5px solid ${theme.line}`,
                  borderRadius: 14,
                  overflow: "hidden",
                  background: theme.surface,
                }}
              >
                <MortgageInsightCell
                  theme={theme}
                  icon={<Ico.clock size={14} />}
                  label="Next Payment Date"
                  value={getNextPaymentDate(item)}
                  borderRight
                />
                <MortgageInsightCell
                  theme={theme}
                  icon={<Ico.wallet size={14} />}
                  label="Monthly Payment"
                  value={
                    <>
                      <Dh /> {fmtAED(monthly)}
                    </>
                  }
                />
              </div>

              <div style={{ marginTop: 18 }}>
                <div style={{ marginBottom: 8 }}>
                  <SectionLabel theme={theme}>Paydown trajectory</SectionLabel>
                </div>
                <PaydownChart
                  data={trajectory}
                  theme={theme}
                  accent={accent}
                  startLabel={startLabel}
                  payoffLabel={payoff}
                  height={86}
                />
              </div>
            </Card>
          </div>

          {/* Section 2: The Core Metrics */}
          <div style={{ padding: "0 16px 14px" }}>
            <div style={{ padding: "0 6px 10px" }}>
              <SectionLabel theme={theme}>Core metrics</SectionLabel>
            </div>
            <div
              style={{
                display: "grid",
                gridTemplateColumns: "1fr 1fr",
                gap: 10,
              }}
            >
              <MortgageMetricTile
                theme={theme}
                label="Original Amount"
                value={
                  <>
                    <Dh /> {fmtAED(original, { compact: true })}
                  </>
                }
              />
              <MortgageMetricTile
                theme={theme}
                label="APR"
                value={`${apr.toFixed(2)}%`}
              />
              <MortgageMetricTile
                theme={theme}
                label="Total Principal Paid"
                value={
                  <>
                    <Dh /> {fmtAED(totalPrincipalPaid, { compact: true })}
                  </>
                }
              />
              <MortgageMetricTile
                theme={theme}
                label="Total Interest Paid"
                value={
                  <>
                    <Dh /> {fmtAED(totalInterestPaid, { compact: true })}
                  </>
                }
              />
            </div>
          </div>

          {/* Section 3: Lifetime Projections & Insights */}
          <div style={{ padding: "0 16px 18px" }}>
            <Card theme={theme} style={{ padding: 18 }}>
              <SectionLabel theme={theme}>
                Lifetime projections & insights
              </SectionLabel>
              <MortgageProjectionRow
                theme={theme}
                label="Total cost of loan"
                value={
                  <>
                    <Dh />{" "}
                    {fmtAED(estimatedTotalCost, {
                      compact: estimatedTotalCost >= 100_000,
                    })}
                  </>
                }
                sub={
                  <>
                    Estimated interest <Dh />{" "}
                    {fmtAED(estimatedTotalInterest, {
                      compact: estimatedTotalInterest >= 100_000,
                    })}
                  </>
                }
              />
              <div
                style={{
                  marginTop: 16,
                  paddingTop: 16,
                  borderTop: `0.5px solid ${theme.line}`,
                }}
              >
                <div
                  style={{
                    display: "flex",
                    justifyContent: "space-between",
                    alignItems: "baseline",
                    gap: 12,
                  }}
                >
                  <div>
                    <div
                      style={{
                        fontSize: 13,
                        fontWeight: 600,
                        color: theme.text,
                      }}
                    >
                      Progress
                    </div>
                    <div
                      style={{
                        marginTop: 3,
                        fontFamily: FONTS.mono,
                        fontSize: 10.5,
                        color: theme.textDim,
                      }}
                    >
                      {debtProgress.remainingLabel}
                    </div>
                  </div>
                  <div
                    style={{
                      fontFamily: FONTS.mono,
                      fontSize: 10.5,
                      color: theme.text,
                      textAlign: "right",
                      fontVariantNumeric: "tabular-nums",
                    }}
                  >
                    {debtProgress.installmentLabel}
                  </div>
                </div>
                <div
                  style={{
                    marginTop: 12,
                    height: 5,
                    borderRadius: 3,
                    background: theme.surface3,
                    overflow: "hidden",
                  }}
                >
                  <div
                    style={{
                      height: "100%",
                      width: `${debtProgress.pct}%`,
                      background: accent,
                    }}
                  />
                </div>
              </div>
            </Card>
          </div>
        </>
      ) : (
        <>
          {/* Balance + paydown chart */}
          <div style={{ padding: "0 16px 14px" }}>
            <Card
              theme={theme}
              style={{
                padding: 22,
                background: `linear-gradient(155deg, ${theme.surface2} 0%, ${theme.surface} 90%)`,
              }}
            >
              <SectionLabel theme={theme}>Outstanding balance</SectionLabel>
              <BigNumber
                value={balance}
                theme={theme}
                accent={theme.text}
                size={32}
              />

              {!isCard && (
                <div
                  style={{
                    marginTop: 6,
                    fontFamily: FONTS.mono,
                    fontSize: 11,
                    color: theme.textDim,
                  }}
                >
                  of <Dh /> {fmtAED(original, { compact: original >= 100_000 })}{" "}
                  starting balance
                </div>
              )}

              {!isCard && (
                <div style={{ marginTop: 18 }}>
                  <div style={{ marginBottom: 8 }}>
                    <SectionLabel theme={theme}>
                      Paydown trajectory
                    </SectionLabel>
                  </div>
                  <PaydownChart
                    data={trajectory}
                    theme={theme}
                    accent={accent}
                    startLabel={startLabel}
                    payoffLabel={payoff}
                  />
                </div>
              )}

              {!isCard && (
                <div style={{ marginTop: 16 }}>
                  <div
                    style={{
                      height: 4,
                      borderRadius: 2,
                      background: theme.surface3,
                      overflow: "hidden",
                    }}
                  >
                    <div
                      style={{
                        height: "100%",
                        width: `${paidPct}%`,
                        background: theme.positive,
                      }}
                    />
                  </div>
                  <div
                    style={{
                      marginTop: 6,
                      fontFamily: FONTS.mono,
                      fontSize: 10.5,
                      color: theme.textDim,
                    }}
                  >
                    {paidPct.toFixed(0)}% paid down
                  </div>
                </div>
              )}
            </Card>
          </div>

          {/* Stat grid */}
          <div style={{ padding: "0 16px 14px" }}>
            <Card theme={theme} style={{ padding: 18 }}>
              <div
                style={{
                  display: "grid",
                  gridTemplateColumns: "1fr 1fr",
                  rowGap: 18,
                  columnGap: 12,
                }}
              >
                {isCard ? (
                  <>
                    <DetailStat
                      label="Credit limit"
                      value={
                        <>
                          <Dh /> {fmtAED(item.limit, { compact: true })}
                        </>
                      }
                      theme={theme}
                    />
                    <DetailStat
                      label="Outstanding balance"
                      value={
                        <>
                          <Dh /> {fmtAED(balance)}
                        </>
                      }
                      theme={theme}
                    />
                    <DetailStat
                      label="APR"
                      value={`${apr.toFixed(2)}%`}
                      theme={theme}
                    />
                    <DetailStat
                      label="Min payment"
                      value={
                        <>
                          <Dh /> {fmtAED(monthly)}
                        </>
                      }
                      theme={theme}
                    />
                    <DetailStat
                      label="Payment due date"
                      value={item.statementDate || "—"}
                      theme={theme}
                    />
                  </>
                ) : (
                  <>
                    <DetailStat
                      label="Original amount"
                      value={
                        <>
                          <Dh /> {fmtAED(original, { compact: true })}
                        </>
                      }
                      theme={theme}
                    />
                    <DetailStat
                      label="Already paid"
                      value={
                        <>
                          <Dh /> {fmtAED(paid, { compact: true })}
                        </>
                      }
                      theme={theme}
                    />
                    <DetailStat
                      label="APR"
                      value={`${apr.toFixed(2)}%`}
                      theme={theme}
                    />
                    <DetailStat
                      label="Monthly payment"
                      value={
                        <>
                          <Dh /> {fmtAED(monthly)}
                        </>
                      }
                      theme={theme}
                    />
                    <DetailStat
                      label="Payoff date"
                      value={payoff}
                      theme={theme}
                    />
                    <DetailStat
                      label="Term outstanding"
                      value={getTermOutstanding(item)}
                      theme={theme}
                    />
                  </>
                )}
              </div>
            </Card>
          </div>

          {isCard && (
            <div style={{ padding: "0 16px 18px" }}>
              <div style={{ padding: "0 6px 10px" }}>
                <SectionLabel theme={theme}>Latest transactions</SectionLabel>
              </div>
              <Card theme={theme} padded={false} style={{ overflow: "hidden" }}>
                {recentCardTxs.map((tx, i) => (
                  <CardTransactionRow
                    key={tx.id}
                    tx={tx}
                    theme={theme}
                    accent={accent}
                    last={i === recentCardTxs.length - 1}
                  />
                ))}
              </Card>
            </div>
          )}
        </>
      )}

      {/* Debt-optimization CTA */}
      <div style={{ padding: "0 16px 18px" }}>
        <button
          onClick={onAskHimma}
          style={{
            width: "100%",
            textAlign: "left",
            background: `linear-gradient(155deg, ${accent}18, ${accent}08)`,
            border: `0.5px solid ${accent}55`,
            borderRadius: 18,
            padding: "16px 18px",
            color: theme.text,
            cursor: "pointer",
            display: "flex",
            gap: 12,
            alignItems: "flex-start",
          }}
        >
          <div
            style={{
              width: 32,
              height: 32,
              borderRadius: 16,
              background: `${accent}25`,
              color: accent,
              flexShrink: 0,
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
            }}
          >
            <Ico.sparkles size={15} />
          </div>
          <div style={{ flex: 1 }}>
            <div
              style={{
                fontFamily: FONTS.mono,
                fontSize: 9.5,
                letterSpacing: 1.4,
                textTransform: "uppercase",
                color: accent,
                marginBottom: 4,
              }}
            >
              Optimize this debt
            </div>
            <div
              style={{ fontSize: 13.5, lineHeight: 1.45, color: theme.text }}
            >
              {isCard ? (
                <>
                  Ask Himma whether refinancing onto a 0% balance-transfer card
                  or paying above the minimum is the smarter move.
                </>
              ) : (
                <>
                  Ask Himma whether overpaying, refinancing, or routing extra
                  cash here beats your other priorities.
                </>
              )}
            </div>
          </div>
          <Ico.chevR
            size={15}
            style={{ color: theme.textMute, marginTop: 6 }}
          />
        </button>
      </div>

      {editingMortgage && (
        <MortgageDetailEditSheet
          item={item}
          theme={theme}
          accent={accent}
          onClose={() => setEditingMortgage(false)}
          onDelete={() => {
            setEditingMortgage(false);
            setConfirmMortgageDelete(true);
          }}
          onSave={(updated) => {
            persistMortgageEdit(updated);
            setEditingMortgage(false);
          }}
        />
      )}

      {confirmMortgageDelete && (
        <MortgageDeleteConfirmSheet
          item={item}
          theme={theme}
          onCancel={() => setConfirmMortgageDelete(false)}
          onConfirm={deleteMortgageAndReturn}
        />
      )}
    </Screen>
  );
}

function MortgageDetailActions({ theme, onEdit, onDelete }) {
  return (
    <div
      style={{
        display: "inline-flex",
        alignItems: "center",
        gap: 6,
        flexShrink: 0,
      }}
    >
      <MortgageDetailActionIcon
        theme={theme}
        icon="compose"
        label="Edit"
        onClick={onEdit}
      />
      <MortgageDetailActionIcon
        theme={theme}
        icon="trash"
        label="Delete"
        tone={theme.negative}
        onClick={onDelete}
      />
    </div>
  );
}

function MortgageDetailEditSheet({
  item,
  theme,
  accent,
  onClose,
  onSave,
  onDelete,
}) {
  const [form, setForm] = React.useState(() => ({ ...item }));

  React.useEffect(() => {
    setForm({ ...item });
  }, [item]);

  const set = (k, v) => setForm((f) => ({ ...f, [k]: v }));
  const cleanMoney = (v) => String(v).replace(/[^0-9]/g, "");
  const cleanRate = (v) => String(v).replace(/[^0-9.]/g, "");
  const canSave = form.lender && Number(form.balance) > 0;
  const save = () =>
    onSave({
      ...item,
      ...form,
      balance: Number(form.balance) || 0,
      currentBalance: Number(form.balance) || 0,
      originalAmount: Number(form.originalAmount) || 0,
      apr: Number(form.apr) || 0,
      monthlyPayment: Number(form.monthlyPayment) || 0,
    });

  return (
    <div
      onClick={onClose}
      style={{
        position: "absolute",
        inset: 0,
        zIndex: 120,
        display: "flex",
        alignItems: "flex-end",
        background: "rgba(0,0,0,0.45)",
      }}
    >
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          width: "100%",
          maxHeight: "82%",
          overflowY: "auto",
          background: theme.surface,
          borderRadius: "24px 24px 0 0",
          borderTop: `0.5px solid ${theme.line2}`,
          padding: "10px 20px 34px",
        }}
      >
        <div
          style={{
            display: "flex",
            justifyContent: "center",
            paddingBottom: 14,
          }}
        >
          <div
            style={{
              width: 40,
              height: 4,
              borderRadius: 2,
              background: theme.line2,
            }}
          />
        </div>
        <div
          style={{
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
            gap: 12,
          }}
        >
          <div
            style={{
              fontFamily: FONTS.display,
              fontSize: 22,
              color: theme.text,
              letterSpacing: -0.4,
            }}
          >
            Edit mortgage
          </div>
          <MortgageDetailActionIcon
            theme={theme}
            icon="trash"
            label="Delete"
            tone={theme.negative}
            onClick={onDelete}
          />
        </div>

        <div style={{ marginTop: 16 }}>
          <MortgageDetailEditField theme={theme} label="Lender">
            <input
              value={form.lender || ""}
              onChange={(e) => set("lender", e.target.value)}
              placeholder="Mashreq"
              style={mortgageDetailInputStyle(theme)}
            />
          </MortgageDetailEditField>
          <div
            style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}
          >
            <MortgageDetailEditField theme={theme} label="Outstanding (AED)">
              <input
                value={form.balance || ""}
                onChange={(e) => set("balance", cleanMoney(e.target.value))}
                inputMode="numeric"
                placeholder="460000"
                style={mortgageDetailInputStyle(theme)}
              />
            </MortgageDetailEditField>
            <MortgageDetailEditField theme={theme} label="Original (AED)">
              <input
                value={form.originalAmount || ""}
                onChange={(e) =>
                  set("originalAmount", cleanMoney(e.target.value))
                }
                inputMode="numeric"
                placeholder="480000"
                style={mortgageDetailInputStyle(theme)}
              />
            </MortgageDetailEditField>
          </div>
          <div
            style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}
          >
            <MortgageDetailEditField theme={theme} label="APR %">
              <input
                value={form.apr || ""}
                onChange={(e) => set("apr", cleanRate(e.target.value))}
                inputMode="decimal"
                placeholder="4.50"
                style={mortgageDetailInputStyle(theme)}
              />
            </MortgageDetailEditField>
            <MortgageDetailEditField theme={theme} label="Monthly (AED)">
              <input
                value={form.monthlyPayment || ""}
                onChange={(e) =>
                  set("monthlyPayment", cleanMoney(e.target.value))
                }
                inputMode="numeric"
                placeholder="2840"
                style={mortgageDetailInputStyle(theme)}
              />
            </MortgageDetailEditField>
          </div>
          <div
            style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}
          >
            <MortgageDetailEditField theme={theme} label="Term">
              <input
                value={form.term || ""}
                onChange={(e) => set("term", e.target.value)}
                placeholder="25 years"
                style={mortgageDetailInputStyle(theme)}
              />
            </MortgageDetailEditField>
            <MortgageDetailEditField theme={theme} label="Started">
              <input
                value={form.originationDate || form.startDate || ""}
                onChange={(e) => set("originationDate", e.target.value)}
                placeholder="May 2024"
                style={mortgageDetailInputStyle(theme)}
              />
            </MortgageDetailEditField>
          </div>
        </div>

        <button
          type="button"
          onClick={save}
          disabled={!canSave}
          style={{
            marginTop: 22,
            width: "100%",
            background: canSave ? accent : theme.surface3,
            color: canSave ? theme.bg : theme.textMute,
            border: "none",
            borderRadius: 14,
            padding: "14px",
            fontFamily: FONTS.ui,
            fontSize: 14,
            fontWeight: 600,
            cursor: canSave ? "pointer" : "not-allowed",
          }}
        >
          Save changes
        </button>
      </div>
    </div>
  );
}

function MortgageDetailActionIcon({ theme, icon, label, tone, onClick }) {
  const Icon = Ico[icon];
  return (
    <button
      type="button"
      aria-label={label}
      title={label}
      onClick={onClick}
      style={{
        width: 28,
        height: 28,
        borderRadius: 14,
        background: theme.surface2,
        border: `0.5px solid ${theme.line2}`,
        color: tone || theme.textDim,
        display: "inline-flex",
        alignItems: "center",
        justifyContent: "center",
        cursor: "pointer",
        padding: 0,
      }}
    >
      <Icon size={13} />
    </button>
  );
}

function MortgageDetailEditField({ theme, label, children }) {
  return (
    <div style={{ marginBottom: 12 }}>
      <div
        style={{
          fontFamily: FONTS.mono,
          fontSize: 10,
          color: theme.textMute,
          textTransform: "uppercase",
          letterSpacing: 1,
          marginBottom: 6,
        }}
      >
        {label}
      </div>
      {children}
    </div>
  );
}

function mortgageDetailInputStyle(theme) {
  return {
    width: "100%",
    background: theme.surface2,
    border: `0.5px solid ${theme.line2}`,
    borderRadius: 12,
    padding: "12px 14px",
    color: theme.text,
    fontSize: 13.5,
    fontFamily: FONTS.mono,
    outline: "none",
  };
}

function MortgageDeleteConfirmSheet({ item, theme, onCancel, onConfirm }) {
  return (
    <div
      onClick={onCancel}
      style={{
        position: "absolute",
        inset: 0,
        zIndex: 140,
        background: "rgba(0,0,0,0.6)",
        display: "flex",
        alignItems: "flex-end",
        animation: "himma-fade 200ms",
      }}
    >
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          width: "100%",
          background: theme.surface,
          borderRadius: "24px 24px 0 0",
          borderTop: `0.5px solid ${theme.line2}`,
          padding: "10px 20px 28px",
          animation: "himma-slide 260ms cubic-bezier(.2,.8,.25,1)",
        }}
      >
        <div
          style={{
            display: "flex",
            justifyContent: "center",
            paddingBottom: 14,
          }}
        >
          <div
            style={{
              width: 40,
              height: 4,
              borderRadius: 2,
              background: theme.line2,
            }}
          />
        </div>
        <div
          style={{
            width: 48,
            height: 48,
            borderRadius: 24,
            margin: "4px auto 14px",
            background: `${theme.negative}18`,
            color: theme.negative,
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
          }}
        >
          <Ico.trash size={21} />
        </div>
        <div
          style={{
            fontFamily: FONTS.display,
            fontSize: 20,
            color: theme.text,
            letterSpacing: -0.3,
            textAlign: "center",
          }}
        >
          Delete this mortgage?
        </div>
        <div
          style={{
            fontSize: 13,
            color: theme.textDim,
            marginTop: 10,
            lineHeight: 1.5,
            textAlign: "center",
            padding: "0 6px",
          }}
        >
          <b style={{ color: theme.text }}>{item.lender}</b> will be removed
          from your mortgage details.
        </div>
        <div style={{ display: "flex", gap: 10, marginTop: 22 }}>
          <button
            type="button"
            onClick={onCancel}
            style={{
              flex: 1,
              background: "transparent",
              border: `0.5px solid ${theme.line2}`,
              borderRadius: 14,
              padding: "13px",
              color: theme.text,
              fontFamily: FONTS.ui,
              fontSize: 13.5,
              fontWeight: 500,
              cursor: "pointer",
            }}
          >
            Cancel
          </button>
          <button
            type="button"
            onClick={onConfirm}
            style={{
              flex: 1,
              background: theme.negative,
              border: "none",
              borderRadius: 14,
              padding: "13px",
              color: "#fff",
              fontFamily: FONTS.ui,
              fontSize: 13.5,
              fontWeight: 600,
              cursor: "pointer",
            }}
          >
            Delete
          </button>
        </div>
      </div>
    </div>
  );
}

function PaydownChart({
  data,
  theme,
  accent,
  startLabel,
  payoffLabel,
  height = 66,
}) {
  const width = 238;
  const max = Math.max(...data, 1);
  const range = max || 1;
  const pts = data.map((v, i) => {
    const x = data.length > 1 ? (i / (data.length - 1)) * width : width;
    const y = height - (v / range) * (height - 6) - 3;
    return [x, y];
  });
  const path = "M " + pts.map((p) => p.join(" ")).join(" L ");
  const area = path + ` L ${width} ${height} L 0 ${height} Z`;
  const todayIdx = Math.floor((pts.length - 1) / 2);
  const todayPt = pts[todayIdx] || pts[0];

  return (
    <div>
      <div style={{ display: "flex", gap: 10, alignItems: "stretch" }}>
        <div
          style={{
            width: 54,
            display: "flex",
            flexDirection: "column",
            justifyContent: "space-between",
            alignItems: "flex-end",
            fontFamily: FONTS.mono,
            fontSize: 8.5,
            color: theme.textMute,
            padding: "1px 0 3px",
          }}
        >
          <PaydownAxisValue label="Original" value={max} theme={theme} />
          <PaydownAxisValue label="Half" value={max / 2} theme={theme} />
          <PaydownAxisValue label="Zero" value={0} theme={theme} />
        </div>
        <svg
          width="100%"
          height={height}
          viewBox={`0 0 ${width} ${height}`}
          preserveAspectRatio="none"
          style={{ display: "block", overflow: "visible", flex: 1 }}
        >
          {[3, height / 2, height - 3].map((y) => (
            <line
              key={y}
              x1="0"
              x2={width}
              y1={y}
              y2={y}
              stroke={theme.line2}
              strokeWidth="0.5"
              vectorEffect="non-scaling-stroke"
            />
          ))}
          <path d={area} fill={accent} opacity="0.10" />
          <path
            d={path}
            fill="none"
            stroke={accent}
            strokeWidth="1.7"
            strokeLinecap="round"
            strokeLinejoin="round"
            vectorEffect="non-scaling-stroke"
          />
          <line
            x1={todayPt[0]}
            x2={todayPt[0]}
            y1="0"
            y2={height}
            stroke={theme.textMute}
            strokeDasharray="3 4"
            strokeWidth="0.8"
            vectorEffect="non-scaling-stroke"
          />
          <circle cx={todayPt[0]} cy={todayPt[1]} r="3" fill={accent} />
        </svg>
      </div>
      <div
        style={{
          display: "grid",
          gridTemplateColumns: "54px 1fr",
          gap: 10,
          marginTop: 5,
          fontFamily: FONTS.mono,
          fontSize: 9,
          color: theme.textMute,
          letterSpacing: 0.4,
        }}
      >
        <span />
        <div style={{ display: "flex", justifyContent: "space-between" }}>
          <span>{startLabel}</span>
          <span>Today</span>
          <span>{payoffLabel}</span>
        </div>
      </div>
    </div>
  );
}

function PaydownAxisValue({ label, value, theme }) {
  return (
    <div style={{ textAlign: "right", lineHeight: 1.15 }}>
      <div>{label}</div>
      <div style={{ color: theme.textDim, marginTop: 1 }}>
        <Dh /> {fmtAED(value, { compact: true })}
      </div>
    </div>
  );
}

function MortgageInsightCell({
  theme,
  icon,
  label,
  value,
  borderRight = false,
}) {
  return (
    <div
      style={{
        minHeight: 68,
        padding: "12px 12px",
        borderRight: borderRight ? `0.5px solid ${theme.line}` : "none",
        display: "flex",
        flexDirection: "column",
        justifyContent: "space-between",
        gap: 7,
      }}
    >
      <div
        style={{
          display: "flex",
          alignItems: "center",
          gap: 6,
          color: theme.textMute,
        }}
      >
        {icon}
        <div
          style={{
            fontFamily: FONTS.mono,
            fontSize: 8.8,
            letterSpacing: 0.9,
            textTransform: "uppercase",
            lineHeight: 1.2,
          }}
        >
          {label}
        </div>
      </div>
      <div
        style={{
          fontFamily: FONTS.display,
          fontSize: 16,
          lineHeight: 1.1,
          color: theme.text,
          fontVariantNumeric: "tabular-nums",
        }}
      >
        {value}
      </div>
    </div>
  );
}

function MortgageMetricTile({ theme, label, value, sub, tone }) {
  return (
    <div
      style={{
        minHeight: 76,
        padding: "10px 12px",
        background: theme.surface,
        border: `0.5px solid ${theme.line}`,
        borderRadius: 14,
        display: "flex",
        flexDirection: "column",
        justifyContent: "space-between",
        gap: 7,
      }}
    >
      <div
        style={{
          fontFamily: FONTS.mono,
          fontSize: 8.8,
          color: theme.textMute,
          textTransform: "uppercase",
          letterSpacing: 0.9,
          lineHeight: 1.25,
        }}
      >
        {label}
      </div>
      <div>
        <div
          style={{
            fontFamily: FONTS.display,
            fontSize: 16,
            color: theme.text,
            letterSpacing: -0.3,
            lineHeight: 1.05,
            fontVariantNumeric: "tabular-nums",
          }}
        >
          {value}
        </div>
        {sub && (
          <div
            style={{
              marginTop: 5,
              fontFamily: FONTS.mono,
              fontSize: 9.5,
              color: theme.textDim,
            }}
          >
            {sub}
          </div>
        )}
      </div>
    </div>
  );
}

function MortgageProjectionRow({ theme, label, value, sub }) {
  return (
    <div
      style={{
        marginTop: 14,
        display: "flex",
        alignItems: "flex-end",
        justifyContent: "space-between",
        gap: 14,
      }}
    >
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 13, fontWeight: 600, color: theme.text }}>
          {label}
        </div>
        <div
          style={{
            marginTop: 3,
            fontFamily: FONTS.mono,
            fontSize: 10.5,
            color: theme.textDim,
          }}
        >
          {sub}
        </div>
      </div>
      <div
        style={{
          fontFamily: FONTS.display,
          fontSize: 24,
          color: theme.text,
          lineHeight: 1,
          letterSpacing: -0.4,
          fontVariantNumeric: "tabular-nums",
          whiteSpace: "nowrap",
        }}
      >
        {value}
      </div>
    </div>
  );
}

function getCardRecentTransactions(card) {
  const issuer = card.issuer || "";
  const tokens = issuer.split(/\s+/).filter((t) => t.length > 2);
  const matches = TRANSACTIONS.filter((tx) => {
    if (tx.amount >= 0) return false;
    const account = tx.account || "";
    return (
      account.includes(issuer) ||
      issuer.includes(account) ||
      tokens.some((token) => account.includes(token))
    );
  });
  return (
    matches.length ? matches : TRANSACTIONS.filter((tx) => tx.amount < 0)
  ).slice(0, 4);
}

function CardTransactionRow({ tx, theme, accent, last }) {
  return (
    <div
      style={{
        display: "flex",
        alignItems: "center",
        gap: 12,
        padding: "12px 16px",
        borderBottom: last ? "none" : `0.5px solid ${theme.line}`,
      }}
    >
      <CategoryIcon
        category={tx.category}
        theme={theme}
        accent={accent}
        size={32}
      />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div
          style={{
            fontSize: 13,
            color: theme.text,
            fontWeight: 500,
            overflow: "hidden",
            textOverflow: "ellipsis",
            whiteSpace: "nowrap",
          }}
        >
          {tx.merchant}
        </div>
        <div
          style={{
            fontFamily: FONTS.mono,
            fontSize: 10,
            color: theme.textMute,
            marginTop: 2,
          }}
        >
          {tx.date}
        </div>
      </div>
      <div
        style={{
          fontFamily: FONTS.mono,
          fontSize: 12.5,
          color: theme.text,
          fontVariantNumeric: "tabular-nums",
          whiteSpace: "nowrap",
        }}
      >
        −<Dh /> {fmtAED(Math.abs(tx.amount))}
      </div>
    </div>
  );
}

function DetailStat({ label, value, theme }) {
  return (
    <div>
      <div
        style={{
          fontFamily: FONTS.mono,
          fontSize: 9.5,
          color: theme.textMute,
          textTransform: "uppercase",
          letterSpacing: 1,
        }}
      >
        {label}
      </div>
      <div
        style={{
          fontFamily: FONTS.display,
          fontSize: 17,
          color: theme.text,
          marginTop: 4,
          letterSpacing: -0.3,
          fontVariantNumeric: "tabular-nums",
        }}
      >
        {value}
      </div>
    </div>
  );
}

Object.assign(window, { LiabilityDetailScreen });
