/* gigi-advances.jsx — advance request wizard + repayment tracking */

// ── Advance status card ────────────────────────────────────────
function AdvanceCard({a, adv, onClick}) {
    const G = window.GIGI;
    const pct = Math.round(adv.withheld / adv.gross * 100);
    return (
        <Card onClick={onClick} style={{padding: 0, overflow: 'hidden'}}>
            <div style={{background: 'var(--accent-ink)', color: '#fff', padding: 'var(--pad)'}}>
                <div style={{
                    display: 'flex',
                    justifyContent: 'space-between',
                    alignItems: 'flex-start',
                    marginBottom: 14
                }}>
                    <div>
                        <div style={{
                            color: 'var(--pill-ink)',
                            fontSize: 12,
                            fontWeight: 600,
                            marginBottom: 5
                        }}>{a.name}</div>
                        <div className="g-num" style={{fontSize: 28, fontWeight: 700}}>{G.fmtKES(adv.gross)}</div>
                    </div>
                    <Badge tone="accent">Repaying</Badge>
                </div>
                <div style={{height: 6, borderRadius: 999, background: 'rgba(255,255,255,.15)', overflow: 'hidden'}}>
                    <div style={{width: pct + '%', height: '100%', background: 'var(--accent)', borderRadius: 999}}/>
                </div>
                <div style={{
                    display: 'flex',
                    justifyContent: 'space-between',
                    marginTop: 8,
                    fontSize: 12,
                    color: 'rgba(255,255,255,.65)'
                }}>
                    <span>{G.fmtKES(adv.withheld, {compact: true})} repaid ({pct}%)</span>
                    <span>{G.fmtKES(adv.outstanding, {compact: true})} remaining</span>
                </div>
            </div>
            <div style={{
                padding: '14px var(--pad)',
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center'
            }}>
                <div>
                    <div style={{fontSize: 13, color: 'var(--ink-2)'}}>Next payment</div>
                    <div className="g-mono" style={{fontSize: 13, fontWeight: 700, marginTop: 2}}>
                        {G.fmtKES(adv.schedule.find(s => s.state === 'SCHEDULED')?.amount || 0, {compact: true})} · {adv.schedule.find(s => s.state === 'SCHEDULED')?.due || '—'}
                    </div>
                </div>
                <Icon name="chevR" size={18} style={{color: 'var(--ink-3)'}}/>
            </div>
        </Card>
    );
}

// ── Inline financing request form (Advances page) ─────────────
function InlineFinancingForm({org, onRequest}) {
    const G = window.GIGI;
    const eligibles = G.assets.filter(a => a.org === org.id && a.status === 'ELIGIBLE');
    const [assetId, setAssetId] = React.useState(eligibles[0]?.id || null);
    const [months, setMonths] = React.useState(3);

    if (eligibles.length === 0) {
        return (
            <Card style={{
                marginBottom: 28,
                display: 'flex',
                alignItems: 'center',
                gap: 14,
                background: 'var(--surface-2)',
                boxShadow: 'none'
            }}>
                <div style={{
                    width: 44,
                    height: 44,
                    borderRadius: 12,
                    background: 'var(--surface)',
                    display: 'grid',
                    placeItems: 'center',
                    color: 'var(--ink-3)',
                    flexShrink: 0
                }}>
                    <Icon name="lock" size={22}/>
                </div>
                <div>
                    <div style={{fontWeight: 700, fontSize: 14.5}}>No properties are eligible yet</div>
                    <div style={{fontSize: 13, color: 'var(--ink-3)', marginTop: 2, lineHeight: 1.45}}>
                        A property needs verified ownership, an active tenancy, and ≥85% occupancy before you can
                        request financing.
                    </div>
                </div>
            </Card>
        );
    }

    const asset = G.assets.find(a => a.id === assetId) || eligibles[0];
    const q = G.quoteAdvance(asset.verifiedRent, months);

    return (
        <Card style={{padding: 0, overflow: 'hidden', marginBottom: 28}}>
            <div className="g-fin-grid" style={{display: 'grid', gridTemplateColumns: '1.1fr 1fr'}}>
                {/* Left — form */}
                <div style={{padding: '24px'}}>
                    <div style={{display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6}}>
                        <Icon name="bolt" size={17} style={{color: 'var(--accent-ink)'}}/>
                        <span style={{
                            fontSize: 12,
                            fontWeight: 700,
                            color: 'var(--ink-3)',
                            textTransform: 'uppercase',
                            letterSpacing: '.05em'
                        }}>Request financing</span>
                    </div>
                    <h3 className="g-num" style={{margin: '0 0 4px', fontSize: 21, fontWeight: 700}}>Advance against a
                        property</h3>
                    <p style={{margin: '0 0 20px', fontSize: 13, color: 'var(--ink-2)', lineHeight: 1.5}}>
                        Borrow up to 60% of your verified monthly rent, for up to 3 months. Repaid automatically from
                        collected rent.
                    </p>

                    {/* Property selector */}
                    <div style={{marginBottom: 18}}>
                        <Select label="Property" value={assetId} onChange={setAssetId}
                                options={eligibles.map(a => ({
                                    value: a.id,
                                    label: `${a.name} · ${G.fmtKES(a.verifiedRent, {compact: true})}/mo`
                                }))}/>
                    </div>

                    {/* Term */}
                    <div>
                        <div style={{fontSize: 12.5, fontWeight: 600, color: 'var(--ink-2)', marginBottom: 8}}>Term
                        </div>
                        <div style={{display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10}}>
                            {[3, 6].map(mo => {
                                const on = months === mo, locked = mo === 6;
                                return (
                                    <div key={mo} onClick={() => !locked && setMonths(mo)}
                                         className={locked ? '' : 'g-tap'} style={{
                                        padding: '14px',
                                        borderRadius: 'var(--r-md)',
                                        textAlign: 'center',
                                        opacity: locked ? 0.4 : 1,
                                        border: `1.5px solid ${on ? 'var(--accent-ink)' : 'var(--line)'}`,
                                        boxShadow: on ? 'var(--shadow)' : 'none',
                                        background: 'var(--surface)'
                                    }}>
                                        <div className="g-num" style={{fontSize: 22, fontWeight: 700}}>{mo}</div>
                                        <div style={{
                                            fontSize: 12,
                                            color: 'var(--ink-3)'
                                        }}>months{locked ? ' · soon' : ''}</div>
                                    </div>
                                );
                            })}
                        </div>
                    </div>
                </div>

                {/* Right — live quote (dark) */}
                <div style={{
                    background: 'var(--accent-ink)',
                    color: '#fff',
                    padding: '24px',
                    display: 'flex',
                    flexDirection: 'column'
                }}>
                    <div style={{color: 'var(--pill-ink)', fontSize: 12.5, fontWeight: 600}}>Net to your account</div>
                    <div className="g-num" style={{
                        fontSize: 40,
                        fontWeight: 700,
                        margin: '8px 0 4px',
                        letterSpacing: '-.02em'
                    }}>{G.fmtKES(q.net)}</div>
                    <div style={{
                        fontSize: 12.5,
                        color: 'rgba(255,255,255,.6)',
                        marginBottom: 20
                    }}>{asset.name} · {months}-month term
                    </div>

                    <div style={{
                        borderTop: '1px solid rgba(255,255,255,.14)',
                        paddingTop: 14,
                        display: 'flex',
                        flexDirection: 'column',
                        gap: 11
                    }}>
                        <div style={{display: 'flex', justifyContent: 'space-between', fontSize: 13.5}}>
                            <span style={{color: 'rgba(255,255,255,.65)'}}>Gross advance</span>
                            <span className="g-mono" style={{fontWeight: 700}}>{G.fmtKES(q.gross)}</span>
                        </div>
                        <div style={{display: 'flex', justifyContent: 'space-between', fontSize: 13.5}}>
                            <span style={{color: 'rgba(255,255,255,.65)'}}>Service fee (1.8%/mo × {months})</span>
                            <span className="g-mono" style={{fontWeight: 700}}>− {G.fmtKES(q.fee)}</span>
                        </div>
                    </div>

                    <div style={{marginTop: 'auto', paddingTop: 20}}>
                        <Btn kind="accent" icon="bolt" full onClick={() => onRequest(asset, months)}>Request
                            advance</Btn>
                        <div style={{
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'center',
                            gap: 7,
                            marginTop: 12,
                            fontSize: 12,
                            color: 'rgba(255,255,255,.55)'
                        }}>
                            <Icon name="clock" size={13}/>Disbursed within 15 minutes of approval
                        </div>
                    </div>
                </div>
            </div>
        </Card>
    );
}

// ── Advances page ──────────────────────────────────────────────
function AdvancesPage({role, org, onRequestAdvance, onOpenAdvance}) {
    const G = window.GIGI;
    const activeAssets = G.assets.filter(a => a.org === org.id && a.status === 'ADVANCE_ACTIVE' && a.advance);
    const eligibleAssets = G.assets.filter(a => a.org === org.id && a.status === 'ELIGIBLE');

    return (
        <div>
            <PageHeader title="Capital Advances" subtitle={org.name}/>

            {/* KPIs */}
            <div className="g-3col" style={{marginBottom: 28}}>
                <KpiCard label="Total lendable equity" value={G.fmtKES(G.kpis.lendableEquity, {compact: true})}
                         icon="bolt" dark sub="Across eligible properties"/>
                <KpiCard label="Active advances" value={G.kpis.activeAdvances} icon="sync"
                         sub={G.fmtKES(G.kpis.activeAdvanceAmount, {compact: true}) + ' outstanding'}/>
                <KpiCard label="Eligible properties" value={eligibleAssets.length} icon="building"
                         sub="Ready to advance against"/>
            </div>

            {/* Inline financing request form */}
            {/*<InlineFinancingForm org={org} onRequest={(asset, months) => onRequestAdvance(asset, months)}/>*/}

            {/* Active advances */}
            {activeAssets.length > 0 && (
                <div style={{marginBottom: 28}}>
                    <SectionLabel>Active repayments</SectionLabel>
                    <div style={{display: 'flex', flexDirection: 'column', gap: 12}}>
                        {activeAssets.map(a => (
                            <AdvanceCard key={a.id} a={a} adv={a.advance} onClick={() => onOpenAdvance(a.id)}/>
                        ))}
                    </div>
                </div>
            )}

            {/* Eligible properties */}
            <div>
                <SectionLabel>Eligible assets</SectionLabel>
                {eligibleAssets.length === 0
                    ? <Empty icon="lock" title="No eligible properties"
                             body="Properties need verified ownership, active tenancy, and ≥85% occupancy to qualify for advances."/>
                    : <div style={{display: 'flex', flexDirection: 'column', gap: 10}}>
                        {eligibleAssets.map(a => {
                            const q = G.quoteAdvance(a.verifiedRent, 3);
                            return (
                                <Card key={a.id} onClick={() => onRequestAdvance(a)}
                                      style={{display: 'flex', alignItems: 'center', gap: 14}}>
                                    <div style={{
                                        width: 44,
                                        height: 44,
                                        borderRadius: 13,
                                        background: 'var(--accent-ink)',
                                        color: 'var(--pill-ink)',
                                        display: 'grid',
                                        placeItems: 'center',
                                        flexShrink: 0
                                    }}>
                                        <Icon name="bolt" size={22} style={{color: 'var(--accent)'}}/>
                                    </div>
                                    <div style={{flex: 1}}>
                                        <div style={{fontWeight: 700, fontSize: 15}}>{a.name}</div>
                                        <div style={{fontSize: 13, color: 'var(--ink-2)', marginTop: 3}}>
                                            Up to <span className="g-num" style={{
                                            fontWeight: 700,
                                            color: 'var(--ink)'
                                        }}>{G.fmtKES(q.gross, {compact: true})}</span> · 3-month term
                                        </div>
                                    </div>
                                    <Btn kind="accent" small>Request</Btn>
                                </Card>
                            );
                        })}
                    </div>
                }
            </div>
        </div>
    );
}

// ── Advance detail / repayment tracking ───────────────────────
function AdvanceDetailPage({assetId, onBack, onManualPayment}) {
    const G = window.GIGI;
    const a = G.assets.find(x => x.id === assetId);
    const adv = a?.advance;
    if (!adv) return <Empty icon="info" title="No advance found"/>;
    const pct = Math.round(adv.withheld / adv.gross * 100);

    return (
        <div>
            <PageHeader title="Advance details" subtitle={a.name} back onBack={onBack}
                        actions={<Btn kind="ghost" small icon="arrowUp" onClick={onManualPayment}>Manual
                            payment</Btn>}/>

            <Card style={{padding: 0, overflow: 'hidden', marginBottom: 20}}>
                <div style={{background: 'var(--accent-ink)', color: '#fff', padding: 'var(--pad)'}}>
                    <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start'}}>
                        <div>
                            <div
                                style={{color: 'var(--pill-ink)', fontSize: 12, fontWeight: 600, marginBottom: 6}}>Gross
                                advance
                            </div>
                            <div className="g-num" style={{
                                fontSize: 36,
                                fontWeight: 700,
                                letterSpacing: '-.02em'
                            }}>{G.fmtKES(adv.gross)}</div>
                        </div>
                        <Badge tone="accent">Repaying</Badge>
                    </div>
                    <div style={{marginTop: 18}}>
                        <div style={{
                            display: 'flex',
                            justifyContent: 'space-between',
                            fontSize: 12.5,
                            color: 'rgba(255,255,255,.7)',
                            marginBottom: 8
                        }}>
                            <span>{pct}% repaid</span><span>{100 - pct}% remaining</span>
                        </div>
                        <div style={{
                            height: 8,
                            borderRadius: 999,
                            background: 'rgba(255,255,255,.15)',
                            overflow: 'hidden'
                        }}>
                            <div style={{
                                width: pct + '%',
                                height: '100%',
                                background: 'var(--accent)',
                                borderRadius: 999
                            }}/>
                        </div>
                    </div>
                </div>
                <div style={{padding: 'var(--pad)', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 0}}>
                    <div style={{paddingRight: 16, borderRight: '1px solid var(--line-2)'}}>
                        <div style={{
                            fontSize: 11.5,
                            color: 'var(--ink-3)',
                            fontWeight: 600,
                            textTransform: 'uppercase',
                            letterSpacing: '.04em',
                            marginBottom: 6
                        }}>Net disbursed
                        </div>
                        <div className="g-num" style={{fontSize: 20, fontWeight: 700}}>{G.fmtKES(adv.net)}</div>
                        <div style={{fontSize: 12, color: 'var(--ink-3)', marginTop: 3}}>{adv.disbursedOn}</div>
                    </div>
                    <div style={{paddingLeft: 16}}>
                        <div style={{
                            fontSize: 11.5,
                            color: 'var(--ink-3)',
                            fontWeight: 600,
                            textTransform: 'uppercase',
                            letterSpacing: '.04em',
                            marginBottom: 6
                        }}>Outstanding
                        </div>
                        <div className="g-num" style={{fontSize: 20, fontWeight: 700}}>{G.fmtKES(adv.outstanding)}</div>
                        <div style={{
                            fontSize: 12,
                            color: 'var(--ink-3)',
                            marginTop: 3
                        }}>{adv.schedule.filter(s => s.state === 'SCHEDULED').length} payments left
                        </div>
                    </div>
                </div>
            </Card>

            <SectionLabel>Repayment schedule</SectionLabel>
            <Card style={{marginBottom: 20}}>
                {adv.schedule.map((s, i) => (
                    <div key={s.n} style={{
                        display: 'flex', alignItems: 'center', gap: 14, padding: '14px 0',
                        borderBottom: i < adv.schedule.length - 1 ? '1px solid var(--line-2)' : 'none'
                    }}>
                        <div style={{
                            width: 36,
                            height: 36,
                            borderRadius: 999,
                            display: 'grid',
                            placeItems: 'center',
                            flexShrink: 0,
                            background: s.state === 'WITHHELD' ? 'var(--go-bg)' : 'var(--surface-2)',
                            color: s.state === 'WITHHELD' ? 'var(--go)' : 'var(--ink-3)'
                        }}>
                            {s.state === 'WITHHELD' ? <Icon name="check" size={18} stroke={2.5}/> :
                                <span className="g-num" style={{fontSize: 14, fontWeight: 700}}>{s.n}</span>}
                        </div>
                        <div style={{flex: 1}}>
                            <div style={{fontWeight: 700, fontSize: 14}}>Installment {s.n}</div>
                            <div style={{display: 'flex', gap: 10, marginTop: 4, flexWrap: 'wrap'}}>
                                <span className="g-mono" style={{fontSize: 12.5, color: 'var(--ink-3)'}}>{s.due}</span>
                                {s.paidVia && <span
                                    style={{fontSize: 12.5, color: 'var(--go)', fontWeight: 600}}>· {s.paidVia}</span>}
                            </div>
                            {s.paidOn && <div className="g-mono" style={{
                                fontSize: 11.5,
                                color: 'var(--ink-3)',
                                marginTop: 2
                            }}>Paid {s.paidOn}</div>}
                        </div>
                        <div style={{textAlign: 'right'}}>
                            <div className="g-num"
                                 style={{fontSize: 16, fontWeight: 700}}>{G.fmtKES(s.amount, {compact: true})}</div>
                            <Badge tone={s.state === 'WITHHELD' ? 'go' : 'neutral'} style={{marginTop: 4}}>
                                {s.state === 'WITHHELD' ? 'Withheld' : 'Scheduled'}
                            </Badge>
                        </div>
                    </div>
                ))}
            </Card>

            <Card style={{background: 'var(--surface-2)', boxShadow: 'none'}}>
                <Field label="Destination" value={adv.destination} mono/>
                <Field label="Service fee" value={G.fmtKES(adv.fee)} mono last/>
            </Card>
        </div>
    );
}

// ── Request advance wizard ─────────────────────────────────────
function RequestAdvanceWizard({initialAsset, initialMonths, startStep, onClose, onDone}) {
    const G = window.GIGI;
    const eligibles = G.assets.filter(a => a.status === 'ELIGIBLE');
    const [step, setStep] = React.useState(startStep != null ? startStep : (initialAsset ? 1 : 0));
    const [assetId, setAssetId] = React.useState(initialAsset?.id || (eligibles[0]?.id || null));
    const [months, setMonths] = React.useState(initialMonths || 3);
    const [pin, setPin] = React.useState('');
    const [done, setDone] = React.useState(false);

    const asset = G.assets.find(a => a.id === assetId);
    const q = asset ? G.quoteAdvance(asset.verifiedRent, months) : null;

    if (done) {
        return (
            <div style={{textAlign: 'center', padding: '12px 0 8px'}}>
                <div style={{
                    width: 72,
                    height: 72,
                    borderRadius: 20,
                    background: 'var(--accent)',
                    display: 'grid',
                    placeItems: 'center',
                    margin: '0 auto'
                }}>
                    <Icon name="bolt" size={36} style={{color: 'var(--accent-ink)'}}/>
                </div>
                <h2 className="g-num" style={{fontSize: 26, fontWeight: 700, margin: '18px 0 8px'}}>Advance
                    disbursed!</h2>
                <p style={{color: 'var(--ink-2)', fontSize: 14.5, lineHeight: 1.55, margin: '0 0 20px'}}>
                    <span className="g-num"
                          style={{fontWeight: 700, color: 'var(--ink)'}}>{q && G.fmtKES(q.net)}</span> is on its way
                    to {G.organisations[0].disbursement.label}.<br/>Usually arrives in under 15 minutes.
                </p>
                <Btn kind="primary" full onClick={onDone}>Back to advances</Btn>
            </div>
        );
    }

    return (
        <div style={{display: 'flex', flexDirection: 'column', gap: 0}}>
            {/* Progress */}
            <div style={{display: 'flex', height: 3, marginBottom: 18}}>
                {['Select asset', 'Configure', 'Confirm'].map((_, i) => (
                    <div key={i} style={{
                        flex: 1,
                        marginRight: 2,
                        background: i <= step ? 'var(--accent-ink)' : 'var(--line)',
                        borderRadius: 999
                    }}/>
                ))}
            </div>

            {step === 0 && (
                <div style={{display: 'flex', flexDirection: 'column', gap: 10}}>
                    <h3 className="g-num" style={{margin: '0 0 14px', fontSize: 18}}>Select a property</h3>
                    {eligibles.map(a => {
                        const qq = G.quoteAdvance(a.verifiedRent, 3);
                        const on = a.id === assetId;
                        return (
                            <div key={a.id} onClick={() => setAssetId(a.id)} className="g-tap" style={{
                                display: 'flex',
                                alignItems: 'center',
                                gap: 12,
                                padding: '14px 16px',
                                borderRadius: 'var(--r-md)',
                                border: `1.5px solid ${on ? 'var(--accent-ink)' : 'var(--line)'}`,
                                background: on ? 'var(--surface-2)' : 'var(--surface)'
                            }}>
                                <div style={{flex: 1}}>
                                    <div style={{fontWeight: 700, fontSize: 14.5}}>{a.name}</div>
                                    <div className="g-mono"
                                         style={{fontSize: 12.5, color: 'var(--ink-3)', marginTop: 3}}>
                                        Up to {G.fmtKES(qq.gross, {compact: true})} available
                                    </div>
                                </div>
                                {on && <Icon name="check" size={18} stroke={2.5} style={{color: 'var(--go)'}}/>}
                            </div>
                        );
                    })}
                    <Btn kind="primary" full onClick={() => setStep(1)} disabled={!assetId}
                         style={{marginTop: 8}}>Continue</Btn>
                </div>
            )}

            {step === 1 && asset && q && (
                <div style={{display: 'flex', flexDirection: 'column', gap: 14}}>
                    <div style={{
                        background: 'var(--accent-ink)',
                        color: '#fff',
                        borderRadius: 'var(--r-lg)',
                        padding: '20px',
                        textAlign: 'center',
                        marginBottom: 4
                    }}>
                        <div style={{color: 'var(--pill-ink)', fontSize: 13, fontWeight: 600}}>Net to your account</div>
                        <div className="g-num" style={{
                            fontSize: 38,
                            fontWeight: 700,
                            margin: '8px 0',
                            letterSpacing: '-.02em'
                        }}>{G.fmtKES(q.net)}</div>
                        <div style={{fontSize: 12.5, color: 'rgba(255,255,255,.65)'}}>{asset.name} · {months}-month term
                            · fee {G.fmtKES(q.fee)}</div>
                    </div>
                    <div>
                        <div style={{fontSize: 12.5, fontWeight: 600, color: 'var(--ink-2)', marginBottom: 10}}>Term
                        </div>
                        <div style={{display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10}}>
                            {[3, 6, 9, 12].map(mo => {
                                const on = months === mo;
                                return (
                                    <div key={mo} onClick={() => setMonths(mo)}
                                         className="g-tap" style={{
                                        padding: '16px',
                                        borderRadius: 'var(--r-md)',
                                        textAlign: 'center',
                                        border: `1.5px solid ${on ? 'var(--accent-ink)' : 'var(--line)'}`,
                                        boxShadow: on ? 'var(--shadow)' : 'none'
                                    }}>
                                        <div className="g-num" style={{fontSize: 26, fontWeight: 700}}>{mo}</div>
                                        <div style={{fontSize: 12.5, color: 'var(--ink-3)'}}>months</div>
                                    </div>
                                );
                            })}
                        </div>
                    </div>
                    <Card>
                        <Field label="Gross advance" value={G.fmtKES(q.gross)} mono/>
                        <Field label={`Fee (1.8%/mo × ${months}mo)`} value={'– ' + G.fmtKES(q.fee)} mono/>
                        <div style={{
                            display: 'flex',
                            justifyContent: 'space-between',
                            padding: '12px 0 2px',
                            borderTop: '2px solid var(--ink)',
                            marginTop: 6
                        }}>
                            <span style={{fontWeight: 700, fontSize: 15}}>Net disbursed</span>
                            <span className="g-num" style={{fontWeight: 700, fontSize: 18}}>{G.fmtKES(q.net)}</span>
                        </div>
                    </Card>
                    <div style={{display: 'flex', gap: 10}}>
                        <Btn kind="line" onClick={() => setStep(0)} style={{width: 46, flexShrink: 0}}><Icon
                            name="chevL" size={17}/></Btn>
                        <Btn kind="accent" icon="bolt" full onClick={() => setStep(2)}>Confirm advance</Btn>
                    </div>
                </div>
            )}

            {step === 2 && q && (
                <div style={{textAlign: 'center'}}>
                    <div style={{
                        width: 52,
                        height: 52,
                        borderRadius: 14,
                        background: 'var(--surface-2)',
                        display: 'grid',
                        placeItems: 'center',
                        margin: '0 auto',
                        color: 'var(--ink-2)'
                    }}>
                        <Icon name="lock" size={24}/>
                    </div>
                    <h3 className="g-num" style={{fontSize: 20, fontWeight: 700, margin: '14px 0 6px'}}>Enter your
                        PIN</h3>
                    <p style={{color: 'var(--ink-3)', fontSize: 13.5, margin: '0 0 22px'}}>4-digit transaction PIN to
                        authorise disbursement of {G.fmtKES(q.net)}</p>
                    <div style={{display: 'flex', gap: 10, justifyContent: 'center', marginBottom: 24}}>
                        {[0, 1, 2, 3].map(i => (
                            <div key={i} style={{
                                width: 56,
                                height: 64,
                                borderRadius: 14,
                                border: `1.5px solid ${pin.length > i ? 'var(--accent-ink)' : 'var(--line)'}`,
                                display: 'grid',
                                placeItems: 'center',
                                background: 'var(--surface-2)',
                                fontSize: 24,
                                fontFamily: 'var(--fm)',
                                fontWeight: 700
                            }}>
                                {pin.length > i ? '●' : ''}
                            </div>
                        ))}
                    </div>
                    <div style={{
                        display: 'grid',
                        gridTemplateColumns: 'repeat(3,1fr)',
                        gap: 10,
                        maxWidth: 240,
                        margin: '0 auto 16px'
                    }}>
                        {[1, 2, 3, 4, 5, 6, 7, 8, 9, '', 0, '⌫'].map((k, i) => (
                            <button key={i} onClick={() => {
                                if (k === '⌫') {
                                    setPin(p => p.slice(0, -1));
                                    return;
                                }
                                if (k === '') return;
                                const next = pin + k;
                                setPin(next);
                                if (next.length === 4) setTimeout(() => setDone(true), 400);
                            }} className="g-tap" style={{
                                height: 60,
                                borderRadius: 14,
                                border: 'none',
                                background: k === '' ? 'transparent' : 'var(--surface-2)',
                                fontFamily: 'var(--fd)',
                                fontSize: 20,
                                fontWeight: 700,
                                color: 'var(--ink)',
                                cursor: k === '' ? 'default' : 'pointer'
                            }}>{k}</button>
                        ))}
                    </div>
                    <Btn kind="line" full onClick={() => setStep(1)}>Back</Btn>
                </div>
            )}
        </div>
    );
}

// ── Manual payment sheet ───────────────────────────────────────
function ManualPaymentSheet({asset, onClose, onDone}) {
    const G = window.GIGI;
    const adv = asset?.advance;
    const [amount, setAmount] = React.useState(adv?.schedule?.find(s => s.state === 'SCHEDULED')?.amount?.toString() || '');
    const [method, setMethod] = React.useState('bank');
    const [ref, setRef] = React.useState('');
    const [done, setDone] = React.useState(false);

    if (done) {
        return (
            <div style={{textAlign: 'center', padding: '12px 0 4px'}}>
                <div style={{
                    width: 56,
                    height: 56,
                    borderRadius: 16,
                    background: 'var(--go-bg)',
                    display: 'grid',
                    placeItems: 'center',
                    margin: '0 auto',
                    color: 'var(--go)'
                }}>
                    <Icon name="check" size={28} stroke={2.5}/>
                </div>
                <h3 className="g-num" style={{fontSize: 20, fontWeight: 700, margin: '16px 0 8px'}}>Payment
                    recorded</h3>
                <p style={{
                    color: 'var(--ink-2)',
                    fontSize: 13.5,
                    margin: '0 0 20px',
                    lineHeight: 1.5
                }}>KES {Number(amount).toLocaleString()} logged. The schedule will update after reconciliation.</p>
                <Btn kind="primary" full onClick={onDone}>Done</Btn>
            </div>
        );
    }

    return (
        <div style={{display: 'flex', flexDirection: 'column', gap: 14}}>
            <Card style={{background: 'var(--surface-2)', boxShadow: 'none'}}>
                <Field label="Property" value={asset?.name || '—'}/>
                <Field label="Outstanding" value={adv ? G.fmtKES(adv.outstanding) : '—'} mono last/>
            </Card>
            <Input label="Payment amount (KES)" placeholder="564000" value={amount} onChange={setAmount} mono
                   prefix="KES" required/>
            <Select label="Payment method" value={method} onChange={setMethod}
                    options={[{value: 'bank', label: 'Bank Transfer'}, {value: 'mpesa', label: 'M-Pesa'}]}/>
            <Input label="Payment reference" placeholder="TXN ref or cheque number" value={ref} onChange={setRef} mono/>
            <div style={{display: 'flex', gap: 9, color: 'var(--ink-3)', fontSize: 12.5, lineHeight: 1.5}}>
                <Icon name="info" size={15} style={{flexShrink: 0, marginTop: 2}}/>
                Manual payments are reconciled within 24 hours. Automatic withholding continues at the next rent
                collection cycle.
            </div>
            <Btn kind="accent" icon="check" full onClick={() => setDone(true)} disabled={!amount || !ref}>Record
                payment</Btn>
            <Btn kind="line" full onClick={onClose}>Cancel</Btn>
        </div>
    );
}

Object.assign(window, {AdvancesPage, AdvanceDetailPage, RequestAdvanceWizard, ManualPaymentSheet});
