/* gigi-add-property.jsx — standalone Add Property wizard + flow launcher cards */

// ── Property type card (large, descriptive) ───────────────────
function PropTypeCard({id, label, desc, icon, accent, on, onClick, flowNote}) {
    return (
        <div onClick={onClick} className="g-tap" style={{
            padding: '18px 16px', borderRadius: 'var(--r-lg)', cursor: 'pointer', display: 'flex', gap: 14,
            border: `1.5px solid ${on ? 'var(--accent-ink)' : 'var(--line)'}`,
            background: on ? 'var(--accent-ink)' : 'var(--surface)',
            color: on ? '#fff' : 'var(--ink)', alignItems: 'flex-start',
            boxShadow: on ? 'var(--shadow-md)' : 'none',
        }}>
            <div style={{
                width: 44, height: 44, borderRadius: 12, flexShrink: 0, display: 'grid', placeItems: 'center',
                background: on ? 'rgba(255,255,255,.12)' : 'var(--surface-2)',
                color: on ? 'var(--accent)' : 'var(--ink-2)'
            }}>
                <Icon name={icon} size={22}/>
            </div>
            <div style={{flex: 1, minWidth: 0}}>
                <div style={{fontWeight: 700, fontSize: 15}}>{label}</div>
                <div style={{
                    fontSize: 13,
                    marginTop: 4,
                    color: on ? 'rgba(255,255,255,.7)' : 'var(--ink-3)',
                    lineHeight: 1.45
                }}>{desc}</div>
                {flowNote && (
                    <div style={{
                        display: 'inline-flex', alignItems: 'center', gap: 5, marginTop: 8, fontSize: 11.5,
                        fontWeight: 600, color: on ? 'var(--accent)' : 'var(--go)',
                        background: on ? 'rgba(255,255,255,.1)' : 'var(--go-bg)',
                        padding: '3px 9px', borderRadius: 999
                    }}>
                        <Icon name="info" size={12}/>{flowNote}
                    </div>
                )}
            </div>
            {on && <Icon name="check" size={20} stroke={2.5}
                         style={{color: 'var(--accent)', flexShrink: 0, marginTop: 2}}/>}
        </div>
    );
}

// ── Step 1: Choose property type ──────────────────────────────
function APStepType({d, set}) {
    const G = window.GIGI;
    const types = [
        {
            id: 'apartment_block',
            icon: 'building',
            label: 'Apartment Block',
            desc: 'Whole residential building under your ownership, with multiple individual units.',
            flowNote: 'Units configured per floor'
        },
        {
            id: 'single_unit',
            icon: 'box',
            label: 'Single Unit',
            desc: 'One apartment or unit in a larger building where you own just that specific unit.',
            flowNote: 'Direct to tenant view'
        },
        {
            id: 'mansionette',
            icon: 'home',
            label: 'Mansionette',
            desc: 'Multi-floor standalone house. One dwelling, one tenant (or family).',
            flowNote: 'Single occupancy'
        },
        {
            id: 'mansion',
            icon: 'home',
            label: 'Mansion',
            desc: 'Large standalone residential estate. Often one primary tenant or vacant.',
            flowNote: 'Single occupancy'
        },
        {
            id: 'office',
            icon: 'office',
            label: 'Office / Commercial',
            desc: 'Commercial, retail, or mixed-use space — may have multiple tenants or a master lease.',
            flowNote: 'Units per floor supported'
        },
    ];
    return (
        <div style={{display: 'flex', flexDirection: 'column', gap: 10}}>
            {types.map(t => {
                const pt = G.PROP_TYPES[t.id];
                return <PropTypeCard key={t.id} {...t} accent={pt?.accent} on={d.propType === t.id}
                                     onClick={() => set('propType', t.id)}/>;
            })}
        </div>
    );
}

// ── Step 2: Property details ───────────────────────────────────
function APStepDetails({d, set}) {
    return (
        <div style={{display: 'flex', flexDirection: 'column', gap: 16}}>
            <Input label="Property legal name" placeholder="Riverside Court" value={d.propName}
                   onChange={v => set('propName', v)} required
                   hint="Use the exact name as it appears on the title deed."/>
            <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
                       hint="Found on the title deed, begins with 'LR' or 'MN'."/>
                <Select label="County" value={d.propCounty || 'Nairobi'} onChange={v => set('propCounty', v)}
                        options={['Nairobi', 'Mombasa', 'Kisumu', 'Nakuru', 'Kiambu', 'Machakos', 'Kajiado', 'Laikipia', 'Nyeri', 'Other']}/>
            </div>

            <div>
                <div style={{fontSize: 12.5, fontWeight: 600, color: 'var(--ink-2)', marginBottom: 8}}>
                    Your ownership stake <span style={{color: 'var(--warn)'}}>*</span>
                </div>
                <div style={{display: 'flex', alignItems: 'center', gap: 16}}>
                    <input type="range" min="5" max="100" step="5"
                           value={d.propStake ?? 100}
                           onChange={e => set('propStake', +e.target.value)}
                           style={{flex: 1, accentColor: 'var(--accent-ink)', height: 6}}/>
                    <div className="g-num" style={{fontSize: 26, fontWeight: 700, minWidth: 64, textAlign: 'right'}}>
                        {d.propStake ?? 100}%
                    </div>
                </div>
                {(d.propStake ?? 100) < 100 && (
                    <div style={{marginTop: 10, display: 'flex', flexDirection: 'column', gap: 8}}>
                        <div style={{
                            fontSize: 12.5,
                            color: 'var(--info)',
                            background: 'var(--info-bg)',
                            padding: '10px 14px',
                            borderRadius: 'var(--r-sm)',
                            lineHeight: 1.5
                        }}>
                            Co-owners must register on Gigi and attest their stake. Advances on this property
                            require <b>majority consent (&gt;50%)</b> before disbursement.
                        </div>
                        <Input label="Co-owner email (invite)" placeholder="coowner@email.com"
                               value={d.coOwnerEmail} onChange={v => set('coOwnerEmail', v)}
                               hint="They'll receive an email to register and confirm their stake."/>
                    </div>
                )}
            </div>

            <div>
                <div style={{fontSize: 12.5, fontWeight: 600, color: 'var(--ink-2)', marginBottom: 8}}>Property
                    description (optional)
                </div>
                <textarea value={d.propDesc || ''} onChange={e => set('propDesc', e.target.value)}
                          placeholder="Year built, number of floors, amenities, parking…"
                          style={{
                              width: '100%', height: 88, borderRadius: 'var(--r-sm)', border: '1.5px solid var(--line)',
                              background: 'var(--surface)', padding: '12px 14px', fontFamily: 'var(--ff)', fontSize: 14,
                              color: 'var(--ink)', resize: 'vertical', outline: 'none', lineHeight: 1.5
                          }}/>
            </div>
        </div>
    );
}

// ── Step 3: Documents ──────────────────────────────────────────
function APStepDocs({d, set}) {
    const G = window.GIGI;
    const isCommercial = d.propType === 'office' || d.propType === 'apartment_block';
    const [uploads, setUploads] = React.useState({});
    const mark = (key) => {
        const next = {...uploads, [key]: true};
        setUploads(next);
        set('uploads', next);
    };

    const required = [
        {
            key: 'title_deed',
            label: 'Title Deed',
            hint: 'Original or certified copy — clearly shows LR number and registered owner'
        },
        {
            key: 'ownership',
            label: 'Land Registry Search Certificate',
            hint: 'Official search from Lands Registry, within the last 30 days'
        },
    ];
    const conditional = isCommercial ? [
        {
            key: 'master_lease',
            label: 'Master Lease / Occupancy Certificate',
            hint: 'Required for commercial and multi-unit properties'
        },
    ] : [];
    const optional = [
        {key: 'insurance', label: 'Insurance Certificate', hint: 'Not required but improves trust score'},
        {key: 'valuation', label: 'Property Valuation Report', hint: 'Registered valuer report (within 2 years)'},
    ];

    return (
        <div style={{display: 'flex', flexDirection: 'column', gap: 14}}>
            <SectionLabel>Required documents</SectionLabel>
            {[...required, ...conditional].map(doc => (
                <FileUpload key={doc.key} label={doc.label} hint={doc.hint}
                            uploaded={!!uploads[doc.key]} filename={doc.label.split(' ').slice(0, 2).join('_') + '.pdf'}
                            onUpload={() => mark(doc.key)}/>
            ))}

            <SectionLabel>Optional (improve verification speed)</SectionLabel>
            {optional.map(doc => (
                <FileUpload key={doc.key} label={doc.label} hint={doc.hint}
                            uploaded={!!uploads[doc.key]} filename={doc.label.split(' ').slice(0, 2).join('_') + '.pdf'}
                            onUpload={() => mark(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="ardhi" size={16} style={{flexShrink: 0, marginTop: 2}}/>
                    <div>After submission, Gigi runs an <b style={{color: 'var(--ink)'}}>Ardhi Sasa</b> title
                        verification automatically. Most properties are verified within 24–48 hours.
                    </div>
                </div>
            </Card>
        </div>
    );
}

// ── Step 4: Unit configuration (conditional) ───────────────────
function APStepUnits({d, set}) {
    const G = window.GIGI;
    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(p => ({...p, id: '', rent: ''}));
    };

    const totalRent = units.reduce((s, u) => s + Number(u.rent || 0), 0);
    const advEst = G.quoteAdvance(totalRent, 3);

    return (
        <div style={{display: 'flex', flexDirection: 'column', gap: 16}}>
            {/* Add unit form */}
            <Card>
                <div style={{fontWeight: 700, fontSize: 14.5, marginBottom: 14}}>Add a unit</div>
                <div className="g-2col" style={{marginBottom: 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 = Ground" value={draft.floor}
                           onChange={v => setDraft(p => ({...p, floor: v}))} mono/>
                </div>
                <div className="g-2col" style={{marginBottom: 14}}>
                    <Select label="Unit type" value={draft.type} onChange={v => setDraft(p => ({...p, type: v}))}
                            options={typeOpts}/>
                    <Input label="Monthly rent" placeholder="95000" value={draft.rent}
                           onChange={v => setDraft(p => ({...p, rent: v}))} mono prefix="KES"/>
                </div>
                <Btn kind="ghost" icon="plus" onClick={addUnit} disabled={!draft.id || !draft.rent} full>Add unit</Btn>
            </Card>

            {/* Units list */}
            {units.length > 0 && (
                <div>
                    <SectionLabel>{units.length} unit{units.length !== 1 ? 's' : ''} · {G.fmtKES(totalRent)}/mo
                        total</SectionLabel>
                    <Card style={{padding: 0}}>
                        {units.map((u, i) => (
                            <div key={u.id} style={{
                                display: 'flex', alignItems: 'center', gap: 12, padding: '13px 16px',
                                borderBottom: i < units.length - 1 ? '1px solid var(--line-2)' : 'none'
                            }}>
                                <div className="g-mono" style={{
                                    width: 48, height: 38, borderRadius: 9, background: 'var(--surface-2)',
                                    display: 'grid', placeItems: 'center', fontSize: 13, fontWeight: 700, flexShrink: 0
                                }}>{u.id}</div>
                                <div style={{flex: 1}}>
                                    <div style={{fontWeight: 600, fontSize: 14}}>{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 n = units.filter((_, j) => j !== i);
                                    setUnits(n);
                                    set('units', n);
                                }}
                                        className="g-tap" style={{
                                    border: 'none',
                                    background: 'transparent',
                                    color: 'var(--ink-3)',
                                    cursor: 'pointer',
                                    padding: 4
                                }}>
                                    <Icon name="x" size={16}/>
                                </button>
                            </div>
                        ))}
                    </Card>

                    {/* Advance preview */}
                    <Card style={{
                        background: 'var(--surface-2)',
                        boxShadow: 'none',
                        padding: '12px 16px',
                        marginTop: 10
                    }}>
                        <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center'}}>
                            <div style={{fontSize: 13, color: 'var(--ink-2)'}}>Estimated advance at 100% occupancy</div>
                            <div className="g-num" style={{fontSize: 17, fontWeight: 700, color: 'var(--accent-ink)'}}>
                                {G.fmtKES(advEst.gross, {compact: true})}
                            </div>
                        </div>
                        <div style={{fontSize: 12, color: 'var(--ink-3)', marginTop: 4}}>60%
                            × {G.fmtKES(totalRent, {compact: true})}/mo × 3 months · after verification
                        </div>
                    </Card>
                </div>
            )}

            {units.length === 0 && (
                <Card style={{background: 'var(--warn-bg)', boxShadow: 'none', padding: '12px 14px'}}>
                    <div style={{display: 'flex', gap: 9, color: 'var(--warn)', fontSize: 13, lineHeight: 1.5}}>
                        <Icon name="info" size={16} style={{flexShrink: 0, marginTop: 2}}/>
                        At least one unit is required. You need ≥85% occupancy to qualify for a capital advance.
                    </div>
                </Card>
            )}
        </div>
    );
}

// ── Step 5: Review ─────────────────────────────────────────────
function APStepReview({d}) {
    const G = window.GIGI;
    const pt = G.PROP_TYPES[d.propType];
    const totalRent = (d.units || []).reduce((s, u) => s + Number(u.rent || 0), 0);

    return (
        <div style={{display: 'flex', flexDirection: 'column', gap: 16}}>
            <Card style={{background: 'var(--surface-2)', boxShadow: 'none', padding: '12px 14px'}}>
                <div style={{fontSize: 13, color: 'var(--ink-2)', lineHeight: 1.55}}>
                    Review the details below before submitting. Once submitted, an Ardhi Sasa verification begins
                    immediately and <b style={{color: 'var(--ink)'}}>cannot be cancelled</b>.
                </div>
            </Card>

            <div>
                <SectionLabel>Property</SectionLabel>
                <Card>
                    <Field label="Name" value={d.propName || '—'}/>
                    <Field label="Type" value={pt?.label || '—'}/>
                    <Field label="Address" value={d.propAddress || '—'}/>
                    <Field label="LR number" value={d.propLR || '—'} mono/>
                    <Field label="County" value={d.propCounty || 'Nairobi'}/>
                    <Field label="Your stake" value={(d.propStake ?? 100) + '%'} last/>
                </Card>
            </div>

            {(d.units || []).length > 0 && (
                <div>
                    <SectionLabel>{d.units.length} units · {G.fmtKES(totalRent)}/mo</SectionLabel>
                    <Card>
                        {d.units.map((u, i) => (
                            <Field key={u.id} label={`${u.id} · ${u.type} · Floor ${u.floor}`}
                                   value={G.fmtKES(Number(u.rent))} mono last={i === d.units.length - 1}/>
                        ))}
                    </Card>
                </div>
            )}

            <div>
                <SectionLabel>Documents</SectionLabel>
                <Card>
                    {Object.keys(d.uploads || {}).length === 0
                        ?
                        <div style={{color: 'var(--warn)', fontSize: 13.5, padding: '4px 0'}}>No documents uploaded yet
                            — required before verification can begin.</div>
                        : Object.entries(d.uploads || {}).map(([k, v], i, arr) => (
                            <Field key={k} label={k.replace(/_/g, ' ').replace(/\b\w/g, c => c.toUpperCase())}
                                   value={<Badge tone="go" dot>Uploaded</Badge>} last={i === arr.length - 1}/>
                        ))
                    }
                </Card>
            </div>

            <Card style={{background: 'var(--go-bg)', boxShadow: 'none', padding: '14px 16px'}}>
                <div style={{display: 'flex', gap: 10, color: 'var(--go)', fontSize: 13.5, lineHeight: 1.55}}>
                    <Icon name="ardhi" size={18} style={{flexShrink: 0, marginTop: 2}}/>
                    <div>Ardhi Sasa verification runs automatically after submission. You'll be notified by email +
                        in-app once complete. Typical SLA: <b>24–48 hours.</b></div>
                </div>
            </Card>
        </div>
    );
}

// ── Success screen ─────────────────────────────────────────────
function APSuccess({d, onDone}) {
    const G = window.GIGI;
    const pt = G.PROP_TYPES[d.propType];
    return (
        <div style={{
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            textAlign: 'center',
            padding: '24px 0'
        }}>
            <div style={{
                width: 80,
                height: 80,
                borderRadius: 22,
                background: 'var(--accent)',
                display: 'grid',
                placeItems: 'center',
                marginBottom: 20
            }}>
                <Icon name="check" size={40} stroke={2.5} style={{color: 'var(--accent-ink)'}}/>
            </div>
            <h2 className="g-num" style={{fontSize: 28, fontWeight: 700, margin: '0 0 10px', lineHeight: 1.1}}>Property
                submitted!</h2>
            <p style={{fontSize: 15, color: 'var(--ink-2)', lineHeight: 1.6, margin: '0 0 28px', maxWidth: 400}}>
                <b style={{color: 'var(--ink)'}}>{d.propName}</b> ({pt?.label}) has been submitted for Ardhi Sasa title
                verification.
                You'll receive a notification once it's complete — usually <b style={{color: 'var(--ink)'}}>24–48
                hours</b>.
            </p>
            <div style={{width: '100%', maxWidth: 380, display: 'flex', flexDirection: 'column', gap: 10}}>
                <Card style={{
                    display: 'flex',
                    alignItems: 'center',
                    gap: 12,
                    textAlign: 'left',
                    background: 'var(--surface-2)',
                    boxShadow: 'none'
                }}>
                    <div style={{
                        width: 38,
                        height: 38,
                        borderRadius: 10,
                        background: 'var(--info-bg)',
                        display: 'grid',
                        placeItems: 'center',
                        color: 'var(--info)',
                        flexShrink: 0
                    }}><Icon name="clock" size={20}/></div>
                    <div>
                        <div style={{fontWeight: 700, fontSize: 14}}>Verification in progress</div>
                        <div style={{fontSize: 12.5, color: 'var(--ink-3)', marginTop: 2}}>Ardhi Sasa · 24–48 hour SLA
                        </div>
                    </div>
                </Card>
                <Card style={{
                    display: 'flex',
                    alignItems: 'center',
                    gap: 12,
                    textAlign: 'left',
                    background: 'var(--surface-2)',
                    boxShadow: 'none'
                }}>
                    <div style={{
                        width: 38,
                        height: 38,
                        borderRadius: 10,
                        background: 'var(--warn-bg)',
                        display: 'grid',
                        placeItems: 'center',
                        color: 'var(--warn)',
                        flexShrink: 0
                    }}><Icon name="users" size={20}/></div>
                    <div>
                        <div style={{fontWeight: 700, fontSize: 14}}>Next: add a tenant</div>
                        <div style={{fontSize: 12.5, color: 'var(--ink-3)', marginTop: 2}}>Required to unlock capital
                            advances
                        </div>
                    </div>
                </Card>
            </div>
            <div style={{marginTop: 24, width: '100%', maxWidth: 380, display: 'flex', gap: 10}}>
                <Btn kind="primary" full onClick={onDone}>View in portfolio</Btn>
            </div>
        </div>
    );
}

// ── Main AddPropertyWizard ─────────────────────────────────────
function AddPropertyWizard({onBack, onDone}) {
    const G = window.GIGI;
    const [d, setD] = React.useState({propType: 'apartment_block', propStake: 100, units: [], uploads: {}});
    const [step, setStep] = React.useState(0);
    const [submitted, setSubmitted] = React.useState(false);
    const set = (k, v) => setD(p => ({...p, [k]: v}));

    const isMulti = d.propType && G.PROP_TYPES[d.propType]?.multi;

    const steps = React.useMemo(() => [
        'Property type',
        'Details',
        'Documents',
        ...(isMulti ? ['Configure units'] : []),
        'Review',
    ], [isMulti]);

    const isLast = step === steps.length - 1;

    const nextDisabled =
        (step === 0 && !d.propType) ||
        (step === 1 && (!d.propName || !d.propLR));

    if (submitted) return <APSuccess d={d} onDone={onDone}/>;

    return (
        <div style={{
            display: 'flex',
            flexDirection: 'column',
            height: '100%',
            background: 'var(--sand)',
            overflow: 'hidden'
        }}>
            {/* Progress */}
            <div style={{flexShrink: 0, display: 'flex', height: 4}}>
                {steps.map((_, i) => (
                    <div key={i} style={{
                        flex: 1, marginRight: 2, borderRadius: 999,
                        background: i < step ? 'rgba(200,218,63,.5)' : i === step ? 'var(--accent-ink)' : 'var(--line)',
                        transition: 'background .3s'
                    }}/>
                ))}
            </div>

            {/* Header */}
            <div style={{flexShrink: 0, padding: '20px 28px 0'}}>
                <div className="g-wiz-wrap" style={{display: 'flex', alignItems: 'center', gap: 14}}>
                    <button onClick={step === 0 ? onBack : () => setStep(s => s - 1)} className="g-tap" style={{
                        width: 38,
                        height: 38,
                        borderRadius: 12,
                        border: 'none',
                        background: 'var(--surface)',
                        display: 'grid',
                        placeItems: 'center',
                        color: 'var(--ink-2)',
                        cursor: 'pointer',
                        boxShadow: 'var(--shadow)',
                        flexShrink: 0
                    }}>
                        <Icon name="chevL" size={18}/>
                    </button>
                    <div>
                        <div style={{
                            fontSize: 11.5,
                            fontWeight: 700,
                            color: 'var(--ink-3)',
                            textTransform: 'uppercase',
                            letterSpacing: '.07em',
                            marginBottom: 4
                        }}>
                            Step {step + 1} of {steps.length} · {steps[step]}
                        </div>
                        <h1 className="g-num" style={{fontSize: 26, fontWeight: 700, margin: 0, lineHeight: 1.1}}>
                            {['What type of property?', 'Property details', 'Upload documents', isMulti ? 'Configure units' : '', 'Review & submit'][step]}
                        </h1>
                    </div>
                </div>
            </div>

            {/* Subtitle */}
            <div style={{flexShrink: 0, padding: '0 28px'}}>
                <p className="g-wiz-wrap"
                   style={{margin: '10px auto 0', fontSize: 14, color: 'var(--ink-2)', lineHeight: 1.55}}>
                    {[
                        'Different types have different verification flows and unit configurations.',
                        'Enter details exactly as they appear on the title deed — discrepancies delay verification.',
                        'Required for Ardhi Sasa title verification. Upload now or during verification.',
                        isMulti ? 'Define each rentable unit. This determines your verified rent roll and advance eligibility.' : '',
                        'Final check before submitting for Ardhi Sasa verification.'
                    ][step]}
                </p>
            </div>

            {/* Body */}
            <div className="g-scroll" style={{flex: 1, overflowY: 'auto', padding: '20px 28px 12px'}}>
                <div className="g-wiz-wrap">
                    {step === 0 && <APStepType d={d} set={set}/>}
                    {step === 1 && <APStepDetails d={d} set={set}/>}
                    {step === 2 && <APStepDocs d={d} set={set}/>}
                    {step === 3 && isMulti && <APStepUnits d={d} set={set}/>}
                    {isLast && <APStepReview d={d}/>}
                </div>
            </div>

            {/* Footer */}
            <div style={{flexShrink: 0, padding: '12px 28px calc(16px + env(safe-area-inset-bottom,0px))'}}>
                <div className="g-wiz-wrap" style={{display: 'flex', gap: 10}}>
                    <Btn kind={isLast ? 'accent' : 'primary'}
                         onClick={() => isLast ? setSubmitted(true) : setStep(s => s + 1)}
                         disabled={nextDisabled} full icon={isLast ? 'check' : undefined}>
                        {isLast ? 'Submit property' : step === 0 ? 'Continue' : 'Next'}
                    </Btn>
                </div>
            </div>
        </div>
    );
}

// ── Flow launcher (dashboard widget) ──────────────────────────
function FlowLauncher({onStartOnboarding, onAddProperty, onAddTenant}) {
    const [open, setOpen] = React.useState(true);
    if (!open) return null;

    const flows = [
        {
            icon: 'vault', label: 'Full onboarding',
            desc: 'Start here as a new property owner — entity KYC, first property, first tenant.',
            kind: 'primary', onClick: onStartOnboarding,
        },
        {
            icon: 'building', label: 'Add a property',
            desc: 'Register a new property in your existing portfolio.',
            kind: 'ghost', onClick: onAddProperty,
        },
        {
            icon: 'users', label: 'Add a tenant',
            desc: 'Onboard a tenant to an existing verified property.',
            kind: 'ghost', onClick: onAddTenant,
        },
    ];

    return (
        <Card style={{padding: 0, overflow: 'hidden', marginBottom: 28, border: '1.5px solid var(--line)'}}>
            <div style={{
                background: 'var(--accent-ink)',
                color: '#fff',
                padding: '18px 20px',
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'flex-start'
            }}>
                <div>
                    <div style={{display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6}}>
                        <Icon name="bolt" size={16} style={{color: 'var(--accent)'}}/>
                        <span style={{
                            fontSize: 12.5,
                            fontWeight: 700,
                            color: 'var(--pill-ink)',
                            letterSpacing: '.04em',
                            textTransform: 'uppercase'
                        }}>Test flows</span>
                    </div>
                    <h3 className="g-num" style={{margin: 0, fontSize: 20, fontWeight: 700}}>Launch a workflow</h3>
                    <p style={{margin: '6px 0 0', fontSize: 13.5, color: 'rgba(255,255,255,.7)', lineHeight: 1.45}}>
                        Click any flow below to walk through the full onboarding or registration experience.
                    </p>
                </div>
                <button onClick={() => setOpen(false)} className="g-tap" style={{
                    border: 'none',
                    background: 'rgba(255,255,255,.12)',
                    width: 30,
                    height: 30,
                    borderRadius: 9,
                    display: 'grid',
                    placeItems: 'center',
                    color: 'rgba(255,255,255,.7)',
                    cursor: 'pointer'
                }}>
                    <Icon name="x" size={15}/>
                </button>
            </div>
            <div style={{padding: '16px 20px', display: 'flex', flexDirection: 'column', gap: 10}}>
                {flows.map(f => (
                    <div key={f.label} onClick={f.onClick} className="g-tap" style={{
                        display: 'flex', alignItems: 'center', gap: 14, padding: '14px 16px',
                        borderRadius: 'var(--r-md)', border: '1.5px solid var(--line)',
                        background: 'var(--surface)', cursor: 'pointer'
                    }}>
                        <div style={{
                            width: 42, height: 42, borderRadius: 12, background: 'var(--surface-2)',
                            display: 'grid', placeItems: 'center', color: 'var(--ink-2)', flexShrink: 0
                        }}>
                            <Icon name={f.icon} size={22}/>
                        </div>
                        <div style={{flex: 1}}>
                            <div style={{fontWeight: 700, fontSize: 14.5}}>{f.label}</div>
                            <div style={{
                                fontSize: 12.5,
                                color: 'var(--ink-3)',
                                marginTop: 2,
                                lineHeight: 1.4
                            }}>{f.desc}</div>
                        </div>
                        <div style={{
                            background: 'var(--accent-ink)', color: 'var(--pill-ink)', borderRadius: 999,
                            padding: '6px 14px', fontSize: 13, fontWeight: 700, whiteSpace: 'nowrap', flexShrink: 0
                        }}>
                            Launch →
                        </div>
                    </div>
                ))}
            </div>
        </Card>
    );
}

Object.assign(window, {AddPropertyWizard, FlowLauncher});
