// Liability detail — full-screen view of a single mortgage / loan / credit card.
// Shows a paydown chart, headline stats (balance, APR, term, payoff),
// 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 an amortization-style paydown trajectory: 6 months back, today, and
// the projected curve through the remaining term. Pure visual — uses simple
// declining-balance interpolation (close enough for a chart).
function buildPaydown(item, kind) {
  const monthly = item.monthlyPayment ?? item.minPayment ?? 0;
  if (kind === 'card' || !monthly) {
    // Cards don't amortize cleanly — show a flat line at current balance
    // with a subtle dip if user pays more than min.
    return new Array(12).fill(item.balance);
  }
  const apr = item.apr / 100;
  const r = apr / 12;
  // Roughly back-fill 6 months of history at the same payment
  const back = [];
  let bal = item.balance;
  for (let i = 0; i < 6; i++) {
    bal = bal + monthly - bal * r;
    back.unshift(bal);
  }
  // Forward-project until balance hits zero (cap at 60 months for chart sanity)
  const fwd = [item.balance];
  let f = item.balance;
  for (let i = 0; i < 60 && f > 0; i++) {
    f = Math.max(0, f * (1 + r) - monthly);
    fwd.push(f);
  }
  return [...back, ...fwd];
}

function LiabilityDetailScreen({ theme, accent, liabilityKind, liabilityId, onBack, onAskHimma }) {
  const item = findLiability(liabilityKind, liabilityId) ||
               LIABILITIES.mortgages[0]; // sensible fallback for the prototype
  const kind = liabilityKind && LIABILITY_KIND_LABELS[liabilityKind]
    ? liabilityKind
    : 'mortgage';

  const isCard = kind === 'card';
  const title    = item.lender || item.issuer;
  const subtitle = isCard
    ? `${item.last} · ${item.apr.toFixed(0)}% APR`
    : `${item.term || ''} · since ${item.originationDate || '—'}`;

  const balance        = item.balance;
  const original       = item.originalAmount || (isCard ? item.limit : item.balance);
  const paid           = isCard ? 0 : Math.max(0, original - balance);
  const paidPct        = original ? (paid / original) * 100 : 0;
  const monthly        = item.monthlyPayment ?? item.minPayment ?? 0;
  const payoff         = item.payoffDate || null;
  const trajectory     = buildPaydown(item, kind);

  const Icon = kind === 'mortgage' ? Ico.building
            : kind === 'card'     ? Ico.wallet
            :                       Ico.wallet;

  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={{
            width: 40, height: 40, borderRadius: 12,
            background: `${accent}18`, color: accent,
            display:'flex', alignItems:'center', justifyContent:'center',
          }}><Icon size={20}/></div>
          <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 style={{ fontFamily: FONTS.mono, fontSize: 11, color: theme.textMute, marginTop: 4 }}>{subtitle}</div>
          </div>
        </div>
      </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>
          )}

          {/* Paydown trajectory chart */}
          <div style={{ marginTop: 18 }}>
            <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom: 6 }}>
              <SectionLabel theme={theme}>Paydown trajectory</SectionLabel>
              {!isCard && (
                <span style={{ fontFamily: FONTS.mono, fontSize: 9, letterSpacing: 1, color: theme.textMute, textTransform:'uppercase' }}>
                  6m back · projected
                </span>
              )}
            </div>
            <Spark
              data={trajectory}
              width={310}
              height={48}
              color={accent}
              responsive
            />
            <div style={{ display:'flex', justifyContent:'space-between', fontFamily: FONTS.mono, fontSize: 9, color: theme.textMute, marginTop: 4, letterSpacing: 0.5 }}>
              <span>{isCard ? 'Today' : '6 mo ago'}</span>
              <span>{isCard ? '' : 'Today'}</span>
              <span>{payoff ? `Payoff · ${payoff}` : (isCard ? '' : 'Projected')}</span>
            </div>
          </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 · <Dh/> {fmtAED(paid, {compact: paid >= 100_000})} cleared
              </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 }}>
            <DetailStat
              label={isCard ? 'Credit limit' : 'Original amount'}
              value={<><Dh/> {fmtAED(isCard ? item.limit : original, {compact: true})}</>}
              theme={theme}
            />
            <DetailStat
              label="APR"
              value={`${item.apr.toFixed(2)}%`}
              theme={theme}
            />
            <DetailStat
              label={isCard ? 'Min payment' : 'Monthly payment'}
              value={<><Dh/> {fmtAED(monthly)}</>}
              theme={theme}
            />
            <DetailStat
              label={isCard ? 'Statement date' : 'Term'}
              value={isCard ? item.statementDate : (item.term || '—')}
              theme={theme}
            />
            {!isCard && payoff && (
              <DetailStat
                label="Payoff date"
                value={payoff}
                theme={theme}
              />
            )}
            {!isCard && item.originationDate && (
              <DetailStat
                label="Started"
                value={item.originationDate}
                theme={theme}
              />
            )}
          </div>
        </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>
    </Screen>
  );
}

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 });
