/* gigi-operations.jsx — rent reconciliation (v2 — uses g-* classes) */

function TxnRow({x, onMatch}) {
    const G = window.GIGI;
    const done = x.status === 'RECONCILED';
    return (
        <div style={{
            display: 'flex',
            alignItems: 'center',
            gap: 12,
            padding: '13px 0',
            borderBottom: '1px solid var(--line-2)'
        }}>
            <div style={{
                width: 8,
                height: 8,
                borderRadius: 999,
                flexShrink: 0,
                background: done ? 'var(--go)' : 'var(--warn)'
            }}/>
            <div style={{flex: 1, minWidth: 0}}>
                <div style={{
                    fontSize: 14,
                    fontWeight: 600,
                    whiteSpace: 'nowrap',
                    overflow: 'hidden',
                    textOverflow: 'ellipsis'
                }}>{x.narrative}</div>
                <div className="g-mono"
                     style={{fontSize: 11.5, color: 'var(--ink-3)', marginTop: 2}}>{x.ref} · {x.date}</div>
                {done &&
                    <div style={{fontSize: 12, color: 'var(--go)', marginTop: 3, fontWeight: 600}}>→ {x.match}</div>}
            </div>
            <div style={{textAlign: 'right', flexShrink: 0}}>
                <div className="g-num" style={{fontSize: 14, fontWeight: 700}}>
                    {x.amount >= 1000 ? (x.amount / 1000).toFixed(x.amount % 1000 ? 1 : 0) + 'K' : x.amount}
                </div>
                {!done && (
                    <button onClick={() => onMatch(x)} className="g-tap" style={{
                        marginTop: 4, border: 'none',
                        background: 'var(--warn-bg)', color: 'var(--warn)', fontSize: 11.5, fontWeight: 700,
                        padding: '4px 10px', borderRadius: 999, cursor: 'pointer'
                    }}>Match</button>
                )}
            </div>
        </div>
    );
}

function Reconciliation({assetId, onBack}) {
    const G = window.GIGI;
    const a = G.assets.find(x => x.id === assetId) || G.assets[0];
    const data = G.reconciliation[assetId] || G.reconciliation.as_riverside;
    const [matchOpen, setMatchOpen] = React.useState(null);
    const [resolved, setResolved] = React.useState({});

    const txns = data.txns;
    const pending = txns.filter(x => x.status === 'PENDING_REVIEW' && !resolved[x.id]);
    const reconciledCount = txns.length - pending.length;

    return (
        <div>
            <PageHeader title="Reconcile rent" subtitle={a.name}
                        back={!!onBack} onBack={onBack}/>

            {/* upload */}
            <div style={{
                border: '1.5px dashed var(--line)', borderRadius: 'var(--r-lg)', padding: '24px',
                textAlign: 'center', background: 'var(--surface)', marginBottom: 20
            }}>
                <div style={{
                    width: 48, height: 48, borderRadius: 14, background: 'var(--surface-2)', display: 'grid',
                    placeItems: 'center', margin: '0 auto', color: 'var(--ink-2)'
                }}><Icon name="upload" size={22}/></div>
                <div style={{fontWeight: 700, fontSize: 15, marginTop: 12}}>Upload bank statement</div>
                <div style={{fontSize: 13, color: 'var(--ink-3)', marginTop: 4}}>CSV or PDF · NCBA, Equity, KCB,
                    Standard Chartered
                </div>
                <div style={{marginTop: 16}}><Btn kind="ghost" icon="upload">Choose file</Btn></div>
            </div>

            {/* summary */}
            <Card style={{display: 'flex', alignItems: 'center', gap: 14, marginBottom: 16}}>
                <div style={{
                    width: 44,
                    height: 44,
                    borderRadius: 11,
                    background: 'var(--surface-2)',
                    display: 'grid',
                    placeItems: 'center',
                    color: 'var(--ink-2)',
                    flexShrink: 0
                }}>
                    <Icon name="doc" size={22}/>
                </div>
                <div style={{flex: 1, minWidth: 0}}>
                    <div className="g-mono" style={{
                        fontSize: 13,
                        fontWeight: 600,
                        whiteSpace: 'nowrap',
                        overflow: 'hidden',
                        textOverflow: 'ellipsis'
                    }}>{data.statement}</div>
                    <div style={{
                        fontSize: 12.5,
                        color: 'var(--ink-3)',
                        marginTop: 2
                    }}>{reconciledCount}/{txns.length} matched · AI auto-reconciliation
                    </div>
                </div>
                <div className="g-num" style={{fontSize: 24, fontWeight: 700, color: 'var(--go)', flexShrink: 0}}>
                    {Math.round(reconciledCount / txns.length * 100)}%
                </div>
            </Card>

            {pending.length > 0 && (
                <Card style={{
                    background: 'var(--warn-bg)',
                    boxShadow: 'none',
                    display: 'flex',
                    alignItems: 'center',
                    gap: 10,
                    marginBottom: 14
                }}>
                    <Icon name="info" size={18} style={{color: 'var(--warn)', flexShrink: 0}}/>
                    <span style={{fontSize: 13, color: 'var(--warn)', fontWeight: 600}}>
            {pending.length} transaction{pending.length > 1 ? 's' : ''} need manual review
          </span>
                </Card>
            )}

            <SectionLabel>Transactions</SectionLabel>
            <Card>
                {txns.map(x => (
                    <TxnRow key={x.id}
                            x={resolved[x.id] ? {...x, status: 'RECONCILED', match: resolved[x.id]} : x}
                            onMatch={setMatchOpen}/>
                ))}
                <div style={{height: 4}}/>
            </Card>

            <div style={{
                display: 'flex',
                gap: 8,
                color: 'var(--ink-3)',
                fontSize: 12.5,
                padding: '14px 4px 0',
                lineHeight: 1.5
            }}>
                <Icon name="info" size={15} style={{flexShrink: 0, marginTop: 2}}/>
                {a.status === 'ADVANCE_ACTIVE'
                    ? 'This asset has an active advance — the installment is withheld at source before net rent is remitted.'
                    : 'Only reconciled transactions count toward verified rent and tenant performance.'}
            </div>

            {/* Match sheet */}
            <Sheet open={!!matchOpen} onClose={() => setMatchOpen(null)} title="Match transaction">
                {matchOpen && (
                    <div>
                        <Card style={{background: 'var(--surface-2)', boxShadow: 'none', marginBottom: 16}}>
                            <Field label="Narrative" value={matchOpen.narrative}/>
                            <Field label="Amount" value={G.fmtKES(matchOpen.amount)} mono/>
                            <Field label="Reference" value={matchOpen.ref} mono last/>
                        </Card>
                        <SectionLabel>Assign to tenant</SectionLabel>
                        <div style={{display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 16}}>
                            {G.allTenants().filter(t => t.kycStatus === 'APPROVED').slice(0, 4).map(t => (
                                <div key={t.id} onClick={() => {
                                    setResolved(r => ({...r, [matchOpen.id]: `${t.name}`}));
                                    setMatchOpen(null);
                                }}
                                     className="g-tap" style={{
                                    display: 'flex', alignItems: 'center', gap: 12, padding: '12px 14px',
                                    borderRadius: 'var(--r-md)', border: '1.5px solid var(--line)', cursor: 'pointer'
                                }}>
                                    <div style={{
                                        width: 34,
                                        height: 34,
                                        borderRadius: 999,
                                        background: 'var(--surface-2)',
                                        display: 'grid',
                                        placeItems: 'center',
                                        fontSize: 12,
                                        fontWeight: 700,
                                        color: 'var(--ink-2)'
                                    }}>
                                        {t.name.split(' ').map(w => w[0]).slice(0, 2).join('')}
                                    </div>
                                    <div style={{flex: 1}}>
                                        <div style={{fontWeight: 600, fontSize: 14}}>{t.name}</div>
                                        <div className="g-mono" style={{fontSize: 12, color: 'var(--ink-3)'}}>
                                            {t.leases[0] ? G.fmtKES(t.leases[0].rent) + '/mo' : 'No lease'}
                                        </div>
                                    </div>
                                    <Icon name="chevR" size={16} style={{color: 'var(--ink-3)'}}/>
                                </div>
                            ))}
                        </div>
                        <Btn kind="line" full onClick={() => {
                            setResolved(r => ({...r, [matchOpen.id]: 'Dismissed — not rent'}));
                            setMatchOpen(null);
                        }}>
                            Dismiss · not rental income
                        </Btn>
                    </div>
                )}
            </Sheet>
        </div>
    );
}

Object.assign(window, {Reconciliation});
