/* gigi-onboarding.jsx — full KYC wizard: entity → property → tenant → review */

const ONB_PHASES = {
    entity: {label: 'Entity KYC', color: 'var(--info)'},
    property: {label: 'Property', color: 'var(--go)'},
    tenant: {label: 'Tenant', color: 'var(--accent-ink)'},
    review: {label: 'Review & Attest', color: 'var(--warn)'},
};

// ── Entity type card ──────────────────────────────────────────
function EntityTypeCard({id, label, desc, icon, on, onClick}) {
    return (
        <div onClick={onClick} className="g-tap" style={{
            padding: '18px 16px', borderRadius: 'var(--r-lg)', cursor: 'pointer',
            border: `1.5px solid ${on ? 'var(--accent-ink)' : 'var(--line)'}`,
            background: on ? 'var(--accent-ink)' : 'var(--surface)',
            color: on ? '#fff' : 'var(--ink)',
            display: 'flex', gap: 14, alignItems: 'flex-start',
        }}>
            <div style={{
                width: 40, height: 40, borderRadius: 11, background: on ? 'rgba(255,255,255,.12)' : 'var(--surface-2)',
                display: 'grid', placeItems: 'center', color: on ? 'var(--accent)' : 'var(--ink-2)', flexShrink: 0
            }}>
                <Icon name={icon} size={21}/>
            </div>
            <div>
                <div style={{fontWeight: 700, fontSize: 15}}>{label}</div>
                <div style={{
                    fontSize: 12.5,
                    marginTop: 4,
                    color: on ? 'rgba(255,255,255,.65)' : 'var(--ink-3)',
                    lineHeight: 1.45
                }}>{desc}</div>
            </div>
            {on && <div style={{marginLeft: 'auto', flexShrink: 0}}><Icon name="check" size={20} stroke={2.5}
                                                                          style={{color: 'var(--accent)'}}/></div>}
        </div>
    );
}

// ── Step: choose entity type ───────────────────────────────────
function StepEntityType({d, set}) {
    const types = [
        {
            id: 'individual',
            icon: 'user',
            label: 'Individual',
            desc: 'Register as a natural person. One KRA PIN, one officer.'
        },
        {
            id: 'llc',
            icon: 'building',
            label: 'Limited Company',
            desc: 'LLC, LTD or Sole Proprietorship with business registration.'
        },
        {
            id: 'trust',
            icon: 'shield',
            label: 'Family Trust',
            desc: 'Registered family trust with a trust deed and trustees.'
        },
    ];
    return (
        <div style={{display: 'flex', flexDirection: 'column', gap: 10}}>
            {types.map(t => <EntityTypeCard key={t.id} {...t} on={d.entityType === t.id}
                                            onClick={() => set('entityType', t.id)}/>)}
            <div style={{
                display: 'flex',
                gap: 8,
                color: 'var(--ink-3)',
                fontSize: 12.5,
                padding: '4px 2px',
                lineHeight: 1.5
            }}>
                <Icon name="lock" size={15} style={{flexShrink: 0, marginTop: 2}}/>
                Entity type is <b style={{color: 'var(--ink)'}}>permanent</b> — it cannot be changed after attestation
                and determines KYC compliance requirements.
            </div>
        </div>
    );
}

// ── Step: individual personal details ─────────────────────────
function StepIndividualKYC({d, set}) {
    return (
        <div style={{display: 'flex', flexDirection: 'column', gap: 14}}>
            <Input label="Full legal name" placeholder="James Kipchoge Meco" value={d.fullName}
                   onChange={v => set('fullName', v)} required/>
            <div className="g-2col">
                <Input label="Date of birth" placeholder="DD / MM / YYYY" value={d.dob} onChange={v => set('dob', v)}
                       required/>
                <Select label="Gender" value={d.gender || ''} onChange={v => set('gender', v)}
                        options={[{value: '', label: 'Select…'}, {value: 'M', label: 'Male'}, {
                            value: 'F',
                            label: 'Female'
                        }, {value: 'O', label: 'Other'}]}/>
            </div>
            <Input label="Nationality" placeholder="Kenyan" value={d.nationality || 'Kenyan'}
                   onChange={v => set('nationality', v)}/>
            <div className="g-2col">
                <Select label="ID type" value={d.idType || 'national_id'} onChange={v => set('idType', v)}
                        options={[{value: 'national_id', label: 'National ID'}, {
                            value: 'passport',
                            label: 'Passport'
                        }, {value: 'alien', label: 'Alien ID'}]}/>
                <Input label="ID number" placeholder="2• • • • • • • •" value={d.idNumber}
                       onChange={v => set('idNumber', v)} mono required/>
            </div>
            <Input label="Phone number" placeholder="+254 7•• ••• •••" value={d.phone} onChange={v => set('phone', v)}
                   mono required hint="Used for OTP and advance notifications."/>
            <Input label="Email address" placeholder="james@example.com" value={d.email} onChange={v => set('email', v)}
                   required/>
            <Input label="Employer / Occupation" placeholder="Safaricom PLC / Self-employed" value={d.employer}
                   onChange={v => set('employer', v)}/>
        </div>
    );
}

// ── Step: business KYC ─────────────────────────────────────────
function StepBusinessKYC({d, set}) {
    const typeLabels = {llc: 'Limited Company', trust: 'Family Trust'};
    return (
        <div style={{display: 'flex', flexDirection: 'column', gap: 14}}>
            <Input label="Registered business name" placeholder="Meco Holdings Ltd" value={d.bizName}
                   onChange={v => set('bizName', v)} required/>
            <div className="g-2col">
                <Input label="Registration number" placeholder="PVT-LX9K22M" value={d.bizReg}
                       onChange={v => set('bizReg', v)} mono required/>
                <Input label="Date of incorporation" placeholder="DD / MM / YYYY" value={d.bizDate}
                       onChange={v => set('bizDate', v)}/>
            </div>
            <Card style={{background: 'var(--surface-2)', boxShadow: 'none', padding: '14px 16px'}}>
                <div style={{display: 'flex', gap: 10, alignItems: 'center'}}>
                    <Badge tone="info">{typeLabels[d.entityType] || d.entityType}</Badge>
                    <span style={{fontSize: 13, color: 'var(--ink-2)'}}>Set on previous step · cannot be changed</span>
                </div>
            </Card>
            <SectionLabel>Authorized Officer</SectionLabel>
            <div className="g-2col">
                <Input label="Full name" placeholder="James Meco" value={d.officerName}
                       onChange={v => set('officerName', v)} required/>
                <Input label="National ID" placeholder="2• • • • • • • •" value={d.officerID}
                       onChange={v => set('officerID', v)} mono required/>
            </div>
            <Input label="Officer email" placeholder="james@meco.co.ke" value={d.officerEmail}
                   onChange={v => set('officerEmail', v)} required/>
            <Input label="Officer phone" placeholder="+254 7•• ••• •••" value={d.officerPhone}
                   onChange={v => set('officerPhone', v)} mono/>
            {d.entityType === 'trust' && (
                <>
                    <SectionLabel>Trustees</SectionLabel>
                    <Card style={{background: 'var(--surface-2)', boxShadow: 'none', padding: '14px 16px'}}>
                        <div style={{fontSize: 13, color: 'var(--ink-2)', lineHeight: 1.55}}>
                            Each trustee needs to complete individual KYC via an invite link sent to their email. You
                            can manage trustees after onboarding.
                        </div>
                    </Card>
                </>
            )}
        </div>
    );
}

// ── Step: KYC documents upload ─────────────────────────────────
function StepDocuments({d, set, isIndividual}) {
    const [uploads, setUploads] = React.useState({});
    const markUploaded = (key) => {
        const next = {...uploads, [key]: true};
        setUploads(next);
        set('docsUploaded', next);
    };
    const docList = isIndividual
        ? [
            {key: 'id_front', label: 'National ID — Front', hint: 'JPG or PNG, under 5MB'},
            {key: 'id_back', label: 'National ID — Back', hint: 'JPG or PNG, under 5MB'},
            {key: 'selfie', label: 'Selfie / Liveness photo', hint: 'Take or upload a clear photo of your face'},
        ]
        : [
            {
                key: 'cert_inc',
                label: d.entityType === 'trust' ? 'Trust Deed' : 'Certificate of Incorporation',
                hint: 'PDF or scanned copy'
            },
            {
                key: 'cr12',
                label: d.entityType === 'trust' ? 'Trustee Resolution' : 'CR12 (Directors list)',
                hint: 'Within last 12 months'
            },
            {key: 'officer_id', label: "Authorized Officer's National ID", hint: 'Front side, JPG or PNG'},
        ];
    return (
        <div style={{display: 'flex', flexDirection: 'column', gap: 14}}>
            {docList.map(doc => (
                <FileUpload key={doc.key} label={doc.label} hint={doc.hint}
                            uploaded={!!uploads[doc.key]}
                            filename={doc.label + '.pdf'}
                            onUpload={() => markUploaded(doc.key)}/>
            ))}
            <Card style={{background: 'var(--surface-2)', boxShadow: 'none', padding: '12px 14px'}}>
                <div style={{display: 'flex', gap: 9, color: 'var(--ink-3)', fontSize: 12.5, lineHeight: 1.5}}>
                    <Icon name="shield" size={16} style={{flexShrink: 0, marginTop: 2}}/>
                    Documents are encrypted at rest and only accessed by Gigi's compliance team under the CBK Digital
                    Credit Provider framework.
                </div>
            </Card>
        </div>
    );
}

// ── Step: KRA PIN ─────────────────────────────────────────────
function StepKRAPIN({d, set}) {
    const [verified, setVerified] = React.useState(false);
    const [checking, setChecking] = React.useState(false);
    const check = () => {
        if (!d.kraPin) return;
        setChecking(true);
        setTimeout(() => {
            setChecking(false);
            setVerified(true);
            set('kraVerified', true);
        }, 1200);
    };
    return (
        <div style={{display: 'flex', flexDirection: 'column', gap: 14}}>
            <Input label="KRA PIN" placeholder="A• • • • • • • • •P" value={d.kraPin} onChange={v => {
                set('kraPin', v);
                setVerified(false);
                set('kraVerified', false);
            }} mono required hint="Format: 1 letter + 9 digits + 1 letter (e.g. A004221987P)"/>
            {!verified
                ? <Btn kind="ghost" onClick={check}
                       disabled={!d.kraPin || checking}>{checking ? 'Verifying…' : 'Verify with iTax'}</Btn>
                : (
                    <Card style={{
                        background: 'var(--go-bg)',
                        boxShadow: 'none',
                        padding: '14px 16px',
                        display: 'flex',
                        gap: 12,
                        alignItems: 'center'
                    }}>
                        <Icon name="check" size={20} stroke={2.5} style={{color: 'var(--go)', flexShrink: 0}}/>
                        <div>
                            <div style={{fontWeight: 700, fontSize: 14, color: 'var(--go)'}}>KRA PIN verified</div>
                            <div style={{fontSize: 12.5, color: 'var(--go)', marginTop: 2}}>Taxpayer found — compliance
                                status: Active
                            </div>
                        </div>
                    </Card>
                )
            }
            {d.entityType !== 'individual' && (
                <>
                    <Input label="Business KRA PIN" placeholder="P• • • • • • • • •X" value={d.bizKraPin}
                           onChange={v => set('bizKraPin', v)} mono hint="Separate PIN for the registered entity."/>
                    <FileUpload label="KRA PIN Certificate" hint="Download from iTax portal — PDF"
                                uploaded={!!d.kraCertUploaded} onUpload={() => set('kraCertUploaded', true)}
                                filename="KRA_Certificate.pdf"/>
                </>
            )}
        </div>
    );
}

// ── Step: disbursement ────────────────────────────────────────
function StepDisbursement({d, set}) {
    return (
        <div style={{display: 'flex', flexDirection: 'column', gap: 14}}>
            <div style={{display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10}}>
                {[
                    {id: 'mpesa', icon: 'mpesa', label: 'M-Pesa Business', desc: 'Mpesa Number'},
                    {id: 'bank', icon: 'bank', label: 'Corporate Bank', desc: 'NCBA, Equity, KCB, etc.'},
                ].map(o => {
                    const on = d.disbursement === o.id;
                    return (
                        <div key={o.id} onClick={() => set('disbursement', o.id)} className="g-tap" style={{
                            padding: '16px',
                            borderRadius: 'var(--r-md)',
                            border: `1.5px solid ${on ? 'var(--accent-ink)' : 'var(--line)'}`,
                            background: on ? 'var(--surface)' : 'var(--surface)',
                            boxShadow: on ? 'var(--shadow)' : 'none',
                            display: 'flex',
                            flexDirection: 'column',
                            gap: 8
                        }}>
                            <Icon name={o.icon} size={22} style={{color: on ? 'var(--ink)' : 'var(--ink-3)'}}/>
                            <div style={{fontWeight: 700, fontSize: 14}}>{o.label}</div>
                            <div style={{fontSize: 12, color: 'var(--ink-3)'}}>{o.desc}</div>
                            {on && <Badge tone="go" dot>Selected</Badge>}
                        </div>
                    );
                })}
            </div>
            {d.disbursement === 'mpesa' && (
                <>
                    <Input label="M-Pesa number" placeholder="****0084" value={d.mpesaAccount}
                           onChange={v => set('mpesaAccount', v)} mono prefix="Mpesa" required/>
                    <Input label="Account name (as registered)" placeholder="meco HOLDINGS LTD" value={d.mpesaName}
                           onChange={v => set('mpesaName', v)}/>
                </>
            )}
            {d.disbursement === 'bank' && (
                <>
                    <Input label="Bank name" placeholder="NCBA / Equity / KCB" value={d.bankName}
                           onChange={v => set('bankName', v)} required/>
                    <Input label="Account number" placeholder="0• • • • • • • • •" value={d.bankAccount}
                           onChange={v => set('bankAccount', v)} mono required/>
                    <Input label="Account name" placeholder="meco HOLDINGS LTD" value={d.bankHolder}
                           onChange={v => set('bankHolder', v)}/>
                </>
            )}
            {d.disbursement && (
                <div style={{
                    display: 'flex',
                    gap: 8,
                    color: 'var(--ink-3)',
                    fontSize: 12,
                    padding: '2px 2px',
                    lineHeight: 1.5
                }}>
                    <Icon name="lock" size={14} style={{flexShrink: 0, marginTop: 2}}/>
                    This destination is <b style={{color: 'var(--ink)'}}>locked after submission</b>. Changes require
                    re-authentication and are audited under CBK requirements.
                </div>
            )}
        </div>
    );
}

// ── Step: property type ───────────────────────────────────────
function StepPropertyType({d, set}) {
    const G = window.GIGI;
    const types = Object.entries(G.PROP_TYPES).map(([id, v]) => ({id, ...v}));
    return (
        <div style={{display: 'flex', flexDirection: 'column', gap: 10}}>
            <ChipSelector options={types} value={d.propType} onChange={v => set('propType', v)}/>
            {d.propType && (
                <Card style={{background: 'var(--info-bg)', boxShadow: 'none', padding: '14px 16px', marginTop: 4}}>
                    <div style={{display: 'flex', gap: 10, alignItems: 'flex-start'}}>
                        <Icon name="info" size={16} style={{color: 'var(--info)', flexShrink: 0, marginTop: 2}}/>
                        <div style={{fontSize: 13, color: 'var(--info)', lineHeight: 1.5}}>
                            {G.PROP_TYPES[d.propType].multi
                                ? 'Multi-unit property — you\'ll configure individual units and assign tenants per unit.'
                                : 'Single dwelling — you\'ll add one tenant directly to this property.'}
                        </div>
                    </div>
                </Card>
            )}
        </div>
    );
}

// ── Step: property details ─────────────────────────────────────
function StepPropertyDetails({d, set}) {
    const [titleUploaded, setTitleUploaded] = React.useState(false);
    const [ownershipUploaded, setOwnershipUploaded] = React.useState(false);
    return (
        <div style={{display: 'flex', flexDirection: 'column', gap: 14}}>
            <Input label="Property legal name" placeholder="Riverside Court" value={d.propName}
                   onChange={v => set('propName', v)} required/>
            <Input label="Physical address" placeholder="Riverside Drive, Westlands, Nairobi" value={d.propAddress}
                   onChange={v => set('propAddress', v)} required/>
            <div className="g-2col">
                <Input label="LR / Title number" placeholder="LR 209/14882" value={d.propLR}
                       onChange={v => set('propLR', v)} mono required/>
                <Select label="City" value={d.propCity || 'Nairobi'} onChange={v => set('propCity', v)}
                        options={['Nairobi', 'Mombasa', 'Kisumu', 'Nakuru', 'Eldoret', 'Other']}/>
            </div>
            <div>
                <div style={{fontSize: 12.5, fontWeight: 600, color: 'var(--ink-2)', marginBottom: 8}}>Your ownership
                    stake *
                </div>
                <div style={{display: 'flex', alignItems: 'center', gap: 12}}>
                    <input type="range" min="10" max="100" step="5" value={d.propStake || 100}
                           onChange={e => set('propStake', +e.target.value)}
                           style={{flex: 1, accentColor: 'var(--accent-ink)'}}/>
                    <div className="g-num"
                         style={{fontSize: 20, fontWeight: 700, minWidth: 54, textAlign: 'right'}}>{d.propStake || 100}%
                    </div>
                </div>
                {(d.propStake || 100) < 100 && (
                    <div style={{fontSize: 12, color: 'var(--info)', marginTop: 6}}>
                        Co-owners will receive an invite to register and attest their stake. Advances on this property
                        require majority consent.
                    </div>
                )}
            </div>
            <SectionLabel>Required documents</SectionLabel>
            <FileUpload label="Title Deed" hint="Scanned copy or PDF — must clearly show LR number and registered owner"
                        uploaded={titleUploaded} filename="Title_Deed.pdf" onUpload={() => {
                setTitleUploaded(true);
                set('titleDeedUploaded', true);
            }}/>
            <FileUpload label="Proof of Ownership / Search Certificate"
                        hint="Land Registry official search, within 30 days"
                        uploaded={ownershipUploaded} filename="Ownership_Search.pdf" onUpload={() => {
                setOwnershipUploaded(true);
                set('ownershipDocUploaded', true);
            }}/>
            {d.propType === 'office' || d.propType === 'apartment_block' ? (
                <FileUpload label="Master Lease (if applicable)"
                            hint="Required for multi-tenanted commercial properties"
                            uploaded={false} filename="Master_Lease.pdf"
                            onUpload={() => set('masterLeaseUploaded', true)}/>
            ) : null}
        </div>
    );
}

// ── Step: unit configuration ───────────────────────────────────
function StepUnits({d, set}) {
    const [units, setUnits] = React.useState(d.units || []);
    const [draft, setDraft] = React.useState({id: '', floor: '1', type: '2BR', rent: ''});
    const typeOpts = ['Studio', '1BR', '2BR', '3BR', '4BR', 'Penthouse', 'Retail', 'Office', 'Other'];

    const addUnit = () => {
        if (!draft.id || !draft.rent) return;
        const next = [...units, {...draft, id: draft.id.toUpperCase()}];
        setUnits(next);
        set('units', next);
        setDraft({id: '', floor: draft.floor, type: draft.type, rent: ''});
    };

    return (
        <div style={{display: 'flex', flexDirection: 'column', gap: 14}}>
            <Card>
                <div style={{fontWeight: 600, fontSize: 14, marginBottom: 14}}>Add a unit</div>
                <div style={{display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10}}>
                    <Input label="Unit ID" placeholder="A1, 101, G01…" value={draft.id}
                           onChange={v => setDraft(p => ({...p, id: v}))} mono/>
                    <Input label="Floor" placeholder="0" value={draft.floor}
                           onChange={v => setDraft(p => ({...p, floor: v}))} mono/>
                </div>
                <div style={{marginTop: 10}}>
                    <Select label="Unit type" value={draft.type} onChange={v => setDraft(p => ({...p, type: v}))}
                            options={typeOpts}/>
                </div>
                <div style={{marginTop: 10}}>
                    <Input label="Monthly rent (KES)" placeholder="95000" value={draft.rent}
                           onChange={v => setDraft(p => ({...p, rent: v}))} mono prefix="KES"/>
                </div>
                <div style={{marginTop: 14}}>
                    <Btn kind="ghost" icon="plus" onClick={addUnit} disabled={!draft.id || !draft.rent}>Add unit</Btn>
                </div>
            </Card>

            {units.length > 0 && (
                <div>
                    <SectionLabel>{units.length} unit{units.length !== 1 ? 's' : ''} configured</SectionLabel>
                    <Card style={{padding: 0}}>
                        {units.map((u, i) => (
                            <div key={u.id} style={{
                                display: 'flex', alignItems: 'center', gap: 12, padding: '12px 16px',
                                borderBottom: i < units.length - 1 ? '1px solid var(--line-2)' : 'none'
                            }}>
                                <div className="g-mono" style={{
                                    width: 44, height: 36, borderRadius: 9, background: 'var(--surface-2)',
                                    display: 'grid', placeItems: 'center', fontSize: 12, fontWeight: 700, flexShrink: 0
                                }}>{u.id}</div>
                                <div style={{flex: 1}}>
                                    <div style={{fontWeight: 600, fontSize: 13.5}}>{u.type} · Floor {u.floor}</div>
                                    <div className="g-mono" style={{
                                        fontSize: 12,
                                        color: 'var(--ink-3)'
                                    }}>KES {Number(u.rent).toLocaleString()}/mo
                                    </div>
                                </div>
                                <button onClick={() => {
                                    const next = units.filter((_, j) => j !== i);
                                    setUnits(next);
                                    set('units', next);
                                }}
                                        className="g-tap" style={{
                                    border: 'none',
                                    background: 'transparent',
                                    color: 'var(--ink-3)',
                                    cursor: 'pointer'
                                }}>
                                    <Icon name="x" size={16}/>
                                </button>
                            </div>
                        ))}
                    </Card>
                </div>
            )}

            <div style={{fontSize: 12.5, color: 'var(--ink-3)', lineHeight: 1.5}}>
                You can add more units after onboarding. At least 85% occupancy is required before an advance can be
                requested.
            </div>
        </div>
    );
}

// ── Step: first tenant ─────────────────────────────────────────
function StepTenant({d, set}) {
    const [adding, setAdding] = React.useState(d.addTenant !== false);
    const [leaseUploaded, setLeaseUploaded] = React.useState(false);
    const G = window.GIGI;
    const isMulti = d.propType && G.PROP_TYPES[d.propType]?.multi;

    if (!adding) {
        return (
            <div>
                <Card style={{
                    textAlign: 'center',
                    padding: '32px 24px',
                    background: 'var(--surface-2)',
                    boxShadow: 'none'
                }}>
                    <Icon name="users" size={28} style={{color: 'var(--ink-3)'}}/>
                    <div style={{fontWeight: 700, fontSize: 15, marginTop: 14}}>Tenants added after onboarding</div>
                    <div style={{fontSize: 13.5, color: 'var(--ink-2)', marginTop: 8, lineHeight: 1.5}}>
                        You can add tenants from the Tenants section once your property is verified. The property will
                        be marked <b>Ineligible</b> until it has active tenancy.
                    </div>
                    <div style={{marginTop: 18}}><Btn kind="ghost" icon="plus" onClick={() => {
                        setAdding(true);
                        set('addTenant', true);
                    }}>Add a tenant now</Btn></div>
                </Card>
            </div>
        );
    }

    return (
        <div style={{display: 'flex', flexDirection: 'column', gap: 14}}>
            {isMulti && d.units?.length > 0 && (
                <Select label="Assign to unit" value={d.tenantUnit || ''} onChange={v => set('tenantUnit', v)}
                        options={[{value: '', label: 'Select unit…'}, ...d.units.map(u => ({
                            value: u.id,
                            label: `${u.id} · ${u.type} · KES ${Number(u.rent).toLocaleString()}/mo`
                        }))]}/>
            )}
            <SectionLabel>Tenant KYC</SectionLabel>
            <Input label="Full legal name" placeholder="Grace Wanjiru" value={d.tenantName}
                   onChange={v => set('tenantName', v)} required/>
            <div className="g-2col">
                <Input label="Phone" placeholder="+254 7•• ••• •••" value={d.tenantPhone}
                       onChange={v => set('tenantPhone', v)} mono required/>
                <Input label="Email" placeholder="tenant@email.com" value={d.tenantEmail}
                       onChange={v => set('tenantEmail', v)}/>
            </div>
            <div className="g-2col">
                <Select label="ID type" value={d.tenantIdType || 'national_id'} onChange={v => set('tenantIdType', 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.tenantIdNumber}
                       onChange={v => set('tenantIdNumber', v)} mono required/>
            </div>
            <SectionLabel>Lease details</SectionLabel>
            <div className="g-2col">
                <Input label="Monthly rent (KES)" placeholder="95000" value={d.tenantRent}
                       onChange={v => set('tenantRent', v)} mono prefix="KES" required/>
                <Input label="Security deposit" placeholder="95000" value={d.tenantDeposit}
                       onChange={v => set('tenantDeposit', v)} mono prefix="KES"/>
            </div>
            <div className="g-2col">
                <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" hint="Day of the month when rent is due."/>
            <Select label="Payment method" value={d.tenantPayMethod || 'mpesa'}
                    onChange={v => set('tenantPayMethod', v)}
                    options={[{value: 'mpesa', label: 'M-Pesa'}, {
                        value: 'bank',
                        label: 'Bank Transfer'
                    }, {value: 'cash', label: 'Cash (not recommended)'}]}/>
            <FileUpload label="Signed lease agreement" hint="PDF — signed by both parties"
                        uploaded={leaseUploaded} filename="Lease_Agreement.pdf"
                        onUpload={() => {
                            setLeaseUploaded(true);
                            set('leaseUploaded', true);
                        }}/>
            <Btn kind="line" small onClick={() => {
                setAdding(false);
                set('addTenant', false);
            }}>Skip for now</Btn>
        </div>
    );
}

// ── Step: review & attest ──────────────────────────────────────
function StepReview({d, attested, setAttested}) {
    const G = window.GIGI;
    const entityLabel = {individual: 'Individual', llc: 'Limited Company', trust: 'Family Trust'}[d.entityType] || '—';
    const propLabel = d.propType ? G.PROP_TYPES[d.propType]?.label : '—';
    return (
        <div style={{display: 'flex', flexDirection: 'column', gap: 16}}>
            <Card style={{background: 'var(--surface-2)', boxShadow: 'none', padding: '12px 14px'}}>
                <div style={{display: 'flex', gap: 8, color: 'var(--ink-2)', fontSize: 13}}>
                    <Icon name="doc" size={16} style={{flexShrink: 0, marginTop: 2}}/>
                    Data manifest — read only. Tap any section to edit before submitting.
                </div>
            </Card>
            <div>
                <SectionLabel>Entity</SectionLabel>
                <Card>
                    <Field label="Type" value={entityLabel}/>
                    <Field label={d.entityType === 'individual' ? 'Full name' : 'Business name'}
                           value={d.fullName || d.bizName || '—'}/>
                    <Field label="KRA PIN" value={d.kraPin || '—'} mono/>
                    {d.bizReg && <Field label="Reg. number" value={d.bizReg} mono/>}
                    <Field label="Disbursement"
                           value={d.disbursement === 'mpesa' ? `M-Pesa · ${d.mpesaAccount || '—'}` : d.bankName || '—'}
                           last/>
                </Card>
            </div>
            {d.propName && (
                <div>
                    <SectionLabel>Property</SectionLabel>
                    <Card>
                        <Field label="Name" value={d.propName}/>
                        <Field label="Type" value={propLabel}/>
                        <Field label="LR number" value={d.propLR || '—'} mono/>
                        <Field label="Your stake" value={(d.propStake || 100) + '%'}/>
                        <Field label="Units configured" value={d.units?.length || 0} last/>
                    </Card>
                </div>
            )}
            {d.addTenant !== false && d.tenantName && (
                <div>
                    <SectionLabel>First Tenant</SectionLabel>
                    <Card>
                        <Field label="Name" value={d.tenantName}/>
                        <Field label="Monthly rent"
                               value={d.tenantRent ? `KES ${Number(d.tenantRent).toLocaleString()}` : '—'} mono/>
                        <Field label="Lease start" value={d.leaseStart || '—'} last/>
                    </Card>
                </div>
            )}
            <div onClick={() => setAttested(!attested)} className="g-tap" style={{
                display: 'flex',
                gap: 12,
                padding: '16px',
                borderRadius: 'var(--r-md)',
                border: `1.5px solid ${attested ? 'var(--accent-ink)' : 'var(--line)'}`,
                background: attested ? 'var(--surface-2)' : 'var(--surface)',
                marginTop: 4
            }}>
                <div style={{
                    width: 22,
                    height: 22,
                    borderRadius: 7,
                    flexShrink: 0,
                    display: 'grid',
                    placeItems: 'center',
                    marginTop: 1,
                    background: attested ? 'var(--accent-ink)' : 'transparent',
                    border: attested ? 'none' : '1.5px solid var(--ink-3)',
                    color: '#fff'
                }}>
                    {attested && <Icon name="check" size={14} stroke={3}/>}
                </div>
                <div style={{fontSize: 13, color: 'var(--ink-2)', lineHeight: 1.55}}>
                    I confirm this information is accurate. I accept the <b style={{color: 'var(--ink)'}}>Data Privacy
                    Protocol</b> under CBK Digital Credit Provider Regulations. I understand submission is <b
                    style={{color: 'var(--ink)'}}>irreversible</b>.
                </div>
            </div>
        </div>
    );
}

// ── Main Onboarding component ─────────────────────────────────
function Onboarding({forcedStep, onFinish}) {
    const G = window.GIGI;
    const [d, setD] = React.useState({
        entityType: 'llc',
        disbursement: 'mpesa',
        propType: 'apartment_block',
        propStake: 100,
        units: [],
        addTenant: true
    });
    const [attested, setAttested] = React.useState(false);
    const set = (k, v) => setD(p => ({...p, [k]: v}));

    const isIndividual = d.entityType === 'individual';
    const isMultiUnit = d.propType && G.PROP_TYPES[d.propType]?.multi;

    // Build step list dynamically
    const steps = React.useMemo(() => {
        const base = [
            {id: 'entity_type', label: 'Entity type', phase: 'entity'},
            {id: 'kyc_details', label: isIndividual ? 'Personal details' : 'Business details', phase: 'entity'},
            {id: 'documents', label: 'Upload documents', phase: 'entity'},
            {id: 'kra', label: 'KRA & tax', phase: 'entity'},
            {id: 'disbursement', label: 'Disbursement', phase: 'entity'},
            {id: 'prop_type', label: 'Property type', phase: 'property'},
            {id: 'prop_details', label: 'Property details', phase: 'property'},
            ...(isMultiUnit ? [{id: 'units', label: 'Configure units', phase: 'property'}] : []),
            {id: 'tenant', label: 'Add tenant', phase: 'tenant'},
            {id: 'review', label: 'Review & attest', phase: 'review'},
        ];
        return base;
    }, [isIndividual, isMultiUnit]);

    const [stepIdx, setStepIdx] = React.useState(0);
    React.useEffect(() => {
        if (forcedStep !== undefined) setStepIdx(Math.min(forcedStep, steps.length - 1));
    }, [forcedStep, steps.length]);

    const current = steps[stepIdx];
    const isLast = stepIdx === steps.length - 1;

    const stepTitles = {
        entity_type: 'How are you organised?',
        kyc_details: isIndividual ? 'Your personal details' : 'Your business details',
        documents: 'Upload your documents',
        kra: 'KRA PIN & tax status',
        disbursement: 'Where should we send money?',
        prop_type: 'What type of property?',
        prop_details: 'Property details',
        units: 'Configure units',
        tenant: 'Add your first tenant',
        review: 'Review & attest',
    };
    const stepSubs = {
        entity_type: 'This determines your compliance obligations and the documents required.',
        kyc_details: isIndividual ? 'These details are verified against government records.' : 'Company details as per the Certificate of Incorporation.',
        documents: 'Encrypted and stored securely. Required for CBK compliance.',
        kra: 'We verify your tax compliance status before unlocking lending.',
        disbursement: 'Advance proceeds are sent here. Locked once set and requires re-authentication to change.',
        prop_type: 'Different property types have different onboarding flows and rent configurations.',
        prop_details: 'Match the exact details on your title deed. Discrepancies delay verification.',
        units: 'Define each rentable unit. Verified monthly rent is calculated from active leases.',
        tenant: 'Add KYC details and a signed lease to activate this property for rent advances.',
        review: 'Check everything before submitting. Once submitted, the entity type and officer identity are locked.',
    };

    const nextDisabled = (
        (current.id === 'entity_type' && !d.entityType) ||
        (current.id === 'disbursement' && !d.disbursement) ||
        (current.id === 'prop_type' && !d.propType) ||
        (current.id === 'review' && !attested)
    );

    const phaseInfo = ONB_PHASES[current.phase];

    return (
        <div className="g-root" style={{
            height: '100%',
            display: 'flex',
            flexDirection: 'column',
            background: 'var(--sand)',
            overflow: 'hidden'
        }}>
            {/* Phase bar */}
            <div style={{flexShrink: 0, padding: '16px 28px 0'}}>
                <div className="g-wiz-wrap" style={{display: 'flex', gap: 6}}>
                    {Object.entries(ONB_PHASES).map(([k, ph]) => {
                        const stepsInPhase = steps.filter(s => s.phase === k);
                        const doneCount = stepsInPhase.filter(s => steps.indexOf(s) < stepIdx).length;
                        const isActive = current.phase === k;
                        return (
                            <div key={k} style={{flex: 1}}>
                                <div style={{
                                    height: 4,
                                    borderRadius: 999,
                                    overflow: 'hidden',
                                    background: 'var(--line)'
                                }}>
                                    <div style={{
                                        height: '100%',
                                        width: isActive ? '60%' : doneCount === stepsInPhase.length ? '100%' : '0%',
                                        background: ph.color,
                                        transition: 'width .4s, background .3s',
                                        borderRadius: 999
                                    }}/>
                                </div>
                                <div style={{
                                    fontSize: 10.5,
                                    fontWeight: 600,
                                    color: isActive ? 'var(--ink)' : 'var(--ink-3)',
                                    marginTop: 5,
                                    letterSpacing: '.03em',
                                    whiteSpace: 'nowrap',
                                    overflow: 'hidden',
                                    textOverflow: 'ellipsis'
                                }}>
                                    {ph.label}
                                </div>
                            </div>
                        );
                    })}
                </div>
            </div>
            {/* Logo */}
            <div style={{flexShrink: 0, padding: '14px 28px 0'}}>
                <div className="g-wiz-wrap" 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={16}/></div>
                    <span className="g-num" style={{fontWeight: 700, fontSize: 16}}>Gigi</span>
                </div>
            </div>
            {/* Title */}
            <div style={{flexShrink: 0, padding: '14px 28px 0'}}>
                <div className="g-wiz-wrap">
                    <div style={{
                        fontSize: 11.5,
                        fontWeight: 700,
                        color: 'var(--ink-3)',
                        textTransform: 'uppercase',
                        letterSpacing: '.07em',
                        marginBottom: 6
                    }}>
                        Step {stepIdx + 1} / {steps.length} · {stepTitles[current.id]}
                    </div>
                    <h1 className="g-num g-enter" key={current.id} style={{
                        fontSize: 28,
                        fontWeight: 700,
                        margin: 0,
                        lineHeight: 1.1
                    }}>{stepTitles[current.id]}</h1>
                    <p style={{
                        fontSize: 13.5,
                        color: 'var(--ink-2)',
                        margin: '8px 0 0',
                        lineHeight: 1.55
                    }}>{stepSubs[current.id]}</p>
                </div>
            </div>
            {/* Body */}
            <div className="g-scroll" style={{flex: 1, overflowY: 'auto', padding: '18px 28px 12px'}}>
                <div className="g-wiz-wrap g-enter" key={current.id + '_body'}>
                    {current.id === 'entity_type' && <StepEntityType d={d} set={set}/>}
                    {current.id === 'kyc_details' && (isIndividual ? <StepIndividualKYC d={d} set={set}/> :
                        <StepBusinessKYC d={d} set={set}/>)}
                    {current.id === 'documents' && <StepDocuments d={d} set={set} isIndividual={isIndividual}/>}
                    {current.id === 'kra' && <StepKRAPIN d={d} set={set}/>}
                    {current.id === 'disbursement' && <StepDisbursement d={d} set={set}/>}
                    {current.id === 'prop_type' && <StepPropertyType d={d} set={set}/>}
                    {current.id === 'prop_details' && <StepPropertyDetails d={d} set={set}/>}
                    {current.id === 'units' && <StepUnits d={d} set={set}/>}
                    {current.id === 'tenant' && <StepTenant d={d} set={set}/>}
                    {current.id === 'review' && <StepReview d={d} attested={attested} setAttested={setAttested}/>}
                </div>
            </div>
            {/* Footer */}
            <div style={{flexShrink: 0, padding: '10px 28px calc(16px + env(safe-area-inset-bottom,0px))'}}>
                <div className="g-wiz-wrap" style={{display: 'flex', gap: 10}}>
                    {stepIdx > 0 && (
                        <Btn kind="line" onClick={() => setStepIdx(s => s - 1)} style={{width: 48, flexShrink: 0}}>
                            <Icon name="chevL" size={18}/>
                        </Btn>
                    )}
                    <Btn kind={isLast ? 'accent' : 'primary'}
                         onClick={() => isLast ? onFinish() : setStepIdx(s => s + 1)}
                         disabled={nextDisabled} full icon={isLast ? 'check' : undefined}>
                        {isLast ? 'Submit for verification' : stepIdx === 0 ? 'Get started' : 'Continue'}
                    </Btn>
                </div>
            </div>
        </div>
    );
}

Object.assign(window, {Onboarding, StepPropertyType, StepPropertyDetails, StepUnits, StepTenant});
