/* ============================================================
   Gear — Equipment Tab
   Extracted from components.jsx via split.py.
   Each component reaches React hooks via window.React.
   ============================================================ */
const { useState, useEffect, useRef, useMemo, useCallback, Fragment } = React;


/* ------------------------------------------------------------
   EquipmentTab — generic browser for Electronics / Security /
   Medical / Misc. All four share the same UI: catalog picker
   with category filter chips + current inventory table.
   ------------------------------------------------------------ */
window.EquipmentTab = function EquipmentTab({ character, onChange, kind }) {
    const C = SR5_CALC;
    const E = SR5_EQUIPMENT;
    const [pickerOpen, setPickerOpen] = useState(false);
    const [customOpen, setCustomOpen] = useState(false);

    const inCareer = C.isCareerMode(character);
    const pendingGear = inCareer ? window.CareerGear.pendingOfKind(character, kind) : [];

    const labels = {
        electronics: { title: 'Electronics',  hint: 'Commlinks, cyberdecks, RCCs, programs, accessories', catalog: E.ELECTRONICS, categories: E.ELECTRONICS_CATEGORIES },
        security:    { title: 'Security',     hint: 'Sensors, locks, restraints, countermeasures',        catalog: E.SECURITY,    categories: E.SECURITY_CATEGORIES },
        medical:     { title: 'Medical',      hint: 'Medkits, patches, DocWagon contracts, drugs',        catalog: E.MEDICAL,     categories: E.MEDICAL_CATEGORIES },
        misc:        { title: 'Misc',         hint: 'Tools, survival gear, explosives, grenades, containers', catalog: E.MISC,    categories: E.MISC_CATEGORIES },
    };
    const meta = labels[kind];
    const items = C.characterEquipment(character, kind);

    function onPick(tpl, opts) {
        if (inCareer) {
            /* Compute cost: template cost scaled by rating if rated. */
            const rating = opts?.rating || tpl.ratingRange?.[0] || 1;
            const baseCost = typeof tpl.cost === 'number' ? tpl.cost : 0;
            const cost = tpl.ratingRange ? baseCost * rating : baseCost;
            if (!window.CareerGear.canAfford(character, cost)) {
                alert(`Not enough nuyen: ${tpl.name} costs ${cost.toLocaleString()}¥.`);
                return;
            }
            onChange(C.stagePendingGear(character, {
                kind,
                templateKey: tpl.key,
                name: tpl.name,
                nuyenCost: cost,
                extras: opts || {},
            }));
        } else {
            onChange(C.addEquipmentFromTemplate(character, kind, tpl.key, opts || {}));
        }
        setPickerOpen(false);
    }

    function onAddCustom(payload) {
        onChange(C.addCustomEquipment(character, kind, payload));
        setCustomOpen(false);
    }

    function onRemove(id) {
        if (inCareer) { alert("Use career log for removed/sold equipment."); return; }
        onChange(C.removeEquipment(character, kind, id));
    }

    function onUnstage(tempId) {
        onChange(C.unstagePendingGear(character, tempId));
    }

    function onChangeRating(id, newRating) {
        if (inCareer) return;
        onChange(C.updateEquipment(character, kind, id, { rating: newRating }));
    }

    return (
        <>
            <div className="equip-actions">
                <button className="btn btn-primary" onClick={() => setPickerOpen(true)}>+ Browse {meta.title}</button>
                {!inCareer && (
                    <button className="btn btn-ghost" onClick={() => setCustomOpen(true)}>+ Custom Item</button>
                )}
            </div>

            {items.length === 0 && pendingGear.length === 0 ? (
                <div className="equip-empty">No {meta.title.toLowerCase()} items. {meta.hint}.</div>
            ) : (
                <div className="equip-table">
                    <div className="equip-head">
                        <span>Name</span>
                        <span>Category</span>
                        <span style={{ textAlign: 'center' }}>Rating</span>
                        <span style={{ textAlign: 'center' }}>Avail</span>
                        <span style={{ textAlign: 'right' }}>Cost</span>
                        <span></span>
                    </div>
                    {items.map(item => {
                        const tpl = item.key ? E.findItem(item.key) : null;
                        const isRated = tpl && tpl.ratingRange;
                        return (
                            <React.Fragment key={item.id}>
                                <div className="equip-row">
                                    <div className="er-name">{item.name}{!item.key && <span className="linked-badge">Custom</span>}</div>
                                    <div className="er-cat">{item.category}</div>
                                    <div>
                                        {isRated ? (
                                            <RatingStepper
                                                value={item.rating || tpl.ratingRange[0]}
                                                min={tpl.ratingRange[0]}
                                                max={tpl.ratingRange[1]}
                                                onChange={(n) => onChangeRating(item.id, n)}
                                                disabled={inCareer}
                                            />
                                        ) : (
                                            <div className="er-rating">{item.rating || '—'}</div>
                                        )}
                                    </div>
                                    <div className="er-avail">{item.avail || '—'}</div>
                                    <div className="er-cost">{(item.nuyen || 0).toLocaleString()}¥</div>
                                    <button className="btn-row-remove"
                                            onClick={() => onRemove(item.id)}
                                            title={inCareer ? "Use career log" : "Remove"}>×</button>
                                    {item.description && <div className="equip-row-desc">{item.description}</div>}
                                </div>
                            </React.Fragment>
                        );
                    })}
                    {pendingGear.map(pg => {
                        const tpl = E.findItem(pg.templateKey);
                        return (
                            <div className="equip-row pending-new" key={pg.tempId}>
                                <div className="er-name">
                                    {pg.name}
                                    <span className="gear-pending-tag">pending</span>
                                </div>
                                <div className="er-cat">{tpl?.category || '—'}</div>
                                <div className="er-rating">{pg.extras?.rating || '—'}</div>
                                <div className="er-avail">{tpl?.avail || '—'}</div>
                                <div className="er-cost" style={{ color: 'var(--accent)' }}>{(pg.nuyenCost || 0).toLocaleString()}¥</div>
                                <button className="btn-row-remove"
                                        onClick={() => onUnstage(pg.tempId)}
                                        title="Discard pending">×</button>
                            </div>
                        );
                    })}
                </div>
            )}

            {pickerOpen && (
                <EquipmentPickerModal
                    catalog={meta.catalog}
                    categories={meta.categories}
                    title={meta.title}
                    character={character}
                    kind={kind}
                    onPick={onPick}
                    onClose={() => setPickerOpen(false)}
                />
            )}

            {customOpen && (
                <CustomEquipmentModal
                    kind={kind}
                    title={meta.title}
                    categories={meta.categories}
                    onAdd={onAddCustom}
                    onClose={() => setCustomOpen(false)}
                />
            )}
        </>
    );
};
