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


/* ------------------------------------------------------------
   WareTab — shared view for cyberware and bioware.
   Props:
     kind: 'cyberware' | 'bioware'
     character, onChange: standard pair
   ------------------------------------------------------------ */
window.WareTab = function WareTab({ kind, character, onChange }) {
    const C = SR5_CALC;
    const A = SR5_AUGS;
    const [pickerOpen, setPickerOpen] = useState(false);
    const [customOpen, setCustomOpen] = useState(false);

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

    const items = kind === 'bioware' ? C.characterBioware(character) : C.characterCyberware(character);
    const templates = kind === 'bioware' ? A.BIOWARE : A.CYBERWARE;
    const categories = kind === 'bioware' ? A.CATEGORIES_BIO : A.CATEGORIES_CYBER;

    const essSpent = C.essenceSpent(character);
    const essCur = C.currentEssence(character);
    const essProjected = inCareer ? C.currentEssenceProjected(character) : essCur;
    const magicCap = C.essenceMagicCap(character);
    const essPct = (essCur / C.STARTING_ESSENCE) * 100;
    const essPctProjected = (essProjected / C.STARTING_ESSENCE) * 100;
    const essClass = essCur <= 1.0 ? 'danger' : (essCur <= 3.0 ? 'warn' : '');

    const magicRow = C.priorityRow(character, 'magic');
    const isAwakened = magicRow && magicRow.type !== 'mundane';
    const magicAttrGranted = magicRow?.magic || 0;
    const magicCapped = isAwakened && magicCap < magicAttrGranted;

    function handlePick(template, extras) {
        if (inCareer) {
            const essenceCost = window.CareerGear.computeEssenceCost(template, extras);
            const nuyenCost = window.CareerGear.computeWareNuyenCost(template, extras);
            if (!window.CareerGear.canAfford(character, nuyenCost)) {
                alert(`Not enough nuyen: ${template.name} costs ${nuyenCost.toLocaleString()}¥.`);
                return;
            }
            if (essProjected - essenceCost < 0) {
                alert(`This install would drop essence to ${(essProjected - essenceCost).toFixed(2)} — you'd burn out. Aborting.`);
                return;
            }
            onChange(C.stagePendingGear(character, {
                kind,
                templateKey: template.key,
                name: template.name,
                nuyenCost,
                essenceCost,
                extras: { grade: extras.grade || 'standard', rating: extras.rating },
            }));
        } else {
            onChange(C.addAugFromTemplate(character, template, extras.grade, extras.rating));
        }
        setPickerOpen(false);
    }
    function handleRemove(id) {
        if (inCareer) { alert("Cyberware/bioware removal requires surgery — log it in the career log."); return; }
        onChange(C.removeAug(character, kind, id));
    }
    function handleUnstage(tempId) {
        onChange(C.unstagePendingGear(character, tempId));
    }
    function handleUpdateGrade(id, grade) {
        if (inCareer) return;
        onChange(C.updateAug(character, kind, id, { grade }));
    }
    function handleUpdateRating(id, rating) {
        if (inCareer) return;
        onChange(C.updateAug(character, kind, id, { rating }));
    }
    function handleUpdateNotes(id, notes) {
        if (inCareer) return;
        onChange(C.updateAug(character, kind, id, { notes }));
    }

    function renderRow(item) {
        const tpl = item.key
            ? (kind === 'bioware' ? A.findBioware(item.key) : A.findCyberware(item.key))
            : null;
        const category = tpl?.category || item.category || '';
        const canRate = tpl && item.rating !== undefined;
        return (
            <div className={`ware-row ${kind} ${item.notes ? 'has-notes' : ''}`} key={item.id}>
                <div className="wr-name">
                    {item.name}{item.rating ? ` ${item.rating}` : ''}
                    <span className="wr-cat">{category.replace(/_/g, ' ').replace(/-/g, ' ')}</span>
                    {tpl?.description && <div className="wr-desc">{tpl.description}</div>}
                </div>
                <select className="wr-grade-select"
                        value={item.grade || 'standard'}
                        disabled={inCareer}
                        onChange={e => handleUpdateGrade(item.id, e.target.value)}>
                    {A.GRADES.filter(g => g.creation).map(g => (
                        <option key={g.key} value={g.key}>{g.label}</option>
                    ))}
                    {A.GRADES.filter(g => !g.creation).map(g => (
                        <option key={g.key} value={g.key}>{g.label}</option>
                    ))}
                </select>
                <div className="wr-stat essence">{(item.essence || 0).toFixed(2)}</div>
                <div className="wr-rating">
                    {canRate ? (
                        <>
                            <button className="stepper-btn" style={{ width: 20, height: 20, fontSize: 12 }}
                                    onClick={() => handleUpdateRating(item.id, Math.max(1, (item.rating || 1) - 1))}
                                    disabled={inCareer || (item.rating || 1) <= 1}>−</button>
                            <span style={{ minWidth: 18, textAlign: 'center', fontFamily: 'var(--font-mono)' }}>
                                {item.rating || 1}
                            </span>
                            <button className="stepper-btn" style={{ width: 20, height: 20, fontSize: 12 }}
                                    disabled={inCareer}
                                    onClick={() => handleUpdateRating(item.id, Math.min(6, (item.rating || 1) + 1))}>+</button>
                        </>
                    ) : (
                        <span className="muted mono" style={{ fontSize: 11 }}>—</span>
                    )}
                </div>
                <div className="wr-stat">{tpl?.avail ? A.adjustAvail(tpl.avail, A.findGrade(item.grade || 'standard').availMod) : '—'}</div>
                <div className="wr-stat cost">{(item.nuyen || 0).toLocaleString()}¥</div>
                <button className="knowledge-remove-btn"
                        onClick={() => { if (confirm(`Remove ${item.name}?`)) handleRemove(item.id); }}
                        title={inCareer ? "Surgery required — use career log" : "Remove"}>×</button>
                <div className="wr-notes-row">
                    <input className="qr-notes-input"
                           type="text"
                           value={item.notes || ''}
                           disabled={inCareer}
                           onChange={e => handleUpdateNotes(item.id, e.target.value)}
                           placeholder="notes — specific model, customization, sub-implants…" />
                </div>
            </div>
        );
    }

    function renderPendingRow(pg) {
        const tpl = kind === 'bioware' ? A.findBioware(pg.templateKey) : A.findCyberware(pg.templateKey);
        return (
            <div className={`ware-row ${kind} pending-new`} key={pg.tempId}>
                <div className="wr-name">
                    {pg.name}{pg.extras?.rating ? ` ${pg.extras.rating}` : ''}
                    <span className="gear-pending-tag">pending</span>
                    {tpl?.description && <div className="wr-desc">{tpl.description}</div>}
                </div>
                <div className="wr-grade-select" style={{ padding: '4px 10px', fontSize: 11, color: 'var(--text-muted)' }}>
                    {pg.extras?.grade || 'standard'}
                </div>
                <div className="wr-stat essence" style={{ color: 'var(--bad)' }}>−{(pg.essenceCost || 0).toFixed(2)}</div>
                <div className="wr-rating">
                    {pg.extras?.rating ? <span className="mono">{pg.extras.rating}</span> : <span className="muted mono" style={{ fontSize: 11 }}>—</span>}
                </div>
                <div className="wr-stat">{tpl?.avail || '—'}</div>
                <div className="wr-stat cost" style={{ color: 'var(--accent)' }}>{(pg.nuyenCost || 0).toLocaleString()}¥</div>
                <button className="knowledge-remove-btn"
                        onClick={() => handleUnstage(pg.tempId)}
                        title="Discard pending">×</button>
            </div>
        );
    }

    return (
        <>
            <div className="essence-meter">
                <div className="essence-big">
                    <span className="e-label">Essence</span>
                    <span className={`e-value ${essClass}`}>
                        {essCur.toFixed(2)}
                        <span className="e-max"> / 6.00</span>
                    </span>
                    {inCareer && essProjected !== essCur && (
                        <span className="mono" style={{ fontSize: 11, color: 'var(--accent)', marginLeft: 8 }}>
                            → {essProjected.toFixed(2)} projected
                        </span>
                    )}
                </div>
                <div className="essence-bar-wrap">
                    <div className="essence-bar-labels">
                        <span>spent: {essSpent.toFixed(2)}{inCareer && essProjected !== essCur ? ` → ${(6 - essProjected).toFixed(2)}` : ''}</span>
                        <span>remaining: {essCur.toFixed(2)}</span>
                    </div>
                    <div className="essence-bar">
                        <div className={`essence-bar-fill ${essClass}`}
                             style={{ width: `${Math.max(0, Math.min(100, essPct))}%` }} />
                        {inCareer && essProjected < essCur && (
                            <div className="essence-bar-fill-projected"
                                 style={{ width: `${Math.max(0, Math.min(100, essPctProjected))}%` }} />
                        )}
                    </div>
                </div>
                <div className="essence-magic">
                    <div className="em-label">Magic Cap</div>
                    <div className="em-value">{magicCap}</div>
                    <div className="em-hint">floor(essence)</div>
                </div>
            </div>

            {magicCapped && (
                <div className="magic-cap-warning">
                    Essence loss has reduced your Magic maximum. Priority granted Magic {magicAttrGranted},
                    but current essence caps it at {magicCap}. Remove some ware or accept the lower Magic.
                </div>
            )}

            {items.length === 0 && pendingGear.length === 0 ? (
                <div className="ware-empty">
                    no {kind} yet — browse the catalog or add a custom implant
                </div>
            ) : (
                <div className="ware-table">
                    <div className="ware-table-head">
                        <div>Name</div>
                        <div style={{ textAlign: 'center' }}>Grade</div>
                        <div style={{ textAlign: 'center' }}>Essence</div>
                        <div style={{ textAlign: 'center' }}>Rating</div>
                        <div style={{ textAlign: 'center' }}>Avail</div>
                        <div style={{ textAlign: 'right' }}>Cost</div>
                        <div></div>
                    </div>
                    {items.map(renderRow)}
                    {pendingGear.map(renderPendingRow)}
                </div>
            )}

            <div className="gear-add-bar">
                <button className="add-button" onClick={() => setPickerOpen(true)}>
                    <span className="plus-icon">+</span>Browse {kind === 'bioware' ? 'Bioware' : 'Cyberware'}
                </button>
                {!inCareer && (
                    <button className="add-button" onClick={() => setCustomOpen(true)}>
                        <span className="plus-icon">+</span>Custom {kind === 'bioware' ? 'Bioware' : 'Cyberware'}
                    </button>
                )}
            </div>

            {pickerOpen && (
                <WarePickerModal
                    kind={kind}
                    templates={templates}
                    categories={categories}
                    character={character}
                    onPick={handlePick}
                    onClose={() => setPickerOpen(false)}
                />
            )}

            {customOpen && (
                <CustomAugDialog
                    kind={kind}
                    onSubmit={payload => {
                        onChange(C.addCustomAug(character, { ...payload, type: kind }));
                        setCustomOpen(false);
                    }}
                    onClose={() => setCustomOpen(false)}
                />
            )}
        </>
    );
};


/* Small wrapper components so the GearView router has named tabs */
window.CyberwareTab = function CyberwareTab(props) { return <WareTab kind="cyberware" {...props} />; };

window.BiowareTab   = function BiowareTab(props)   { return <WareTab kind="bioware"   {...props} />; };
