/* ============================================================
   Magic — Focus Picker Modal (Phase 5d)
   
   Uses EntityPicker to browse the 7 focus categories, with
   inline configuration (Force stepper, subtype selector,
   spell category / spirit type selector) on the detail panel.
   ============================================================ */
const { useState, useEffect, useRef, useMemo, useCallback, Fragment } = React;

window.FocusPickerModal = function FocusPickerModal({ character, onPick, onClose }) {
    const M = SR5_MAGIC;
    const C = SR5_CALC;

    const allowed = C.allowedFocusCategories(character);
    const magic = C.specialAttributeValue(character, 'mag');

    /* Per-category state: force + subtype + spellCategory + spiritType */
    const [config, setConfig] = useState({});
    function cfg(key, field, value) {
        setConfig(s => ({ ...s, [key]: { ...(s[key] || {}), [field]: value } }));
    }
    function getCfg(key) {
        return config[key] || {};
    }

    function handlePick(cat) {
        const c = getCfg(cat.key);
        const force = Math.max(1, c.force || 1);
        const payload = {
            categoryKey: cat.key,
            force,
            subtypeKey: c.subtypeKey || (cat.subtypes?.[0]?.key) || null,
            spellCategory: cat.key === 'spell' ? (c.spellCategory || M.SPELL_FOCUS_CATEGORIES[0]) : null,
            spiritType: cat.key === 'spirit' ? (c.spiritType || M.COMMON_SPIRIT_TYPES[0]) : null,
            bonded: c.bonded !== false,
        };
        onPick(payload);
    }

    return (
        <EntityPicker
            title="Browse Foci"
            items={allowed}
            getItemKey={c => c.key}
            filterBy={(c, query) => {
                if (!query) return true;
                const q = query.toLowerCase();
                return (c.label + ' ' + c.description).toLowerCase().includes(q);
            }}
            isBlocked={cat => {
                const force = Math.max(1, getCfg(cat.key).force || 1);
                return !C.availAllowedForCharacter(character, M.focusAvail(cat.key, force));
            }}
            blockedReason={cat => {
                const force = Math.max(1, getCfg(cat.key).force || 1);
                return `Availability ${M.focusAvail(cat.key, force)} exceeds creation cap of ${C.CREATION_AVAIL_CAP} (lower the Force)`;
            }}
            itemRenderer={(c, { selected, blocked, onClick }) => {
                const force = getCfg(c.key).force || 1;
                return (
                    <div key={c.key}
                         className={`picker-item ${selected ? 'selected' : ''} ${blocked ? 'blocked' : ''}`}
                         onClick={onClick}
                         title={blocked ? `Availability over creation cap at F${force}` : undefined}>
                        <span className="pi-name">{c.label}</span>
                        <span className="pi-cost">
                            {c.karmaPerF * force}k · {(c.costPerF * force).toLocaleString()}¥
                        </span>
                        <div className="pi-meta">
                            F{force} · {c.karmaPerF}k/F · {c.costPerF.toLocaleString()}¥/F
                        </div>
                    </div>
                );
            }}
            renderDetails={(cat) => {
                const c = getCfg(cat.key);
                const force = Math.max(1, c.force || 1);
                const subtypeKey = c.subtypeKey || (cat.subtypes?.[0]?.key) || null;
                const spellCategory = c.spellCategory || M.SPELL_FOCUS_CATEGORIES[0];
                const spiritType = c.spiritType || M.COMMON_SPIRIT_TYPES[0];
                const karma = M.focusKarmaCost(cat.key, force);
                const nuyen = M.focusNuyenCost(cat.key, force);
                const avail = M.focusAvail(cat.key, force);
                const selectedSubtype = cat.subtypes?.find(s => s.key === subtypeKey);

                return (
                    <>
                        <h3 className="picker-details-title">{cat.label}</h3>
                        <div className="weapon-stat-grid">
                            <div className="ws"><span className="ws-label">Karma</span><span className="ws-value accent">{karma}</span></div>
                            <div className="ws"><span className="ws-label">Nuyen</span><span className="ws-value accent">{nuyen.toLocaleString()}¥</span></div>
                            <div className="ws"><span className="ws-label">Avail</span><span className="ws-value">{avail}</span></div>
                            <div className="ws"><span className="ws-label">Formula</span>
                                <span className="ws-value" style={{ fontSize: 11 }}>
                                    K:F×{cat.karmaPerF} · ¥:F×{cat.costPerF.toLocaleString()}
                                </span>
                            </div>
                        </div>

                        <div className="picker-details-section">
                            <div className="picker-details-label">Description</div>
                            <div className="picker-details-text">{cat.description}</div>
                        </div>

                        <div className="picker-details-section">
                            <div className="picker-details-label">Force</div>
                            <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                                <RatingStepper
                                    value={force}
                                    min={1}
                                    max={12}
                                    onChange={(n) => cfg(cat.key, 'force', n)}
                                    stopPropagation
                                />
                                <span className="muted" style={{ fontSize: 11 }}>
                                    (Your Magic is {magic}; suggested max Force = Magic)
                                </span>
                            </div>
                        </div>

                        {cat.subtypes && (
                            <div className="picker-details-section">
                                <div className="picker-details-label">Sub-type</div>
                                <select className="input"
                                        value={subtypeKey || ''}
                                        onChange={e => cfg(cat.key, 'subtypeKey', e.target.value)}>
                                    {cat.subtypes.map(s => (
                                        <option key={s.key} value={s.key}>{s.label}</option>
                                    ))}
                                </select>
                                {selectedSubtype && (
                                    <div className="muted" style={{ fontSize: 11, marginTop: 6, fontStyle: 'italic' }}>
                                        {selectedSubtype.description}
                                    </div>
                                )}
                            </div>
                        )}

                        {cat.key === 'spell' && (
                            <div className="picker-details-section">
                                <div className="picker-details-label">Spell category</div>
                                <select className="input"
                                        value={spellCategory}
                                        onChange={e => cfg(cat.key, 'spellCategory', e.target.value)}>
                                    {M.SPELL_FOCUS_CATEGORIES.map(sc => (
                                        <option key={sc} value={sc}>{sc.charAt(0).toUpperCase() + sc.slice(1)}</option>
                                    ))}
                                </select>
                                <div className="muted" style={{ fontSize: 11, marginTop: 6 }}>
                                    This focus only works with spells in the chosen category.
                                </div>
                            </div>
                        )}

                        {cat.key === 'spirit' && (
                            <div className="picker-details-section">
                                <div className="picker-details-label">Spirit type</div>
                                <input className="input"
                                       value={spiritType}
                                       onChange={e => cfg(cat.key, 'spiritType', e.target.value)}
                                       list={`spirit-types-${cat.key}`}
                                       placeholder="e.g. Fire, Earth, Beasts" />
                                <datalist id={`spirit-types-${cat.key}`}>
                                    {M.COMMON_SPIRIT_TYPES.map(t => <option key={t} value={t} />)}
                                </datalist>
                                <div className="muted" style={{ fontSize: 11, marginTop: 6 }}>
                                    This focus only works with spirits of the chosen type.
                                </div>
                            </div>
                        )}

                        {cat.key === 'qi' && (
                            <div className="picker-details-section">
                                <div className="picker-details-label muted" style={{ fontSize: 10 }}>Note</div>
                                <div className="muted" style={{ fontSize: 11, fontStyle: 'italic' }}>
                                    Qi foci channel a specific adept power. Force must be 4× the PP cost of the power it
                                    holds (e.g. a Level 1 Improved Reflexes Qi focus is Force 6). Edit the focus name
                                    after purchase to specify which power.
                                </div>
                            </div>
                        )}
                    </>
                );
            }}
            onPick={(cat) => handlePick(cat)}
            onClose={onClose}
        />
    );
};
