/* gigi-app.jsx — responsive web shell: sidebar + mobile nav + router */

const {useState, useEffect, useCallback, useRef} = React;

// ── Sidebar nav item ───────────────────────────────────────────
function NavItem({icon, label, active, onClick, badge, narrow}) {
    return (
        <button onClick={onClick} className="g-tap" style={{
            display: 'flex', alignItems: 'center', gap: 12, width: '100%', border: 'none',
            background: active ? 'var(--surface-2)' : 'transparent', borderRadius: 10,
            padding: narrow ? '10px 0' : '10px 12px', cursor: 'pointer',
            color: active ? 'var(--ink)' : 'var(--ink-2)',
            justifyContent: narrow ? 'center' : 'flex-start',
            transition: 'background .15s, color .15s', position: 'relative',
        }}>
            <div style={{position: 'relative', flexShrink: 0}}>
                <Icon name={icon} size={20} stroke={active ? 2.2 : 1.7}/>
                {badge > 0 && (
                    <div style={{
                        position: 'absolute',
                        top: -4,
                        right: -4,
                        width: 14,
                        height: 14,
                        borderRadius: 999,
                        background: 'var(--warn)',
                        color: '#fff',
                        fontSize: 9,
                        fontWeight: 700,
                        display: 'grid',
                        placeItems: 'center'
                    }}>{badge}</div>
                )}
            </div>
            {!narrow && <span style={{fontSize: 14, fontWeight: active ? 700 : 500}}>{label}</span>}
            {active && !narrow && <div style={{
                marginLeft: 'auto',
                width: 6,
                height: 6,
                borderRadius: 999,
                background: 'var(--accent)',
                flexShrink: 0
            }}/>}
        </button>
    );
}

// ── Sidebar ────────────────────────────────────────────────────
function Sidebar({tab, onChange, org, orgs, onSwitchOrg, narrow, onToggleNarrow}) {
    const isSov = true; // always show all nav for now
    const navItems = [
        {id: 'dashboard', icon: 'home', label: 'Dashboard'},
        {id: 'properties', icon: 'building', label: 'Properties'},
        {id: 'tenants', icon: 'users', label: 'Tenants'},
        {id: 'advances', icon: 'bolt', label: 'Advances'},
        {id: 'reconcile', icon: 'sync', label: 'Reconcile'},
        {id: 'settings', icon: 'settings', label: 'Settings'},
    ];

    return (
        <aside className={`g-sidebar${narrow ? ' narrow' : ''}`}>
            {/* Logo */}
            <div style={{
                padding: narrow ? '20px 0' : '20px 16px', display: 'flex', alignItems: 'center',
                gap: 10, justifyContent: narrow ? 'center' : 'space-between', flexShrink: 0
            }}>
                {!narrow && (
                    <div style={{display: 'flex', alignItems: 'center', gap: 9}}>
                        <div style={{
                            width: 30,
                            height: 30,
                            borderRadius: 9,
                            background: 'var(--accent-ink)',
                            color: 'var(--pill-ink)',
                            display: 'grid',
                            placeItems: 'center'
                        }}>
                            <Icon name="vault" size={17}/>
                        </div>
                        <span className="g-num" style={{fontWeight: 700, fontSize: 17}}>Gigi</span>
                    </div>
                )}
                {narrow && (
                    <div style={{
                        width: 30,
                        height: 30,
                        borderRadius: 9,
                        background: 'var(--accent-ink)',
                        color: 'var(--pill-ink)',
                        display: 'grid',
                        placeItems: 'center'
                    }}>
                        <Icon name="vault" size={17}/>
                    </div>
                )}
                {!narrow && (
                    <button onClick={onToggleNarrow} className="g-tap" style={{
                        border: 'none',
                        background: 'transparent',
                        color: 'var(--ink-3)',
                        cursor: 'pointer',
                        padding: 4
                    }}>
                        <Icon name="menu" size={18}/>
                    </button>
                )}
            </div>

            {/* Org switcher */}
            <div style={{padding: narrow ? '0 8px 12px' : '0 12px 12px', flexShrink: 0}}>
                <div onClick={onSwitchOrg} className="g-tap" style={{
                    display: 'flex', alignItems: 'center', gap: 9, padding: narrow ? '8px' : '8px 10px',
                    borderRadius: 10, background: 'var(--surface-2)', justifyContent: narrow ? 'center' : 'flex-start',
                    border: '1px solid var(--line)'
                }}>
                    <div style={{
                        width: 28,
                        height: 28,
                        borderRadius: 8,
                        background: 'var(--accent-ink)',
                        color: 'var(--pill-ink)',
                        display: 'grid',
                        placeItems: 'center',
                        fontFamily: 'var(--fd)',
                        fontSize: 12,
                        fontWeight: 700,
                        flexShrink: 0
                    }}>{org.initials}</div>
                    {!narrow && (
                        <>
                            <div style={{flex: 1, minWidth: 0}}>
                                <div style={{
                                    fontSize: 12.5,
                                    fontWeight: 700,
                                    whiteSpace: 'nowrap',
                                    overflow: 'hidden',
                                    textOverflow: 'ellipsis'
                                }}>{org.name}</div>
                                <div style={{fontSize: 11, color: 'var(--ink-3)'}}>{org.type}</div>
                            </div>
                            <Icon name="switch" size={15} style={{color: 'var(--ink-3)', flexShrink: 0}}/>
                        </>
                    )}
                </div>
            </div>

            {/* Nav */}
            <div style={{
                flex: 1,
                padding: narrow ? '0 8px' : '0 12px',
                display: 'flex',
                flexDirection: 'column',
                gap: 2,
                overflowY: 'auto'
            }}>
                {navItems.map(item => (
                    <NavItem key={item.id} {...item} active={tab === item.id} onClick={() => onChange(item.id)}
                             narrow={narrow}/>
                ))}
            </div>

            {/* Collapse toggle when narrow */}
            {narrow && (
                <div style={{padding: '12px 8px', flexShrink: 0}}>
                    <button onClick={onToggleNarrow} className="g-tap" style={{
                        width: '100%',
                        border: 'none',
                        background: 'var(--surface-2)',
                        borderRadius: 10,
                        padding: '10px 0',
                        cursor: 'pointer',
                        color: 'var(--ink-3)',
                        display: 'grid',
                        placeItems: 'center'
                    }}>
                        <Icon name="chevR" size={18}/>
                    </button>
                </div>
            )}

            {/* Bottom: user */}
            <div
                style={{padding: narrow ? '12px 8px' : '12px 16px', borderTop: '1px solid var(--line)', flexShrink: 0}}>
                <div style={{
                    display: 'flex',
                    alignItems: 'center',
                    gap: 10,
                    justifyContent: narrow ? 'center' : 'flex-start'
                }}>
                    <div style={{
                        width: 32,
                        height: 32,
                        borderRadius: 999,
                        background: 'var(--accent-ink)',
                        color: 'var(--pill-ink)',
                        display: 'grid',
                        placeItems: 'center',
                        fontFamily: 'var(--fd)',
                        fontSize: 12,
                        fontWeight: 700,
                        flexShrink: 0
                    }}>JM
                    </div>
                    {!narrow && (
                        <div style={{flex: 1, minWidth: 0}}>
                            <div style={{fontSize: 13, fontWeight: 700}}>James Meco</div>
                            <div style={{fontSize: 11.5, color: 'var(--ink-3)'}}>Sovereign</div>
                        </div>
                    )}
                </div>
            </div>
        </aside>
    );
}

// ── Mobile top bar ─────────────────────────────────────────────
function MobileTopBar({title, canBack, onBack, onMenu, org}) {
    return (
        <div className="g-topbar">
            {canBack
                ? <button onClick={onBack} className="g-tap" style={{
                    width: 36,
                    height: 36,
                    borderRadius: 10,
                    border: 'none',
                    background: 'var(--surface-2)',
                    display: 'grid',
                    placeItems: 'center',
                    color: 'var(--ink)',
                    cursor: 'pointer'
                }}>
                    <Icon name="chevL" size={18}/>
                </button>
                : <div style={{display: 'flex', alignItems: 'center', gap: 8}}>
                    <div style={{
                        width: 28,
                        height: 28,
                        borderRadius: 8,
                        background: 'var(--accent-ink)',
                        color: 'var(--pill-ink)',
                        display: 'grid',
                        placeItems: 'center'
                    }}><Icon name="vault" size={15}/></div>
                    <span className="g-num" style={{fontWeight: 700, fontSize: 16}}>Gigi</span>
                </div>
            }
            <div style={{flex: 1, textAlign: canBack ? 'left' : 'center'}}>
                {canBack && title && <span style={{fontWeight: 700, fontSize: 16}}>{title}</span>}
            </div>
            <div style={{display: 'flex', gap: 8}}>
                <div style={{
                    width: 34,
                    height: 34,
                    borderRadius: 999,
                    background: 'var(--surface-2)',
                    display: 'grid',
                    placeItems: 'center',
                    color: 'var(--ink-2)'
                }}>
                    <Icon name="bell" size={18}/>
                </div>
                <div style={{
                    width: 34,
                    height: 34,
                    borderRadius: 999,
                    background: 'var(--accent-ink)',
                    display: 'grid',
                    placeItems: 'center',
                    color: 'var(--pill-ink)',
                    fontFamily: 'var(--fd)',
                    fontSize: 12,
                    fontWeight: 700
                }}>JM
                </div>
            </div>
        </div>
    );
}

// ── Mobile bottom nav ──────────────────────────────────────────
function MobileNav({tab, onChange}) {
    const items = [
        {id: 'dashboard', icon: 'home', label: 'Home'},
        {id: 'properties', icon: 'building', label: 'Assets'},
        {id: 'advances', icon: 'bolt', label: 'Capital'},
        {id: 'tenants', icon: 'users', label: 'Tenants'},
        {id: 'settings', icon: 'settings', label: 'Settings'},
    ];
    return (
        <nav className="g-mobile-nav" style={{justifyContent: 'space-around'}}>
            {items.map(item => {
                const on = tab === item.id;
                return (
                    <button key={item.id} onClick={() => onChange(item.id)} className="g-tap" style={{
                        flex: 1, border: 'none', background: 'none', display: 'flex', flexDirection: 'column',
                        alignItems: 'center', gap: 3, padding: '8px 0 2px', cursor: 'pointer',
                        color: on ? 'var(--ink)' : 'var(--ink-3)', position: 'relative'
                    }}>
                        {on && <div style={{
                            position: 'absolute',
                            top: 0,
                            width: 24,
                            height: 3,
                            borderRadius: '0 0 4px 4px',
                            background: 'var(--accent)'
                        }}/>}
                        <Icon name={item.icon} size={22} stroke={on ? 2.2 : 1.7}/>
                        <span style={{fontSize: 10.5, fontWeight: on ? 700 : 500}}>{item.label}</span>
                    </button>
                );
            })}
        </nav>
    );
}

// ── Dashboard overview ─────────────────────────────────────────
function DashboardPage({
                           org,
                           onNavigate,
                           onOpenProperty,
                           onOpenAdvance,
                           onStartOnboarding,
                           onAddProperty,
                           onAddTenant
                       }) {
    const G = window.GIGI;
    const activeAdv = G.assets.filter(a => a.org === org.id && a.status === 'ADVANCE_ACTIVE' && a.advance);
    const eligibles = G.assets.filter(a => a.org === org.id && a.status === 'ELIGIBLE');
    const pendingKyc = G.allTenants().filter(t => t.kycStatus === 'PENDING' || t.kycStatus === 'MANUAL_REVIEW').length;

    return (
        <div>
            <PageHeader title={`Good morning, James`} subtitle={org.name}/>

            <FlowLauncher
                onStartOnboarding={onStartOnboarding}
                onAddProperty={onAddProperty}
                onAddTenant={onAddTenant}
            />

            <div className="g-3col" style={{marginBottom: 28}}>
                <KpiCard label="Portfolio value" value={G.fmtKES(G.kpis.portfolioValue, {compact: true})}
                         icon="building" sub={`${G.assets.filter(a => a.org === org.id).length} properties`}/>
                <KpiCard label="Monthly rent roll" value={G.fmtKES(G.kpis.monthlyRentRoll, {compact: true})} icon="sync"
                         sub={`${G.kpis.occupiedUnits}/${G.kpis.totalUnits} units occupied`}/>
                <KpiCard label="Lendable equity" value={G.fmtKES(G.kpis.lendableEquity, {compact: true})} icon="bolt"
                         dark sub={`${eligibles.length} eligible assets`}/>
            </div>

            {/* Active advances */}
            {activeAdv.length > 0 && (
                <div style={{marginBottom: 24}}>
                    <SectionLabel action={<span onClick={() => onNavigate('advances')} className="g-tap" style={{
                        fontSize: 12.5,
                        fontWeight: 700,
                        color: 'var(--go)',
                        cursor: 'pointer'
                    }}>View all →</span>}>Active repayments</SectionLabel>
                    {activeAdv.map(a => {
                        const adv = a.advance, pct = Math.round(adv.withheld / adv.gross * 100);
                        return (
                            <Card key={a.id} onClick={() => onOpenAdvance(a.id)} style={{marginBottom: 10}}>
                                <div style={{
                                    display: 'flex',
                                    justifyContent: 'space-between',
                                    alignItems: 'center',
                                    marginBottom: 12
                                }}>
                                    <div>
                                        <div style={{fontWeight: 700, fontSize: 15}}>{a.name}</div>
                                        <div className="g-mono" style={{
                                            fontSize: 12.5,
                                            color: 'var(--ink-3)',
                                            marginTop: 2
                                        }}>{G.fmtKES(adv.gross)} · {adv.months} months
                                        </div>
                                    </div>
                                    <Badge tone="accent">Repaying</Badge>
                                </div>
                                <div style={{
                                    height: 7,
                                    borderRadius: 999,
                                    background: 'var(--surface-2)',
                                    overflow: 'hidden'
                                }}>
                                    <div style={{
                                        width: pct + '%',
                                        height: '100%',
                                        background: 'var(--accent-ink)',
                                        borderRadius: 999
                                    }}/>
                                </div>
                                <div style={{
                                    display: 'flex',
                                    justifyContent: 'space-between',
                                    marginTop: 6,
                                    fontSize: 12.5
                                }}>
                                    <span style={{color: 'var(--ink-3)'}}>{pct}% repaid</span>
                                    <span style={{
                                        color: 'var(--ink-2)',
                                        fontWeight: 600
                                    }}>{G.fmtKES(adv.outstanding, {compact: true})} remaining</span>
                                </div>
                            </Card>
                        );
                    })}
                </div>
            )}

            {/* Quick actions */}
            <div style={{marginBottom: 24}}>
                <SectionLabel>Quick actions</SectionLabel>
                <div className="g-2col">
                    {eligibles.length > 0 && (
                        <Card onClick={() => onNavigate('advances')}
                              style={{display: 'flex', alignItems: 'center', gap: 12, cursor: 'pointer'}}>
                            <div style={{
                                width: 42,
                                height: 42,
                                borderRadius: 12,
                                background: 'var(--accent-ink)',
                                display: 'grid',
                                placeItems: 'center',
                                flexShrink: 0,
                                color: 'var(--accent)'
                            }}>
                                <Icon name="bolt" size={22}/>
                            </div>
                            <div>
                                <div style={{fontWeight: 700, fontSize: 14}}>Request advance</div>
                                <div style={{
                                    fontSize: 12,
                                    color: 'var(--ink-3)',
                                    marginTop: 2
                                }}>{eligibles.length} eligible
                                </div>
                            </div>
                        </Card>
                    )}
                    {pendingKyc > 0 && (
                        <Card onClick={() => onNavigate('tenants')}
                              style={{display: 'flex', alignItems: 'center', gap: 12, cursor: 'pointer'}}>
                            <div style={{
                                width: 42,
                                height: 42,
                                borderRadius: 12,
                                background: 'var(--warn-bg)',
                                display: 'grid',
                                placeItems: 'center',
                                flexShrink: 0,
                                color: 'var(--warn)'
                            }}>
                                <Icon name="users" size={22}/>
                            </div>
                            <div>
                                <div style={{fontWeight: 700, fontSize: 14}}>KYC pending</div>
                                <div style={{
                                    fontSize: 12,
                                    color: 'var(--ink-3)',
                                    marginTop: 2
                                }}>{pendingKyc} tenant{pendingKyc > 1 ? 's' : ''}</div>
                            </div>
                        </Card>
                    )}
                    <Card onClick={() => onNavigate('reconcile')}
                          style={{display: 'flex', alignItems: 'center', gap: 12, cursor: 'pointer'}}>
                        <div style={{
                            width: 42,
                            height: 42,
                            borderRadius: 12,
                            background: 'var(--info-bg)',
                            display: 'grid',
                            placeItems: 'center',
                            flexShrink: 0,
                            color: 'var(--info)'
                        }}>
                            <Icon name="sync" size={22}/>
                        </div>
                        <div>
                            <div style={{fontWeight: 700, fontSize: 14}}>Reconcile rent</div>
                            <div style={{fontSize: 12, color: 'var(--ink-3)', marginTop: 2}}>Upload bank statement</div>
                        </div>
                    </Card>
                    <Card onClick={() => onNavigate('properties')}
                          style={{display: 'flex', alignItems: 'center', gap: 12, cursor: 'pointer'}}>
                        <div style={{
                            width: 42,
                            height: 42,
                            borderRadius: 12,
                            background: 'var(--go-bg)',
                            display: 'grid',
                            placeItems: 'center',
                            flexShrink: 0,
                            color: 'var(--go)'
                        }}>
                            <Icon name="building" size={22}/>
                        </div>
                        <div>
                            <div style={{fontWeight: 700, fontSize: 14}}>View portfolio</div>
                            <div style={{
                                fontSize: 12,
                                color: 'var(--ink-3)',
                                marginTop: 2
                            }}>{G.assets.filter(a => a.org === org.id).length} properties
                            </div>
                        </div>
                    </Card>
                </div>
            </div>

            {/* Recent properties */}
            <div>
                <SectionLabel action={<span onClick={() => onNavigate('properties')} className="g-tap" style={{
                    fontSize: 12.5,
                    fontWeight: 700,
                    color: 'var(--go)',
                    cursor: 'pointer'
                }}>All →</span>}>Properties</SectionLabel>
                <div className="g-card-grid">
                    {G.assets.filter(a => a.org === org.id).slice(0, 3).map(a => (
                        <PropertyCard key={a.id} a={a} onClick={() => onOpenProperty(a.id)}/>
                    ))}
                </div>
            </div>
        </div>
    );
}

// ── Org switcher sheet ─────────────────────────────────────────
function OrgSwitcherSheet({open, current, orgs, onClose, onChange, onAddOrg}) {
    return (
        <Sheet open={open} onClose={onClose} title="Switch organisation">
            <div style={{display: 'flex', flexDirection: 'column', gap: 10}}>
                {orgs.map(o => {
                    const on = o.id === current;
                    return (
                        <div key={o.id} onClick={() => {
                            onChange(o.id);
                            onClose();
                        }} 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={{
                                width: 38,
                                height: 38,
                                borderRadius: 10,
                                background: 'var(--accent-ink)',
                                color: 'var(--pill-ink)',
                                display: 'grid',
                                placeItems: 'center',
                                fontFamily: 'var(--fd)',
                                fontWeight: 700
                            }}>{o.initials}</div>
                            <div style={{flex: 1}}>
                                <div style={{fontWeight: 700, fontSize: 14.5}}>{o.name}</div>
                                <div style={{
                                    fontSize: 12,
                                    color: 'var(--ink-3)'
                                }}>{o.type} · {o.kycStatus === 'APPROVED' ? 'KYC approved' : 'KYC pending'}</div>
                            </div>
                            {on && <Icon name="check" size={18} stroke={2.5} style={{color: 'var(--go)'}}/>}
                        </div>
                    );
                })}
                <div onClick={onAddOrg} className="g-tap" style={{
                    display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px',
                    borderRadius: 'var(--r-md)', border: '1.5px dashed var(--line)', cursor: 'pointer'
                }}>
                    <div style={{
                        width: 38,
                        height: 38,
                        borderRadius: 10,
                        background: 'var(--accent-ink)',
                        display: 'grid',
                        placeItems: 'center',
                        color: 'var(--pill-ink)'
                    }}>
                        <Icon name="plus" size={20}/>
                    </div>
                    <div style={{flex: 1}}>
                        <div style={{fontWeight: 700, fontSize: 14, color: 'var(--ink)'}}>Add organisation</div>
                        <div style={{fontSize: 12, color: 'var(--ink-3)', marginTop: 1}}>Onboard a new entity &amp; its
                            properties
                        </div>
                    </div>
                    <Icon name="chevR" size={16} style={{color: 'var(--ink-3)'}}/>
                </div>
            </div>
        </Sheet>
    );
}

// ── Main App ───────────────────────────────────────────────────
function GigiApp({tweaks}) {
    const G = window.GIGI;
    const {
        role = 'SOVEREIGN',
        density = 'normal',
        screen: forcedScreen = 'dashboard',
        onbStep = '1',
        theme = 'light'
    } = tweaks || {};

    const [tab, setTab] = useState('dashboard');
    const [orgId, setOrgId] = useState(G.organisations[0].id);
    const [narrow, setNarrow] = useState(false);
    const [stack, setStack] = useState([]);
    const [orgSheet, setOrgSheet] = useState(false);
    const [advSheet, setAdvSheet] = useState(null);
    const [tenantSheet, setTenantSheet] = useState(false);
    const [manualPaySheet, setManualPaySheet] = useState(null);
    const pageRef = useRef(null);

    useEffect(() => {
        pageRef.current?.scrollTo(0, 0);
    }, [tab, stack]);

    const org = G.organisations.find(o => o.id === orgId);
    const top = stack[stack.length - 1];
    const push = frame => setStack(s => [...s, frame]);
    const pop = () => setStack(s => s.slice(0, -1));

    // forced screen from tweaks
    useEffect(() => {
        const map = {
            dashboard: 'dashboard',
            properties: 'properties',
            tenants: 'tenants',
            advances: 'advances',
            reconcile: 'reconcile',
            settings: 'settings',
            onboarding: 'onboarding'
        };
        if (map[forcedScreen]) {
            setTab(map[forcedScreen]);
            setStack([]);
        }
    }, [forcedScreen]);

    const openProperty = id => push({kind: 'property', assetId: id});
    const openTenant = id => push({kind: 'tenant', tenantId: id});
    const openAdvance = id => push({kind: 'advance', assetId: id});
    const openReconcile = id => push({kind: 'reconcile', assetId: id});

    // Build screen content
    let screenContent;
    if (top?.kind === 'property') {
        screenContent = <PropertyDetail assetId={top.assetId} role={role} onBack={pop}
                                        onOpenTenant={openTenant} onReconcile={openReconcile}
                                        onRequestAdvance={a => setAdvSheet({asset: a})}/>;
    } else if (top?.kind === 'tenant') {
        screenContent = <TenantDetailPage tenantId={top.tenantId} onBack={pop} onReconcile={openReconcile}/>;
    } else if (top?.kind === 'advance') {
        screenContent = <AdvanceDetailPage assetId={top.assetId} onBack={pop}
                                           onManualPayment={() => setManualPaySheet(G.assets.find(a => a.id === top.assetId))}/>;
    } else if (top?.kind === 'reconcile') {
        screenContent = <Reconciliation assetId={top.assetId} onBack={pop}/>;
    } else {
        const navigate = (t) => {
            setTab(t);
            setStack([]);
        };
        if (tab === 'dashboard') screenContent =
            <DashboardPage org={org} onNavigate={navigate} onOpenProperty={openProperty} onOpenAdvance={openAdvance}
                           onStartOnboarding={() => {
                               setTab('onboarding');
                               setStack([]);
                           }}
                           onAddProperty={() => {
                               setTab('add-property');
                               setStack([]);
                           }}
                           onAddTenant={() => setTenantSheet(true)}/>;
        else if (tab === 'add-property') return (
            <div className={`g-root g-shell${density === 'compact' ? ' gigi-compact' : ''}`}>
                <Sidebar tab="" onChange={t => {
                    setTab(t);
                    setStack([]);
                }} org={org} orgs={G.organisations}
                         onSwitchOrg={() => setOrgSheet(true)} narrow={narrow}
                         onToggleNarrow={() => setNarrow(n => !n)}/>
                <div className="g-main">
                    <div className="g-page" style={{padding: 0}}>
                        <AddPropertyWizard onBack={() => setTab('properties')} onDone={() => {
                            setTab('properties');
                            setStack([]);
                        }}/>
                    </div>
                </div>
            </div>
        );
        else if (tab === 'properties') screenContent =
            <PropertiesPage role={role} org={org} onOpenProperty={openProperty} onAddProperty={() => {
                setTab('add-property');
                setStack([]);
            }}/>;
        else if (tab === 'tenants') screenContent =
            <TenantsPage role={role} org={org} onOpenTenant={openTenant} onAddTenant={() => setTenantSheet(true)}/>;
        else if (tab === 'advances') screenContent =
            <AdvancesPage role={role} org={org} onRequestAdvance={(a, months) => setAdvSheet({asset: a, months})}
                          onOpenAdvance={openAdvance}/>;
        else if (tab === 'reconcile') screenContent = <Reconciliation assetId="as_riverside" onBack={() => {
        }}/>;
        else if (tab === 'settings') screenContent = <SettingsScreen role={role} org={org}/>;
        else if (tab === 'onboarding') {
            return (
                <div className={`g-root${density === 'compact' ? ' gigi-compact' : ''}`}
                     style={{height: '100%', background: 'var(--sand)'}}>
                    <Onboarding forcedStep={Number(onbStep) - 1} onFinish={() => setTab('dashboard')}/>
                </div>
            );
        }
    }

    const canBack = stack.length > 0;
    const pageTitle = top?.kind === 'property' ? G.assets.find(a => a.id === top?.assetId)?.name
        : top?.kind === 'tenant' ? G.tenants[top?.tenantId]?.name
            : top?.kind === 'advance' ? 'Advance details'
                : top?.kind === 'reconcile' ? 'Reconciliation' : '';

    return (
        <div className={`g-root g-shell${density === 'compact' ? ' gigi-compact' : ''}`}>
            <Sidebar tab={top ? '' : tab} onChange={t => {
                setTab(t);
                setStack([]);
            }} org={org} orgs={G.organisations}
                     onSwitchOrg={() => setOrgSheet(true)} narrow={narrow} onToggleNarrow={() => setNarrow(n => !n)}/>

            <div className="g-main">
                <MobileTopBar title={pageTitle} canBack={canBack} onBack={pop} org={org}/>
                <div className="g-page" ref={pageRef}>
                    <div key={top?.assetId || top?.tenantId || top?.kind || tab}>
                        {screenContent}
                    </div>
                </div>
                <MobileNav tab={tab} onChange={t => {
                    setTab(t);
                    setStack([]);
                }}/>
            </div>

            <OrgSwitcherSheet open={orgSheet} current={orgId} orgs={G.organisations} onClose={() => setOrgSheet(false)}
                              onChange={setOrgId}
                              onAddOrg={() => {
                                  setOrgSheet(false);
                                  setStack([]);
                                  setTab('onboarding');
                              }}/>

            <Sheet open={!!advSheet} onClose={() => setAdvSheet(null)} title="Request advance" width={520}>
                {advSheet && <RequestAdvanceWizard initialAsset={advSheet.asset} initialMonths={advSheet.months}
                                                   startStep={advSheet.months != null ? 2 : undefined}
                                                   onClose={() => setAdvSheet(null)} onDone={() => {
                    setAdvSheet(null);
                    setTab('advances');
                    setStack([]);
                }}/>}
            </Sheet>

            <Sheet open={tenantSheet} onClose={() => setTenantSheet(false)} title="Add tenant" width={520}>
                {tenantSheet &&
                    <AddTenantWizard onClose={() => setTenantSheet(false)} onDone={() => setTenantSheet(false)}/>}
            </Sheet>

            <Sheet open={!!manualPaySheet} onClose={() => setManualPaySheet(null)} title="Manual payment">
                {manualPaySheet && <ManualPaymentSheet asset={manualPaySheet} onClose={() => setManualPaySheet(null)}
                                                       onDone={() => setManualPaySheet(null)}/>}
            </Sheet>
        </div>
    );
}

Object.assign(window, {GigiApp});
