/* ============================================================
   Lifestyle View (Phase 14)

   SR5 CRB p. 373. Pick one of six lifestyle tiers. Pay first
   month's rent from starting nuyen; metatype modifier applies
   (Dwarf +20%, Troll +100%). Career mode locks the tier but
   lets you change notes / months-ahead; changing the tier
   mid-career is a fiction decision (move up, slum down) and
   is out of scope for Phase 14.
   ============================================================ */
const { useState, useEffect, useRef, useMemo, useCallback, Fragment } = React;

window.LifestyleView = function LifestyleView({ character, onChange }) {
    const C = SR5_CALC;
    const D = SR5_DATA;
    const tiers = C.LIFESTYLE_TIERS;
    const inCareer = C.isCareerMode(character);
    const currentTier = character?.lifestyle?.tier || null;
    const months = character?.lifestyle?.months || 1;
    const notes = character?.lifestyle?.notes || '';
    const multiplier = C.lifestyleMultiplier(character);
    const mtype = D.METATYPES[character?.identity?.metatype];
    const startingCost = C.lifestyleStartingCost(character);

    function pickTier(key) {
        if (inCareer) return;
        if (currentTier === key) {
            /* clicking the selected tier clears it */
            onChange(C.setLifestyleTier(character, null));
            return;
        }
        onChange(C.setLifestyleTier(character, key));
    }

    return (
        <>
            <div className="content-header">
                <div className="content-title">08 / Lifestyle</div>
                <h2 className="content-heading">Where the runner lives</h2>
            </div>

            {inCareer && (
                <div className="priorities-locked-banner" style={{ marginBottom: 16 }}>
                    <span className="plb-icon">🔒</span>
                    <span>
                        <strong>Lifestyle locked in career mode.</strong> Moving up (or slumming down)
                        is a fiction decision and a career-log event, not a creation edit. The monthly
                        rent continues to drain from your bank per session.
                    </span>
                </div>
            )}

            <div className="card">
                <div className="card-header">
                    <h3 className="card-title">Monthly rent tier</h3>
                </div>
                <div className="card-body">
                    <p className="muted" style={{ margin: '0 0 14px 0', fontSize: 12 }}>
                        Pick one tier. First month's rent is deducted from your starting nuyen —
                        after that, you're responsible for paying it yourself each in-game month.
                        {mtype && multiplier !== 1.0 && (
                            <>
                                {' '}Your metatype adjusts lifestyle cost by <strong className="accent">
                                    ×{multiplier.toFixed(1)}
                                </strong>{' '}
                                ({mtype.name}).
                            </>
                        )}
                    </p>
                    <div className="lifestyle-grid">
                        {tiers.map(t => {
                            const isSelected = currentTier === t.key;
                            const adjustedCost = Math.round(t.monthly * multiplier);
                            return (
                                <div key={t.key}
                                     className={`lifestyle-tile ${isSelected ? 'selected' : ''} ${inCareer && !isSelected ? 'disabled' : ''}`}
                                     onClick={() => pickTier(t.key)}>
                                    <div className="lt-head">
                                        <span className="lt-name">{t.label}</span>
                                        <span className="lt-cost">
                                            {adjustedCost === 0 ? 'free' : `${adjustedCost.toLocaleString()}¥/mo`}
                                        </span>
                                    </div>
                                    {multiplier !== 1.0 && t.monthly > 0 && (
                                        <div className="lt-base">
                                            base {t.monthly.toLocaleString()}¥ × {multiplier.toFixed(1)}
                                        </div>
                                    )}
                                    <div className="lt-desc">{t.description}</div>
                                    {isSelected && (
                                        <div className="lt-selected-badge">✓ selected</div>
                                    )}
                                </div>
                            );
                        })}
                    </div>
                </div>
            </div>

            {currentTier && (
                <div className="card" style={{ marginTop: 14 }}>
                    <div className="card-header">
                        <h3 className="card-title">Rent paid at creation</h3>
                    </div>
                    <div className="card-body">
                        <div style={{ display: 'grid', gridTemplateColumns: 'auto 1fr', gap: 12, alignItems: 'center' }}>
                            <label style={{ fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.1em',
                                           color: 'var(--text-muted)', textTransform: 'uppercase' }}>
                                Months paid
                            </label>
                            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                                <RatingStepper
                                    value={months}
                                    min={1}
                                    max={12}
                                    onChange={(n) => !inCareer && onChange(C.setLifestyleMonths(character, n))}
                                />
                                <span className="muted mono" style={{ fontSize: 12 }}>
                                    × {C.lifestyleMonthlyRent(character).toLocaleString()}¥ =
                                    <strong className="accent" style={{ marginLeft: 6 }}>
                                        {startingCost.toLocaleString()}¥
                                    </strong>
                                    <span style={{ marginLeft: 8, fontSize: 11, color: 'var(--text-muted)' }}>
                                        {' '}deducted from starting nuyen
                                    </span>
                                </span>
                            </div>
                            <label style={{ fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.1em',
                                           color: 'var(--text-muted)', textTransform: 'uppercase' }}>
                                Location / notes
                            </label>
                            <TextArea
                                value={notes}
                                onChange={(v) => onChange(C.setLifestyleNotes(character, v))}
                                placeholder="District, address, housemates, security setup, quirks — anything the GM might use during a home-invasion scene."
                                rows={3}
                            />
                        </div>
                    </div>
                </div>
            )}

            <div className="phase-note" style={{ marginTop: 16 }}>
                <strong>Lifestyle tiers</strong> from CRB p. 373. Street is free but you're homeless.
                Squatter is a flophouse or squat, 500¥/mo. Low is a ratty apartment, 2,000¥. Middle is
                a decent place, 5,000¥. High is a proper mid-rise with doorman, 10,000¥. Luxury is a
                penthouse or corp enclave at 100,000¥/mo. Expansion books add more fine-grained
                options (Bolt-Hole, Commercial, Corporate SIN, etc.) but core six covers 95% of runners.
            </div>
        </>
    );
};
