/* gigi-properties.jsx — property list + type-aware detail views */

// ── Property type badge ────────────────────────────────────────
function PropTypeBadge({propType}) {
    const G = window.GIGI, pt = G.PROP_TYPES[propType];
    if (!pt) return null;
    return (
        <span style={{
            display: 'inline-flex', alignItems: 'center', gap: 5,
            fontSize: 11.5, fontWeight: 600, color: 'var(--ink-2)', background: 'var(--surface-2)',
            padding: '3px 9px', borderRadius: 999
        }}>
      <Icon name={pt.icon} size={12}/>{pt.label}
    </span>
    );
}

// ── Property card (grid item) ──────────────────────────────────
function PropertyCard({a, onClick}) {
    const G = window.GIGI;
    const m = G.statusMeta[a.status];
    const pt = G.PROP_TYPES[a.propType];
    const occ = G.occupancy(a);
    const occupiedCount = a.units.filter(u => u.occupied).length;
    return (
        <Card onClick={onClick}
              style={{display: 'flex', flexDirection: 'column', gap: 0, padding: 0, overflow: 'hidden'}}>
            {/* colour header */}
            <div style={{height: 6, background: pt?.accent || 'var(--line)'}}/>
            <div style={{padding: 'var(--pad)'}}>
                <div style={{
                    display: 'flex',
                    align: 'flex-start',
                    justifyContent: 'space-between',
                    gap: 8,
                    marginBottom: 12
                }}>
                    <div style={{display: 'flex', alignItems: 'center', gap: 10}}>
                        <div style={{
                            width: 40,
                            height: 40,
                            borderRadius: 11,
                            background: 'var(--surface-2)',
                            display: 'grid',
                            placeItems: 'center',
                            flexShrink: 0,
                            color: 'var(--ink-2)'
                        }}>
                            <Icon name={pt?.icon || 'building'} size={21}/>
                        </div>
                        <div>
                            <div style={{fontWeight: 700, fontSize: 15, lineHeight: 1.2}}>{a.name}</div>
                            <div style={{fontSize: 12, color: 'var(--ink-3)', marginTop: 2}}>{a.city}</div>
                        </div>
                    </div>
                    <Badge tone={m.tone} dot>{m.label}</Badge>
                </div>

                <div style={{
                    display: 'grid',
                    gridTemplateColumns: '1fr 1fr',
                    gap: 8,
                    borderTop: '1px solid var(--line-2)',
                    paddingTop: 12
                }}>
                    <div>
                        <div style={{
                            fontSize: 11,
                            fontWeight: 700,
                            color: 'var(--ink-3)',
                            textTransform: 'uppercase',
                            letterSpacing: '.04em'
                        }}>{pt?.multi ? 'Units' : 'Type'}</div>
                        <div className="g-num" style={{fontSize: 18, fontWeight: 700, marginTop: 3}}>
                            {pt?.multi ? `${occupiedCount}/${a.units.length}` : pt?.label?.split(' ')[0]}
                        </div>
                        <div style={{
                            fontSize: 11.5,
                            color: 'var(--ink-3)'
                        }}>{pt?.multi ? `${occ}% occupied` : a.address.split(',')[0]}</div>
                    </div>
                    {a.status !== 'PENDING_VERIFICATION' && a.verifiedRent > 0 ? (
                        <div>
                            <div style={{
                                fontSize: 11,
                                fontWeight: 700,
                                color: 'var(--ink-3)',
                                textTransform: 'uppercase',
                                letterSpacing: '.04em'
                            }}>Verified rent
                            </div>
                            <div className="g-num" style={{
                                fontSize: 15,
                                fontWeight: 700,
                                marginTop: 3
                            }}>{G.fmtKES(a.verifiedRent, {compact: true})}</div>
                            <div style={{fontSize: 11.5, color: 'var(--ink-3)'}}>/ month</div>
                        </div>
                    ) : (
                        <div>
                            <div style={{
                                fontSize: 11,
                                fontWeight: 700,
                                color: 'var(--ink-3)',
                                textTransform: 'uppercase',
                                letterSpacing: '.04em'
                            }}>Status
                            </div>
                            <div style={{fontSize: 13, fontWeight: 600, marginTop: 3, color: 'var(--ink-2)'}}>
                                {a.status === 'PENDING_VERIFICATION' ? 'Under review' : 'Not eligible'}
                            </div>
                        </div>
                    )}
                </div>
            </div>
        </Card>
    );
}

// ── Properties list page ───────────────────────────────────────
function PropertiesPage({role, org, onOpenProperty, onAddProperty}) {
    const G = window.GIGI;
    const [filter, setFilter] = React.useState('all');
    const isSov = role === 'SOVEREIGN';
    const assets = G.assets.filter(a => a.org === org.id);

    const filtered = assets.filter(a =>
        filter === 'all' ? true :
            filter === 'eligible' ? (a.status === 'ELIGIBLE' || a.status === 'ADVANCE_ACTIVE') :
                filter === 'pending' ? (a.status === 'PENDING_VERIFICATION' || a.status === 'VERIFYING') :
                    a.status === 'INELIGIBLE'
    );

    const eligibleCount = assets.filter(a => a.status === 'ELIGIBLE' || a.status === 'ADVANCE_ACTIVE').length;

    return (
        <div>
            <PageHeader title="Properties" subtitle={org.name}
                        actions={isSov && <Btn kind="primary" icon="plus" onClick={onAddProperty}>Add property</Btn>}/>

            {isSov && (
                <div className="g-3col" style={{marginBottom: 28}}>
                    <KpiCard label="Total properties" value={assets.length} icon="building"
                             sub={`${eligibleCount} eligible for advance`}/>
                    <KpiCard label="Monthly rent roll" value={G.fmtKES(G.kpis.monthlyRentRoll, {compact: true})}
                             icon="bank" sub="Across active leases"/>
                    <KpiCard label="Lendable equity" value={G.fmtKES(G.kpis.lendableEquity, {compact: true})}
                             icon="bolt" dark sub="60% of verified rent × 3 mo"/>
                </div>
            )}

            <div style={{marginBottom: 16}}>
                <SegTabs scroll active={filter} onChange={setFilter} tabs={[
                    {id: 'all', label: `All (${assets.length})`},
                    {id: 'eligible', label: 'Eligible'},
                    {id: 'pending', label: 'Pending'},
                    {id: 'ineligible', label: 'Ineligible'},
                ]}/>
            </div>

            {filtered.length === 0
                ? <Empty icon="building" title="No properties here"
                         body="Add your first property to get started."
                         action={isSov && <Btn kind="primary" icon="plus" onClick={onAddProperty}>Add property</Btn>}/>
                : <div className="g-card-grid">
                    {filtered.map(a => <PropertyCard key={a.id} a={a} onClick={() => onOpenProperty(a.id)}/>)}
                </div>
            }
        </div>
    );
}

// ── Unit grid (apartment block / office) ───────────────────────
function UnitGrid({a, onOpenTenant}) {
    const G = window.GIGI;
    const floors = [...new Set(a.units.map(u => u.floor))].sort((x, y) => x - y);
    return (
        <div style={{display: 'flex', flexDirection: 'column', gap: 14}}>
            {floors.map(fl => (
                <div key={fl}>
                    <SectionLabel>Floor {fl === 0 ? 'G (Ground)' : fl}</SectionLabel>
                    <div style={{display: 'grid', gridTemplateColumns: 'repeat(auto-fill,minmax(180px,1fr))', gap: 10}}>
                        {a.units.filter(u => u.floor === fl).map(u => {
                            const tenant = G.tenantForUnit(u.tenantId);
                            const km = tenant ? G.kycMeta[tenant.kycStatus] : null;
                            return (
                                <div key={u.id} onClick={() => tenant && onOpenTenant(tenant.id, a.id)}
                                     className={tenant ? 'g-tap' : ''}
                                     style={{
                                         borderRadius: 'var(--r-md)',
                                         border: '1.5px solid var(--line)',
                                         background: 'var(--surface)',
                                         padding: '14px',
                                         cursor: tenant ? 'pointer' : 'default'
                                     }}>
                                    <div style={{
                                        display: 'flex',
                                        justifyContent: 'space-between',
                                        alignItems: 'center'
                                    }}>
                                        <span className="g-mono" style={{fontSize: 14, fontWeight: 700}}>{u.id}</span>
                                        {u.occupied
                                            ? <span style={{
                                                width: 8,
                                                height: 8,
                                                borderRadius: 999,
                                                background: 'var(--go)'
                                            }}/>
                                            : <span style={{
                                                width: 8,
                                                height: 8,
                                                borderRadius: 999,
                                                background: 'var(--line)',
                                                border: '1px solid var(--sand-2)'
                                            }}/>}
                                    </div>
                                    <div style={{fontSize: 12.5, color: 'var(--ink-3)', marginTop: 4}}>{u.type}</div>
                                    <div className="g-num" style={{fontSize: 14, fontWeight: 700, marginTop: 8}}>
                                        {G.fmtKES(u.rent, {compact: true})}
                                        <span
                                            style={{fontSize: 11.5, fontWeight: 500, color: 'var(--ink-3)'}}>/mo</span>
                                    </div>
                                    {tenant
                                        ? <div style={{
                                            marginTop: 8,
                                            display: 'flex',
                                            justifyContent: 'space-between',
                                            alignItems: 'center'
                                        }}>
                                            <span style={{
                                                fontSize: 12,
                                                fontWeight: 600,
                                                whiteSpace: 'nowrap',
                                                overflow: 'hidden',
                                                textOverflow: 'ellipsis',
                                                maxWidth: 100
                                            }}>{tenant.name.split(' ')[0]}</span>
                                            <Badge tone={km.tone} style={{fontSize: 10}}>{km.label}</Badge>
                                        </div>
                                        : <Btn kind="ghost" small full style={{marginTop: 10}}
                                               onClick={e => {
                                                   e.stopPropagation(); /* add tenant flow */
                                               }}>+ Tenant</Btn>
                                    }
                                </div>
                            );
                        })}
                    </div>
                </div>
            ))}
        </div>
    );
}

// ── Single unit / mansion / mansionette view ───────────────────
function SingleDwellingView({a, onOpenTenant}) {
    const G = window.GIGI;
    const u = a.units[0];
    const t = u ? G.tenantForUnit(u.tenantId) : null;
    const km = t ? G.kycMeta[t.kycStatus] : null;

    if (!t) {
        return (
            <Card style={{textAlign: 'center', padding: '36px 24px'}}>
                <div style={{
                    width: 56,
                    height: 56,
                    borderRadius: 16,
                    background: 'var(--surface-2)',
                    display: 'grid',
                    placeItems: 'center',
                    margin: '0 auto',
                    color: 'var(--ink-3)'
                }}>
                    <Icon name="user" size={26}/>
                </div>
                <div style={{fontWeight: 700, fontSize: 15, marginTop: 14}}>No active tenant</div>
                <div style={{fontSize: 13.5, color: 'var(--ink-2)', marginTop: 8, lineHeight: 1.5}}>
                    Add a tenant with a signed lease to make this property eligible for rent advances.
                </div>
                <div style={{marginTop: 18}}><Btn kind="primary" icon="plus">Add tenant</Btn></div>
            </Card>
        );
    }

    return (
        <Card onClick={() => onOpenTenant(t.id, a.id)} style={{display: 'flex', alignItems: 'center', gap: 16}}>
            <div style={{
                width: 48,
                height: 48,
                borderRadius: 13,
                background: 'var(--surface-2)',
                display: 'grid',
                placeItems: 'center',
                fontSize: 16,
                fontWeight: 700,
                color: 'var(--ink-2)',
                flexShrink: 0
            }}>
                {t.name.split(' ').map(w => w[0]).slice(0, 2).join('')}
            </div>
            <div style={{flex: 1, minWidth: 0}}>
                <div style={{fontWeight: 700, fontSize: 15}}>{t.name}</div>
                <div className="g-mono" style={{fontSize: 12.5, color: 'var(--ink-3)', marginTop: 2}}>
                    {G.fmtKES(u.rent)}/mo · Due day {t.leases[0]?.payDay || '—'}
                </div>
                <div style={{marginTop: 8, display: 'flex', gap: 8}}>
                    <Badge tone={km.tone} dot>{km.label}</Badge>
                    {t.onTime > 0 && <Badge tone="neutral">{t.onTime}% on-time</Badge>}
                </div>
            </div>
            <Icon name="chevR" size={18} style={{color: 'var(--ink-3)', flexShrink: 0}}/>
        </Card>
    );
}

// ── Documents tab ──────────────────────────────────────────────
function PropertyDocsTab({a}) {
    const stateMeta = {
        verified: {t: 'go', l: 'Verified'},
        uploaded: {t: 'info', l: 'Uploaded'},
        missing: {t: 'warn', l: 'Required'}
    };
    return (
        <div style={{display: 'flex', flexDirection: 'column', gap: 10}}>
            {a.docs.map(d => {
                const s = stateMeta[d.state];
                return (
                    <Card key={d.name} style={{display: 'flex', alignItems: 'center', gap: 12}}>
                        <div style={{
                            width: 40,
                            height: 40,
                            borderRadius: 10,
                            background: 'var(--surface-2)',
                            display: 'grid',
                            placeItems: 'center',
                            color: 'var(--ink-2)',
                            flexShrink: 0
                        }}>
                            <Icon name="doc" size={20}/>
                        </div>
                        <span style={{flex: 1, fontWeight: 600, fontSize: 14}}>{d.name}</span>
                        {d.state === 'missing'
                            ? <Btn kind="ghost" small icon="upload">Upload</Btn>
                            : <Badge tone={s.t} dot>{s.l}</Badge>}
                    </Card>
                );
            })}
            <Card style={{background: 'var(--surface-2)', boxShadow: 'none', padding: '12px 14px'}}>
                <div style={{display: 'flex', gap: 8, color: 'var(--ink-3)', fontSize: 12.5, lineHeight: 1.5}}>
                    <Icon name="ardhi" size={15} style={{flexShrink: 0, marginTop: 2}}/>
                    <div>
                        <b style={{color: 'var(--ink)'}}>Ardhi Sasa</b> · {a.ardhi.note}
                        <div className="g-mono" style={{fontSize: 11, marginTop: 2}}>{a.ardhi.date}</div>
                    </div>
                </div>
            </Card>
        </div>
    );
}

// ── Ownership tab ──────────────────────────────────────────────
function OwnershipTab({a}) {
    return (
        <div style={{display: 'flex', flexDirection: 'column', gap: 12}}>
            <Card>
                {a.owners.map((o, i) => (
                    <div key={o.name} style={{
                        display: 'flex', alignItems: 'center', gap: 12, padding: '12px 0',
                        borderBottom: i < a.owners.length - 1 ? '1px solid var(--line-2)' : 'none'
                    }}>
                        <div style={{
                            width: 36,
                            height: 36,
                            borderRadius: 999,
                            background: o.you ? 'var(--accent-ink)' : 'var(--surface-2)',
                            color: o.you ? '#fff' : 'var(--ink-2)',
                            display: 'grid',
                            placeItems: 'center',
                            fontSize: 12,
                            fontWeight: 700
                        }}>
                            {o.name.split(' ').map(w => w[0]).slice(0, 2).join('')}
                        </div>
                        <div style={{flex: 1}}>
                            <div style={{fontWeight: 700, fontSize: 14}}>{o.name}{o.you &&
                                <span style={{color: 'var(--ink-3)', fontWeight: 500}}> · you</span>}</div>
                        </div>
                        <div style={{textAlign: 'right'}}>
                            <div className="g-num" style={{fontSize: 18, fontWeight: 700}}>{o.stake}%</div>
                            <div style={{fontSize: 11, color: 'var(--ink-3)', marginTop: 1}}>stake</div>
                        </div>
                    </div>
                ))}
                <div style={{
                    paddingTop: 14,
                    marginTop: 4,
                    borderTop: '1.5px solid var(--line)',
                    display: 'flex',
                    justifyContent: 'space-between'
                }}>
                    <span style={{fontSize: 13, color: 'var(--ink-2)'}}>Total</span>
                    <span className="g-num" style={{fontWeight: 700, color: 'var(--go)'}}>100%</span>
                </div>
            </Card>
            {a.owners.length > 1 && (
                <Card style={{background: 'var(--info-bg)', boxShadow: 'none', padding: '12px 14px'}}>
                    <div style={{display: 'flex', gap: 9, color: 'var(--info)', fontSize: 13, lineHeight: 1.5}}>
                        <Icon name="info" size={16} style={{flexShrink: 0, marginTop: 2}}/>
                        This property has multiple co-owners. Advances require majority consent (&gt;50% stake approval)
                        before disbursement.
                    </div>
                </Card>
            )}
        </div>
    );
}

// ── Property detail (type-aware) ───────────────────────────────
function PropertyDetail({assetId, role, onBack, onOpenTenant, onReconcile, onRequestAdvance}) {
    const G = window.GIGI;
    const a = G.assets.find(x => x.id === assetId);
    const pt = G.PROP_TYPES[a.propType];
    const m = G.statusMeta[a.status];
    const occ = G.occupancy(a);
    const isSov = role === 'SOVEREIGN';
    const isMulti = pt?.multi;

    const tabs = [
        {id: 'units', label: isMulti ? 'Units' : 'Tenant'},
        {id: 'overview', label: 'Overview'},
        {id: 'docs', label: 'Documents'},
        {id: 'owners', label: 'Ownership'},
        ...(isSov ? [{id: 'capital', label: 'Capital'}] : []),
    ];
    const [tab, setTab] = React.useState(tabs[0].id);

    return (
        <div>
            <PageHeader title={a.name} subtitle={`${pt?.label} · ${a.city}`} back onBack={onBack}
                        actions={
                            <div style={{display: 'flex', gap: 8}}>
                                {isSov && (a.status === 'ELIGIBLE' || a.status === 'ADVANCE_ACTIVE') && (
                                    <Btn kind="accent" icon="bolt" small
                                         onClick={() => onRequestAdvance(a)}>Advance</Btn>
                                )}
                                <Btn kind="ghost" icon="sync" small onClick={() => onReconcile(a.id)}>Reconcile</Btn>
                            </div>
                        }/>

            {/* Status strip */}
            <div style={{display: 'flex', gap: 10, flexWrap: 'wrap', marginBottom: 20}}>
                <Badge tone={m.tone} dot>{m.label}</Badge>
                <Badge tone="neutral"><Icon name={pt?.icon || 'building'} size={12}
                                            style={{marginRight: 4}}/>{pt?.label}</Badge>
                {isMulti && <Badge tone={occ >= 85 ? 'go' : 'warn'}>{occ}% occupied
                    · {a.units.filter(u => u.occupied).length}/{a.units.length} units</Badge>}
                <span className="g-mono" style={{fontSize: 12, color: 'var(--ink-3)'}}>{a.lr}</span>
            </div>

            {/* KPI row */}
            {isSov && a.verifiedRent > 0 && (
                <div className="g-3col" style={{marginBottom: 20}}>
                    <Card>
                        <div style={{
                            fontSize: 11.5,
                            color: 'var(--ink-3)',
                            fontWeight: 600,
                            textTransform: 'uppercase',
                            letterSpacing: '.04em',
                            marginBottom: 8
                        }}>Verified rent
                        </div>
                        <div className="g-num"
                             style={{fontSize: 24, fontWeight: 700}}>{G.fmtKES(a.verifiedRent, {compact: true})}/mo
                        </div>
                    </Card>
                    <Card>
                        <div style={{
                            fontSize: 11.5,
                            color: 'var(--ink-3)',
                            fontWeight: 600,
                            textTransform: 'uppercase',
                            letterSpacing: '.04em',
                            marginBottom: 8
                        }}>Lendable equity
                        </div>
                        <div className="g-num" style={{
                            fontSize: 24,
                            fontWeight: 700
                        }}>{G.fmtKES(a.verifiedRent * 3 * 0.6, {compact: true})}</div>
                        <div style={{fontSize: 11.5, color: 'var(--ink-3)', marginTop: 4}}>60% × 3 months</div>
                    </Card>
                    <Card>
                        <div style={{
                            fontSize: 11.5,
                            color: 'var(--ink-3)',
                            fontWeight: 600,
                            textTransform: 'uppercase',
                            letterSpacing: '.04em',
                            marginBottom: 8
                        }}>Portfolio value
                        </div>
                        <div className="g-num"
                             style={{fontSize: 24, fontWeight: 700}}>{G.fmtKES(a.value, {compact: true})}</div>
                    </Card>
                </div>
            )}

            <div style={{marginBottom: 18}}>
                <SegTabs scroll tabs={tabs} active={tab} onChange={setTab}/>
            </div>

            <div className="g-enter" key={tab}>
                {tab === 'units' && (
                    isMulti
                        ? <UnitGrid a={a} onOpenTenant={(tenantId) => onOpenTenant(tenantId, a.id)}/>
                        : <SingleDwellingView a={a} onOpenTenant={(tenantId) => onOpenTenant(tenantId, a.id)}/>
                )}
                {tab === 'overview' && (
                    <Card>
                        <Field label="Address" value={a.address}/>
                        <Field label="LR Number" value={a.lr} mono/>
                        <Field label="Property type" value={pt?.label}/>
                        {isMulti && <Field label="Total units" value={a.units.length}/>}
                        {isMulti &&
                            <Field label="Occupied" value={`${a.units.filter(u => u.occupied).length} · ${occ}%`}/>}
                        {isSov && a.verifiedRent > 0 &&
                            <Field label="Verified monthly rent" value={G.fmtKES(a.verifiedRent)} mono/>}
                        <Field label="Portfolio value" value={a.value ? G.fmtKES(a.value, {compact: true}) : 'Pending'}
                               mono last/>
                    </Card>
                )}
                {tab === 'docs' && <PropertyDocsTab a={a}/>}
                {tab === 'owners' && <OwnershipTab a={a}/>}
                {tab === 'capital' && isSov && <PropertyCapitalTab a={a} onRequestAdvance={onRequestAdvance}/>}
            </div>
        </div>
    );
}

// ── Capital tab (inline, Sovereign only) ──────────────────────
function PropertyCapitalTab({a, onRequestAdvance}) {
    const G = window.GIGI;
    if (a.status === 'ADVANCE_ACTIVE' && a.advance) {
        const adv = a.advance;
        const pct = Math.round(adv.withheld / adv.gross * 100);
        return (
            <div style={{display: 'flex', flexDirection: 'column', gap: 16}}>
                <Card 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: 6
                                }}>Active advance
                                </div>
                                <div className="g-num"
                                     style={{fontSize: 32, fontWeight: 700}}>{G.fmtKES(adv.gross)}</div>
                            </div>
                            <Badge tone="accent">Repaying</Badge>
                        </div>
                        <div style={{
                            height: 7,
                            borderRadius: 999,
                            background: 'rgba(255,255,255,.18)',
                            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,.7)'
                        }}>
                            <span>{G.fmtKES(adv.withheld, {compact: true})} repaid</span>
                            <span>{G.fmtKES(adv.outstanding, {compact: true})} remaining</span>
                        </div>
                    </div>
                    <div style={{padding: 'var(--pad)'}}>
                        <Field label="Disbursed on" value={adv.disbursedOn}/>
                        <Field label="Destination" value={adv.destination} mono/>
                        <Field label="Service fee" value={G.fmtKES(adv.fee)} mono last/>
                    </div>
                </Card>
                <div>
                    <SectionLabel>Repayment schedule</SectionLabel>
                    <Card>
                        {adv.schedule.map((s, i) => (
                            <div key={s.n} style={{
                                display: 'flex',
                                alignItems: 'center',
                                gap: 12,
                                padding: '12px 0',
                                borderBottom: i < adv.schedule.length - 1 ? '1px solid var(--line-2)' : 'none'
                            }}>
                                <div style={{
                                    width: 30,
                                    height: 30,
                                    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={16} stroke={2.5}/> :
                                        <span className="g-num" style={{fontSize: 13, fontWeight: 700}}>{s.n}</span>}
                                </div>
                                <div style={{flex: 1}}>
                                    <div style={{fontSize: 14, fontWeight: 600}}>Installment {s.n}</div>
                                    <div style={{display: 'flex', gap: 8, marginTop: 3}}>
                                        <span className="g-mono"
                                              style={{fontSize: 12, color: 'var(--ink-3)'}}>{s.due}</span>
                                        {s.paidOn && <span style={{
                                            fontSize: 12,
                                            color: 'var(--go)',
                                            fontWeight: 600
                                        }}>· {s.paidVia}</span>}
                                    </div>
                                </div>
                                <div className="g-num"
                                     style={{fontSize: 15, fontWeight: 700}}>{G.fmtKES(s.amount, {compact: true})}</div>
                            </div>
                        ))}
                    </Card>
                </div>
            </div>
        );
    }
    if (a.status === 'ELIGIBLE') {
        const q = G.quoteAdvance(a.verifiedRent, 3);
        return (
            <div style={{display: 'flex', flexDirection: 'column', gap: 16}}>
                <Card
                    style={{background: 'var(--accent-ink)', color: '#fff', textAlign: 'center', padding: '28px 24px'}}>
                    <div style={{color: 'var(--pill-ink)', fontSize: 13, fontWeight: 600}}>Available advance (3
                        months)
                    </div>
                    <div className="g-num" style={{
                        fontSize: 42,
                        fontWeight: 700,
                        margin: '10px 0',
                        letterSpacing: '-.02em'
                    }}>{G.fmtKES(q.gross)}</div>
                    <div style={{fontSize: 12.5, color: 'rgba(255,255,255,.65)'}}>60% of {G.fmtKES(a.verifiedRent)}/mo ·
                        fee {G.fmtKES(q.fee)}</div>
                    <div style={{marginTop: 18}}><Btn kind="accent" icon="bolt" onClick={() => onRequestAdvance(a)}>Request
                        advance</Btn></div>
                </Card>
                <div style={{
                    display: 'flex',
                    gap: 8,
                    color: 'var(--go)',
                    fontSize: 13,
                    fontWeight: 600,
                    justifyContent: 'center'
                }}>
                    <Icon name="bolt" size={16}/>Disbursed within 15 minutes of approval
                </div>
            </div>
        );
    }
    return <Empty icon="lock" title="Capital not available"
                  body="This property must be Eligible — verified ownership, active tenancy, and ≥85% occupancy."/>;
}

Object.assign(window, {PropertiesPage, PropertyDetail, PropertyCard});
