// Debt tracker — avalanche vs snowball, payoff projections, animated bars.

const PageDebt = () => {
  const { state, derived, addDebt, deleteDebt, updateDebt, loadDemo } = useAppState();
  const [showAdd, setShowAdd] = React.useState(false);
  const [strategy, setStrategy] = React.useState('avalanche'); // avalanche | snowball
  const [extra, setExtra] = React.useState(1000);

  const debts = state.debts;
  const total = debts.reduce((a, d) => a + d.balance, 0);
  const minTotal = debts.reduce((a, d) => a + d.minimum, 0);

  // Calculate payoff plan
  const planAvalanche = simulatePayoff(debts, minTotal + extra, 'avalanche');
  const planSnowball = simulatePayoff(debts, minTotal + extra, 'snowball');
  const plan = strategy === 'avalanche' ? planAvalanche : planSnowball;

  const interestSavings = planSnowball.totalInterest - planAvalanche.totalInterest;

  // Recommendation
  const recommend = (() => {
    if (debts.length === 0) return null;
    if (Math.abs(interestSavings) < 500) {
      return { strategy: 'snowball', reason: "Your debts are balanced — go for snowball wins to stay motivated." };
    }
    return {
      strategy: 'avalanche',
      reason: `Avalanche saves you ${fmtZARShort(Math.abs(interestSavings))} in interest vs snowball.`,
    };
  })();

  if (debts.length === 0) {
    return (
      <div>
        <div className="topbar">
          <div>
            <h1 className="page-title">Debt tracker</h1>
            <div className="page-sub">Pay it off the smart way</div>
          </div>
        </div>
        <div className="empty">
          <div className="empty-icon"><IDebt size={22}/></div>
          <h3 className="serif" style={{fontSize:22}}>No debts tracked</h3>
          <p>Add your loans, credit cards or store accounts and we'll show you the fastest payoff path.</p>
          <div className="row" style={{justifyContent:'center', gap:8}}>
            <button className="btn btn-primary" onClick={() => setShowAdd(true)}><IPlus size={14}/> Add debt</button>
            <button className="btn" onClick={loadDemo}><IPlay size={13}/> Load demo</button>
          </div>
        </div>
        {showAdd && <AddDebtModal onClose={() => setShowAdd(false)} onAdd={d => { addDebt(d); setShowAdd(false); }}/>}
      </div>
    );
  }

  return (
    <div>
      <div className="topbar">
        <div>
          <h1 className="page-title">Debt <span className="serif">tracker</span></h1>
          <div className="page-sub">{debts.length} debts · {fmtZAR(total, {cents:false})} total</div>
        </div>
        <button className="btn btn-primary" onClick={() => setShowAdd(true)}><IPlus size={14}/> Add debt</button>
      </div>

      {/* Top KPIs */}
      <div className="grid" style={{gridTemplateColumns:'repeat(3, 1fr)', gap:16, marginBottom:20}}>
        <KPICard label="Total debt" value={total} icon={IDebt} sub={`${debts.length} accounts`}/>
        <KPICard label="Minimum payments" value={minTotal} icon={IBolt} accent="amber" sub="Per month"/>
        <KPICard label="Debt-free in" value={Math.round(plan.months)} icon={ITarget} accent="mint" sub={`with extra ${fmtZARShort(extra)}/mo`}/>
      </div>

      {/* Strategy selector + recommendation */}
      <div className="card card-pad-lg fade-up" style={{marginBottom:20}}>
        <div className="row-between" style={{marginBottom:18, flexWrap:'wrap', gap:12}}>
          <div>
            <div className="card-title" style={{margin:0}}>Payoff strategy</div>
            <div className="serif" style={{fontSize:22, marginTop:2}}>Compare avalanche vs snowball</div>
          </div>
          <div className="mode-toggle">
            <button className={strategy === 'avalanche' ? 'active' : ''} onClick={() => setStrategy('avalanche')}>
              <IFire size={12}/> Avalanche
            </button>
            <button className={strategy === 'snowball' ? 'active' : ''} onClick={() => setStrategy('snowball')}>
              <ISpark size={12}/> Snowball
            </button>
          </div>
        </div>

        <div className="grid" style={{gridTemplateColumns:'1fr 1fr', gap:20}}>
          <div className="card card-pad" style={{
            background: strategy === 'avalanche' ? 'var(--ink)' : 'var(--surface-2)',
            color: strategy === 'avalanche' ? 'white' : 'var(--ink)',
            border: 'none',
            transition:'all 0.3s',
          }}>
            <div className="row" style={{gap:8, marginBottom:10}}>
              <IFire size={15}/>
              <span style={{fontSize:11, textTransform:'uppercase', letterSpacing:'0.06em', fontWeight:500}}>Avalanche</span>
            </div>
            <div className="serif" style={{fontSize:32, lineHeight:1}}>{Math.round(planAvalanche.months)} <span style={{fontSize:14, opacity:0.6}}>months</span></div>
            <div style={{fontSize:12, opacity:0.7, marginTop:6}}>Pays {fmtZARShort(planAvalanche.totalInterest)} interest · highest APR first</div>
          </div>
          <div className="card card-pad" style={{
            background: strategy === 'snowball' ? 'var(--ink)' : 'var(--surface-2)',
            color: strategy === 'snowball' ? 'white' : 'var(--ink)',
            border: 'none',
            transition:'all 0.3s',
          }}>
            <div className="row" style={{gap:8, marginBottom:10}}>
              <ISpark size={15}/>
              <span style={{fontSize:11, textTransform:'uppercase', letterSpacing:'0.06em', fontWeight:500}}>Snowball</span>
            </div>
            <div className="serif" style={{fontSize:32, lineHeight:1}}>{Math.round(planSnowball.months)} <span style={{fontSize:14, opacity:0.6}}>months</span></div>
            <div style={{fontSize:12, opacity:0.7, marginTop:6}}>Pays {fmtZARShort(planSnowball.totalInterest)} interest · smallest balance first</div>
          </div>
        </div>

        {recommend && (
          <div className="row" style={{
            marginTop:18,
            padding:'14px 16px',
            background:'var(--mint-soft)',
            borderRadius:12,
            color:'var(--mint-deep)',
            gap:12,
          }}>
            <ISparkle size={16}/>
            <div style={{flex:1, fontSize:13, fontWeight:500}}>
              We recommend <strong style={{textTransform:'capitalize'}}>{recommend.strategy}</strong> — {recommend.reason}
            </div>
            <button className="btn btn-sm" onClick={() => setStrategy(recommend.strategy)} style={{background:'white', borderColor:'transparent', color:'var(--mint-deep)'}}>
              Use it
            </button>
          </div>
        )}

        {/* Extra payment slider */}
        <div style={{marginTop:18}}>
          <div className="row-between" style={{marginBottom:10}}>
            <span style={{fontSize:13, color:'var(--ink-3)', fontWeight:500}}>Extra payment per month</span>
            <span className="mono" style={{fontWeight:500}}>{fmtZAR(extra, {cents:false})}</span>
          </div>
          <input type="range" min="0" max="10000" step="100" value={extra} onChange={e => setExtra(parseInt(e.target.value))}
            style={{width:'100%', accentColor:'var(--ink)'}}/>
          <div className="row-between mono" style={{fontSize:11, color:'var(--ink-3)', marginTop:4}}>
            <span>R 0</span><span>R 10 000</span>
          </div>
        </div>
      </div>

      {/* Payoff order */}
      <div className="card card-pad-lg fade-up" style={{marginBottom:20}}>
        <div className="card-title">Payoff order · {strategy}</div>
        <StackedProgress items={debts.map(d => ({ value: d.balance, cssVar: '--coral' }))}/>
        <div style={{marginTop:18, display:'flex', flexDirection:'column', gap:14}}>
          {plan.order.map((d, i) => {
            const pct = d.balance / total;
            const member = state.members.find(m => m.id === d.memberId);
            return (
              <div key={d.id} className="card" style={{
                padding:'16px 18px',
                border:'1px solid var(--line)',
                animation:`fadeUp 0.4s ${i * 0.06}s both`,
              }}>
                <div className="row-between" style={{marginBottom:10}}>
                  <div className="row" style={{gap:12}}>
                    <div style={{
                      width:32, height:32, borderRadius:9,
                      background: i === 0 ? 'var(--ink)' : 'var(--surface-2)',
                      color: i === 0 ? 'white' : 'var(--ink-2)',
                      display:'inline-flex', alignItems:'center', justifyContent:'center',
                      fontSize:13, fontWeight:600,
                    }}>{i+1}</div>
                    <div>
                      <div style={{fontWeight:500, fontSize:14}}>{d.name} {i === 0 && <span className="pill pill-mint" style={{marginLeft:6}}><IFire size={10}/> Focus</span>}</div>
                      <div style={{fontSize:11.5, color:'var(--ink-3)', marginTop:2}}>
                        {d.apr}% APR · Min {fmtZARShort(d.minimum)}/mo
                        {state.mode === 'household' && member && ` · ${member.name}`}
                      </div>
                    </div>
                  </div>
                  <div style={{textAlign:'right'}}>
                    <div className="mono" style={{fontWeight:500, fontSize:15}}>{fmtZAR(d.balance, {cents:false})}</div>
                    <div style={{fontSize:11, color:'var(--ink-3)', marginTop:2}}>Paid off month {d.payoffMonth}</div>
                  </div>
                </div>
                <div className="progress-track">
                  <div className="progress-fill" style={{
                    width: `${(1 - d.balance / d.originalBalance) * 100}%`,
                    background: i === 0 ? 'var(--mint)' : 'var(--coral)',
                  }}/>
                </div>
                <div className="row-between" style={{marginTop:6, fontSize:11, color:'var(--ink-3)'}}>
                  <span>{((1 - d.balance / d.originalBalance) * 100).toFixed(0)}% paid</span>
                  <span className="mono">of {fmtZAR(d.originalBalance, {cents:false})}</span>
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {/* Debt list with delete */}
      <div className="card fade-up" style={{overflow:'hidden'}}>
        <div className="card-pad-lg" style={{paddingBottom:0}}>
          <div className="card-title">Your debts</div>
        </div>
        <table className="table">
          <thead>
            <tr>
              <th>Name</th>
              <th>APR</th>
              <th>Minimum</th>
              <th style={{textAlign:'right'}}>Balance</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            {debts.map(d => (
              <tr key={d.id} className="row-hov">
                <td style={{fontWeight:500}}>{d.name}</td>
                <td data-label="APR" className="mono">{d.apr}%</td>
                <td data-label="Minimum" className="mono">{fmtZAR(d.minimum, {cents:false})}</td>
                <td data-label="Balance" className="mono" style={{textAlign:'right', fontWeight:500}}>{fmtZAR(d.balance, {cents:false})}</td>
                <td><button className="btn btn-ghost btn-sm" onClick={() => deleteDebt(d.id)}><ITrash size={13}/></button></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {showAdd && <AddDebtModal onClose={() => setShowAdd(false)} onAdd={d => { addDebt(d); setShowAdd(false); }}/>}
    </div>
  );
};

// Simulate debt payoff (simple monthly amortization)
function simulatePayoff(debts, totalPayment, strategy) {
  const sim = debts.map(d => ({ ...d }));
  let month = 0;
  let totalInterest = 0;
  const order = [];
  const MAX_MONTHS = 600;

  while (sim.some(d => d.balance > 0.01) && month < MAX_MONTHS) {
    month++;
    // Accrue interest
    sim.forEach(d => {
      if (d.balance > 0) {
        const interest = d.balance * (d.apr / 100 / 12);
        d.balance += interest;
        totalInterest += interest;
      }
    });

    // Sort active debts by strategy
    let active = sim.filter(d => d.balance > 0.01);
    if (strategy === 'avalanche') active.sort((a, b) => b.apr - a.apr);
    else active.sort((a, b) => a.balance - b.balance);

    // Pay minimums first
    let pool = totalPayment;
    sim.forEach(d => {
      if (d.balance > 0.01) {
        const pay = Math.min(d.minimum, d.balance, pool);
        d.balance -= pay;
        pool -= pay;
      }
    });

    // Throw remainder at the focus debt
    if (pool > 0 && active.length) {
      // Find focus from re-sorted list (post-min payment, still active)
      const stillActive = sim.filter(d => d.balance > 0.01);
      if (stillActive.length) {
        if (strategy === 'avalanche') stillActive.sort((a, b) => b.apr - a.apr);
        else stillActive.sort((a, b) => a.balance - b.balance);
        const focus = stillActive[0];
        const pay = Math.min(focus.balance, pool);
        focus.balance -= pay;
      }
    }

    // Record payoff order
    sim.forEach(d => {
      if (d.balance <= 0.01 && !order.find(o => o.id === d.id)) {
        order.push({ ...d, payoffMonth: month });
      }
    });
  }

  // Add any remaining debts (in case we hit MAX)
  sim.forEach(d => {
    if (!order.find(o => o.id === d.id)) {
      order.push({ ...d, payoffMonth: month });
    }
  });

  // Sort order by strategy for display
  const display = [...debts].map(d => {
    const o = order.find(x => x.id === d.id) || { payoffMonth: month };
    return { ...d, payoffMonth: o.payoffMonth };
  });
  if (strategy === 'avalanche') display.sort((a, b) => b.apr - a.apr);
  else display.sort((a, b) => a.balance - b.balance);

  return { months: month, totalInterest, order: display };
}

const AddDebtModal = ({ onClose, onAdd }) => {
  const { state } = useAppState();
  const [name, setName] = React.useState('');
  const [balance, setBalance] = React.useState('');
  const [apr, setApr] = React.useState('');
  const [minimum, setMinimum] = React.useState('');
  const [memberId, setMemberId] = React.useState(state.members[0]?.id);

  const submit = (e) => {
    e.preventDefault();
    onAdd({
      name: name.trim() || 'New debt',
      balance: parseFloat(balance) || 0,
      apr: parseFloat(apr) || 0,
      minimum: parseFloat(minimum) || 0,
      memberId,
    });
  };

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <div className="row-between" style={{marginBottom:18}}>
          <div className="serif" style={{fontSize:24}}>New debt</div>
          <button className="btn btn-ghost btn-sm" onClick={onClose}><IClose size={16}/></button>
        </div>
        <form onSubmit={submit} className="grid" style={{gap:14}}>
          <div className="field">
            <label className="label">Name</label>
            <input className="input" value={name} onChange={e => setName(e.target.value)} placeholder="e.g. Credit card — FNB" autoFocus required/>
          </div>
          <div className="grid" style={{gridTemplateColumns:'1fr 1fr', gap:12}}>
            <div className="field">
              <label className="label">Balance (R)</label>
              <input className="input" type="number" step="0.01" value={balance} onChange={e => setBalance(e.target.value)} required/>
            </div>
            <div className="field">
              <label className="label">APR %</label>
              <input className="input" type="number" step="0.1" value={apr} onChange={e => setApr(e.target.value)} required/>
            </div>
          </div>
          <div className="field">
            <label className="label">Minimum payment / month</label>
            <input className="input" type="number" step="0.01" value={minimum} onChange={e => setMinimum(e.target.value)} required/>
          </div>
          {state.mode === 'household' && (
            <div className="field">
              <label className="label">Whose debt</label>
              <div className="row" style={{gap:8, flexWrap:'wrap'}}>
                {state.members.map(m => (
                  <button type="button" key={m.id} className="member-chip" style={{
                    cursor:'pointer',
                    borderColor: memberId === m.id ? 'var(--ink)' : 'var(--line)',
                  }} onClick={() => setMemberId(m.id)}>
                    <span className="avatar" style={{background: m.color}}>{m.initials}</span>
                    {m.name}
                  </button>
                ))}
              </div>
            </div>
          )}
          <div className="row" style={{gap:8, marginTop:6}}>
            <button type="button" className="btn" style={{flex:1, justifyContent:'center'}} onClick={onClose}>Cancel</button>
            <button type="submit" className="btn btn-primary" style={{flex:1, justifyContent:'center'}}>Add debt</button>
          </div>
        </form>
      </div>
    </div>
  );
};

Object.assign(window, { PageDebt, AddDebtModal, simulatePayoff });
