/* gigi-tenants.jsx — tenant list, detail, and onboarding wizard */

// ── Tenant card ────────────────────────────────────────────────
function TenantCard({t, onClick}) {
    const G = window.GIGI;
    const km = G.kycMeta[t.kycStatus];
    const lease = t.leases[0];
    const asset = lease ? G.assets.find(a => a.id === lease.assetId) : null;
    return (
        <Card onClick={onClick} style={{display: 'flex', alignItems: 'center', gap: 14}}>
            <div style={{
                width: 44,
                height: 44,
                borderRadius: 13,
                background: 'var(--surface-2)',
                display: 'grid',
                placeItems: 'center',
                fontSize: 14,
                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 style={{fontSize: 12.5, color: 'var(--ink-3)', marginTop: 2}}>
                    {asset ? `${asset.name} · ${lease.unitId}` : 'No active lease'}
                </div>
                <div style={{display: 'flex', gap: 8, marginTop: 8, flexWrap: 'wrap'}}>
                    <Badge tone={km.tone} dot>{km.label}</Badge>
                    {lease && <Badge tone="neutral">{G.fmtKES(lease.rent, {compact: true})}/mo</Badge>}
                    {t.onTime > 0 && <Badge tone={t.onTime >= 90 ? 'go' : 'warn'}>{t.onTime}% on-time</Badge>}
                </div>
            </div>
            <Icon name="chevR" size={18} style={{color: 'var(--ink-3)', flexShrink: 0}}/>
        </Card>
    );
}

// ── Tenants list page ──────────────────────────────────────────
function TenantsPage({role, org, onOpenTenant, onAddTenant}) {
    const G = window.GIGI;
    const [search, setSearch] = React.useState('');
    const [kycFilter, setKycFilter] = React.useState('all');
    const allT = G.allTenants();

    const filtered = allT.filter(t => {
        const matchSearch = !search || t.name.toLowerCase().includes(search.toLowerCase()) || t.phone.includes(search);
        const matchKyc = kycFilter === 'all' || t.kycStatus === kycFilter;
        return matchSearch && matchKyc;
    });

    const approvedCount = allT.filter(t => t.kycStatus === 'APPROVED').length;
    const pendingCount = allT.filter(t => t.kycStatus === 'PENDING' || t.kycStatus === 'MANUAL_REVIEW').length;

    return (
        <div>
            <PageHeader title="Tenants" subtitle={org.name}
                        actions={<Btn kind="primary" icon="plus" onClick={onAddTenant}>Add tenant</Btn>}/>

            <div className="g-2col" style={{marginBottom: 24}}>
                <KpiCard label="Active tenants" value={allT.length} icon="users" sub={`${approvedCount} KYC approved`}/>
                <KpiCard label="Pending KYC" value={pendingCount} icon="clock" sub="Awaiting review" tone="warn"/>
            </div>

            <div style={{display: 'flex', gap: 12, marginBottom: 16, flexWrap: 'wrap'}}>
                <div style={{flex: 1, minWidth: 200, position: 'relative'}}>
                    <div style={{
                        position: 'absolute',
                        left: 12,
                        top: '50%',
                        transform: 'translateY(-50%)',
                        color: 'var(--ink-3)',
                        pointerEvents: 'none'
                    }}>
                        <Icon name="search" size={17}/>
                    </div>
                    <input value={search} onChange={e => setSearch(e.target.value)}
                           placeholder="Search by name or phone…"
                           style={{
                               width: '100%',
                               height: 44,
                               borderRadius: 'var(--r-sm)',
                               border: '1.5px solid var(--line)',
                               background: 'var(--surface)',
                               paddingLeft: 40,
                               paddingRight: 14,
                               fontFamily: 'var(--ff)',
                               fontSize: 14,
                               color: 'var(--ink)',
                               outline: 'none'
                           }}/>
                </div>
                <SegTabs active={kycFilter} onChange={setKycFilter} tabs={[
                    {id: 'all', label: 'All'},
                    {id: 'APPROVED', label: 'Approved'},
                    {id: 'PENDING', label: 'Pending'},
                    {id: 'MANUAL_REVIEW', label: 'Review'},
                ]}/>
            </div>

            {filtered.length === 0
                ? <Empty icon="users" title="No tenants found"
                         body="Add tenants to your properties to start tracking rent and build eligibility for advances."
                         action={<Btn kind="primary" icon="plus" onClick={onAddTenant}>Add tenant</Btn>}/>
                : <div style={{display: 'flex', flexDirection: 'column', gap: 10}}>
                    {filtered.map(t => <TenantCard key={t.id} t={t} onClick={() => onOpenTenant(t.id)}/>)}
                </div>
            }
        </div>
    );
}

// ── Tenant detail ──────────────────────────────────────────────
function TenantDetailPage({tenantId, onBack, onReconcile}) {
    const G = window.GIGI;
    const t = G.tenants[tenantId];
    const km = G.kycMeta[t.kycStatus];
    const lease = t.leases[0];
    const asset = lease ? G.assets.find(a => a.id === lease.assetId) : null;
    const [tab, setTab] = React.useState('overview');

    const ledger = lease ? [
        {label: `Rent · ${lease.payMethod}`, amount: lease.rent, kind: 'in', date: '02 Jun 2026'},
        {label: `Rent · ${lease.payMethod}`, amount: lease.rent, kind: 'in', date: '03 May 2026'},
        {label: 'Security deposit (held)', amount: lease.deposit, kind: 'held', date: '01 Jan 2024'},
    ] : [];

    return (
        <div>
            <PageHeader title={t.name} subtitle={asset ? `${asset.name} · Unit ${lease?.unitId}` : 'No active lease'}
                        back onBack={onBack}
                        actions={
                            <div style={{display: 'flex', gap: 8}}>
                                <Badge tone={km.tone} dot style={{padding: '8px 14px'}}>{km.label}</Badge>
                            </div>
                        }/>

            <div style={{marginBottom: 18}}>
                <SegTabs tabs={[{id: 'overview', label: 'Overview'}, {id: 'payments', label: 'Payments'}, {
                    id: 'lease',
                    label: 'Lease'
                }, {id: 'docs', label: 'Documents'}]}
                         active={tab} onChange={setTab}/>
            </div>

            <div className="g-enter" key={tab}>
                {tab === 'overview' && (
                    <div style={{display: 'flex', flexDirection: 'column', gap: 16}}>
                        <div className="g-2col">
                            <KpiCard label="Monthly rent" value={lease ? G.fmtKES(lease.rent, {compact: true}) : '—'}
                                     icon="bank"/>
                            <KpiCard label="On-time rate" value={t.onTime ? t.onTime + '%' : '—'} icon="check"
                                     sub="12-month reconciled"/>
                        </div>
                        <Card>
                            <Field label="Full name" value={t.name}/>
                            <Field label="Phone" value={t.phone} mono/>
                            <Field label="Email" value={t.email}/>
                            <Field label="ID type" value={t.idType}/>
                            <Field label="ID number" value={t.idNumber} mono/>
                            <Field label="Employer" value={t.employer || '—'} last/>
                        </Card>
                    </div>
                )}

                {tab === 'payments' && (
                    <div style={{display: 'flex', flexDirection: 'column', gap: 16}}>
                        <Card>
                            <div style={{
                                display: 'flex',
                                justifyContent: 'space-between',
                                alignItems: 'baseline',
                                marginBottom: 16
                            }}>
                                <span className="g-num" style={{fontSize: 32, fontWeight: 700}}>{t.onTime || 0}%</span>
                                <span style={{fontSize: 13, color: 'var(--ink-3)'}}>on-time · 12 months</span>
                            </div>
                            <PerfBars data={t.perf} height={44}/>
                            {t.perf && t.perf.length > 0 && (
                                <div style={{
                                    display: 'flex',
                                    gap: 16,
                                    marginTop: 12,
                                    fontSize: 12,
                                    color: 'var(--ink-3)'
                                }}>
                                    <span style={{display: 'flex', alignItems: 'center', gap: 5}}><span
                                        style={{width: 9, height: 9, borderRadius: 2, background: 'var(--go)'}}/>On time</span>
                                    <span style={{display: 'flex', alignItems: 'center', gap: 5}}><span
                                        style={{width: 9, height: 9, borderRadius: 2, background: 'var(--warn)'}}/>Late</span>
                                    <span style={{display: 'flex', alignItems: 'center', gap: 5}}><span style={{
                                        width: 9,
                                        height: 9,
                                        borderRadius: 2,
                                        background: 'var(--neutral-bg)'
                                    }}/>Missed</span>
                                </div>
                            )}
                        </Card>
                        <SectionLabel>Ledger</SectionLabel>
                        <Card>
                            {ledger.map((l, i) => (
                                <div key={i} style={{
                                    display: 'flex',
                                    justifyContent: 'space-between',
                                    alignItems: 'center',
                                    padding: '12px 0',
                                    borderBottom: i < ledger.length - 1 ? '1px solid var(--line-2)' : 'none'
                                }}>
                                    <div>
                                        <div style={{fontSize: 14, fontWeight: 600}}>{l.label}</div>
                                        <div className="g-mono"
                                             style={{fontSize: 12, color: 'var(--ink-3)', marginTop: 2}}>{l.date}</div>
                                    </div>
                                    <span className="g-mono" style={{
                                        fontWeight: 700, fontSize: 14,
                                        color: l.kind === 'in' ? 'var(--go)' : l.kind === 'out' ? 'var(--warn)' : 'var(--ink-2)'
                                    }}>
                    {l.kind === 'out' ? '−' : l.kind === 'in' ? '+' : '~'} KES {l.amount.toLocaleString()}
                  </span>
                                </div>
                            ))}
                        </Card>
                        {asset && <Btn kind="ghost" icon="sync"
                                       onClick={() => onReconcile(asset.id)}>Reconcile {asset.name}</Btn>}
                    </div>
                )}

                {tab === 'lease' && lease && (
                    <div style={{display: 'flex', flexDirection: 'column', gap: 16}}>
                        <Card>
                            <Field label="Property" value={asset?.name || '—'}/>
                            <Field label="Unit" value={lease.unitId} mono/>
                            <Field label="Monthly rent" value={G.fmtKES(lease.rent)} mono/>
                            <Field label="Security deposit" value={G.fmtKES(lease.deposit)} mono/>
                            <Field label="Lease start" value={lease.start}/>
                            <Field label="Lease end" value={lease.end}/>
                            <Field label="Pay day" value={`${lease.payDay}th of each month`}/>
                            <Field label="Pay method" value={lease.payMethod} last/>
                        </Card>
                        <div style={{display: 'flex', gap: 10}}>
                            <Btn kind="ghost" icon="doc" full>View lease agreement</Btn>
                            <Btn kind="line" icon="x" full>Terminate lease</Btn>
                        </div>
                    </div>
                )}

                {tab === 'docs' && (
                    <div style={{display: 'flex', flexDirection: 'column', gap: 10}}>
                        {['Government ID', 'Signed lease agreement', 'Proof of income'].map((d, i) => (
                            <Card key={d} 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)'
                                }}>
                                    <Icon name="doc" size={20}/>
                                </div>
                                <span style={{flex: 1, fontWeight: 600, fontSize: 14}}>{d}</span>
                                <Badge tone={i < 2 ? 'go' : 'neutral'} dot>{i < 2 ? 'On file' : 'Optional'}</Badge>
                            </Card>
                        ))}
                    </div>
                )}
            </div>
        </div>
    );
}

// ── Add tenant wizard ──────────────────────────────────────────
function AddTenantWizard({onClose, onDone}) {
    const G = window.GIGI;
    const [step, setStep] = React.useState(0);
    const [d, setD] = React.useState({idType: 'national_id', payMethod: 'mpesa'});
    const set = (k, v) => setD(p => ({...p, [k]: v}));
    const [leaseUploaded, setLeaseUploaded] = React.useState(false);
    const [idUploaded, setIdUploaded] = React.useState(false);

    const steps = ['Find or create', 'Tenant KYC', 'Lease details', 'Documents'];
    const titles = ['Add a tenant', 'Tenant KYC', 'Lease details', 'Upload documents'];
    const subs = [
        'Search for an existing Gigi-registered tenant, or create a new one.',
        'These details are verified against government records for AML/KYC compliance.',
        'Enter the lease terms as per the signed agreement.',
        'Upload the signed lease and supporting documents.',
    ];

    return (
        <div style={{display: 'flex', flexDirection: 'column', height: '100%'}}>
            {/* Progress */}
            <div style={{display: 'flex', height: 3, flexShrink: 0}}>
                {steps.map((_, i) => (
                    <div key={i} style={{
                        flex: 1, background: i <= step ? 'var(--accent-ink)' : 'var(--line)',
                        opacity: i < step ? 0.45 : 1, transition: 'background .3s'
                    }}/>
                ))}
            </div>
            <div style={{padding: '20px 0 16px', flexShrink: 0}}>
                <div style={{
                    fontSize: 11.5,
                    color: 'var(--ink-3)',
                    fontWeight: 700,
                    textTransform: 'uppercase',
                    letterSpacing: '.07em',
                    marginBottom: 6
                }}>
                    Step {step + 1} / {steps.length}
                </div>
                <h2 className="g-num" style={{fontSize: 22, fontWeight: 700, margin: 0}}>{titles[step]}</h2>
                <p style={{fontSize: 13.5, color: 'var(--ink-2)', margin: '6px 0 0', lineHeight: 1.55}}>{subs[step]}</p>
            </div>

            <div className="g-scroll" style={{flex: 1, overflowY: 'auto'}}>
                {step === 0 && (
                    <div style={{display: 'flex', flexDirection: 'column', gap: 12}}>
                        <div style={{position: 'relative'}}>
                            <div style={{
                                position: 'absolute',
                                left: 14,
                                top: '50%',
                                transform: 'translateY(-50%)',
                                color: 'var(--ink-3)'
                            }}>
                                <Icon name="search" size={17}/>
                            </div>
                            <input placeholder="Search by name, phone or email…"
                                   style={{
                                       width: '100%',
                                       height: 46,
                                       borderRadius: 'var(--r-sm)',
                                       border: '1.5px solid var(--line)',
                                       background: 'var(--surface)',
                                       paddingLeft: 44,
                                       fontFamily: 'var(--ff)',
                                       fontSize: 14,
                                       color: 'var(--ink)',
                                       outline: 'none'
                                   }}/>
                        </div>
                        <Card style={{background: 'var(--surface-2)', boxShadow: 'none', padding: '12px 14px'}}>
                            <div style={{fontSize: 13, color: 'var(--ink-2)'}}>No matches found — a new tenant profile
                                will be created.
                            </div>
                        </Card>
                        <div style={{display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10}}>
                            <Select label="Assign to property" value={d.assetId || ''} onChange={v => set('assetId', v)}
                                    options={[{
                                        value: '',
                                        label: 'Select property…'
                                    }, ...G.assets.map(a => ({value: a.id, label: a.name}))]}/>
                            {d.assetId && G.assets.find(a => a.id === d.assetId)?.units && (
                                <Select label="Unit" value={d.unitId || ''} onChange={v => set('unitId', v)}
                                        options={[{
                                            value: '',
                                            label: 'Select unit…'
                                        }, ...G.assets.find(a => a.id === d.assetId).units.filter(u => !u.occupied).map(u => ({
                                            value: u.id,
                                            label: `${u.id} · ${u.type}`
                                        }))]}/>
                            )}
                        </div>
                    </div>
                )}

                {step === 1 && (
                    <div style={{display: 'flex', flexDirection: 'column', gap: 12}}>
                        <Input label="Full legal name" placeholder="Grace Wanjiru" value={d.name}
                               onChange={v => set('name', v)} required/>
                        <div style={{display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12}}>
                            <Input label="Phone" placeholder="+254 7••" value={d.phone} onChange={v => set('phone', v)}
                                   mono required/>
                            <Input label="Email" placeholder="tenant@email.com" value={d.email}
                                   onChange={v => set('email', v)}/>
                        </div>
                        <div style={{display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12}}>
                            <Select label="ID type" value={d.idType} onChange={v => set('idType', v)}
                                    options={[{value: 'national_id', label: 'National ID'}, {
                                        value: 'passport',
                                        label: 'Passport'
                                    }, {value: 'company', label: 'Company Reg'}]}/>
                            <Input label="ID number" placeholder="2•••••••" value={d.idNumber}
                                   onChange={v => set('idNumber', v)} mono required/>
                        </div>
                        <Input label="Employer / Occupation" placeholder="Safaricom PLC" value={d.employer}
                               onChange={v => set('employer', v)}/>
                    </div>
                )}

                {step === 2 && (
                    <div style={{display: 'flex', flexDirection: 'column', gap: 12}}>
                        <div style={{display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12}}>
                            <Input label="Monthly rent (KES)" placeholder="95000" value={d.rent}
                                   onChange={v => set('rent', v)} mono prefix="KES" required/>
                            <Input label="Security deposit" placeholder="95000" value={d.deposit}
                                   onChange={v => set('deposit', v)} mono prefix="KES"/>
                        </div>
                        <div style={{display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12}}>
                            <Input label="Lease start" placeholder="01 / 07 / 2026" value={d.leaseStart}
                                   onChange={v => set('leaseStart', v)}/>
                            <Input label="Lease end" placeholder="30 / 06 / 2027" value={d.leaseEnd}
                                   onChange={v => set('leaseEnd', v)}/>
                        </div>
                        <Input label="Rent due day" placeholder="1" value={d.payDay} onChange={v => set('payDay', v)}
                               mono suffix="of each month"/>
                        <Select label="Payment method" value={d.payMethod} onChange={v => set('payMethod', v)}
                                options={[{value: 'mpesa', label: 'M-Pesa'}, {
                                    value: 'bank',
                                    label: 'Bank Transfer'
                                }, {value: 'cash', label: 'Cash'}]}/>
                    </div>
                )}

                {step === 3 && (
                    <div style={{display: 'flex', flexDirection: 'column', gap: 12}}>
                        <FileUpload label="Signed lease agreement" hint="PDF signed by both parties"
                                    uploaded={leaseUploaded} filename="Lease_Agreement.pdf"
                                    onUpload={() => setLeaseUploaded(true)}/>
                        <FileUpload label="Government-issued ID" hint="National ID or Passport front — JPG or PNG"
                                    uploaded={idUploaded} filename="Tenant_ID.jpg"
                                    onUpload={() => setIdUploaded(true)}/>
                        <Card style={{background: 'var(--surface-2)', boxShadow: 'none', padding: '12px 14px'}}>
                            <div style={{fontSize: 13, color: 'var(--ink-2)', lineHeight: 1.55}}>
                                KYC screening runs automatically after submission. Most tenants clear within 15 minutes.
                            </div>
                        </Card>
                    </div>
                )}
            </div>

            <div style={{flexShrink: 0, paddingTop: 16, display: 'flex', gap: 10}}>
                {step > 0 &&
                    <Btn kind="line" onClick={() => setStep(s => s - 1)} style={{width: 46, flexShrink: 0}}><Icon
                        name="chevL" size={17}/></Btn>}
                {step < steps.length - 1
                    ? <Btn kind="primary" full onClick={() => setStep(s => s + 1)}>Continue</Btn>
                    : <Btn kind="accent" full icon="check" onClick={onDone}>Add tenant</Btn>}
            </div>
        </div>
    );
}

Object.assign(window, {TenantsPage, TenantDetailPage, AddTenantWizard});
