/* ============================================================
   Matrix — Sprites Section (Phase 6b)
   
   Technomancer-only. Shows three cards:
     1. Stats ribbon — compiling/registering dice pools, slot limits
     2. Roster — current sprites (compiled/registered/dismissed)
     3. Reference browser (button → modal) — all 5 types with Level preview
   ============================================================ */
const { useState, useEffect, useRef, useMemo, useCallback, Fragment } = React;

window.SpritesSection = function SpritesSection({ character, onChange }) {
    const C = SR5_CALC;
    const MX = SR5_MATRIX;

    const [referenceOpen, setReferenceOpen] = useState(false);
    const [compileOpen, setCompileOpen] = useState(false);
    const [previewLevel, setPreviewLevel] = useState(3);

    const sprites = C.characterSprites(character);
    const compiled = sprites.filter(s => s.state === 'compiled');
    const registered = sprites.filter(s => s.state === 'registered');
    const dismissed = sprites.filter(s => s.state === 'dismissed');

    const regLimit = C.registeredSpriteLimit(character);
    const compilingPool = C.compilingDicePool(character);
    const registeringPool = C.registeringDicePool(character);
    const resonance = C.specialAttributeValue(character, 'res');
    const fadingPool = C.fadingDicePool(character);

    const overRegLimit = registered.length > regLimit;

    function onCompile(payload) {
        onChange(C.addSprite(character, payload));
        setCompileOpen(false);
    }
    function onRemove(id) {
        onChange(C.removeSprite(character, id));
    }
    function onUpdate(id, patch) {
        onChange(C.updateSprite(character, id, patch));
    }

    return (
        <>
            {/* Stats ribbon */}
            <div className="card">
                <div className="card-header">
                    <h3 className="card-title">Sprites</h3>
                    <div className="card-actions">
                        <button className="btn btn-primary" onClick={() => setCompileOpen(true)}>+ Compile Sprite</button>
                        <button className="btn btn-ghost" onClick={() => setReferenceOpen(true)}>Reference</button>
                    </div>
                </div>
                <div className="card-body">
                    <div className="sprite-ribbon">
                        <div className="sr-stat">
                            <div className="sr-label">Compiling pool</div>
                            <div className="sr-value">{compilingPool}</div>
                            <div className="sr-hint">Compiling + Resonance</div>
                        </div>
                        <div className="sr-stat">
                            <div className="sr-label">Registering pool</div>
                            <div className="sr-value">{registeringPool}</div>
                            <div className="sr-hint">Registering + Resonance</div>
                        </div>
                        <div className="sr-stat">
                            <div className="sr-label">Fading resist</div>
                            <div className="sr-value">{fadingPool}</div>
                            <div className="sr-hint">Willpower + Logic</div>
                        </div>
                        <div className="sr-stat">
                            <div className="sr-label">Registered</div>
                            <div className="sr-value" style={{ color: overRegLimit ? 'var(--bad)' : 'var(--text-primary)' }}>
                                {registered.length}<span className="muted" style={{ fontSize: 13 }}>/{regLimit}</span>
                            </div>
                            <div className="sr-hint">Max = Charisma</div>
                        </div>
                        <div className="sr-stat">
                            <div className="sr-label">Resonance</div>
                            <div className="sr-value accent">{resonance}</div>
                            <div className="sr-hint">Sprite DV formulas</div>
                        </div>
                    </div>
                    {overRegLimit && (
                        <div className="foci-warning" style={{ marginTop: 12 }}>
                            <div>Registered count ({registered.length}) exceeds your Charisma ({regLimit}). In play this isn't allowed — the overflow sprites will drop at rest.</div>
                        </div>
                    )}
                </div>
            </div>

            {/* Roster */}
            {sprites.length === 0 ? (
                <div className="spell-empty" style={{ marginTop: 16 }}>
                    No sprites in your roster yet. Compile sprites for short-term tasks (lasts 8 hours),
                    or register them for permanent service (capped at Charisma). Use the reference browser
                    to see what each sprite type is good at.
                </div>
            ) : (
                <>
                    {compiled.length > 0 && (
                        <SpriteStateSection
                            heading="Compiled"
                            subtitle="Temporary — 8 hour timer or until tasks complete"
                            sprites={compiled}
                            onUpdate={onUpdate}
                            onRemove={onRemove}
                        />
                    )}
                    {registered.length > 0 && (
                        <SpriteStateSection
                            heading="Registered"
                            subtitle={`Permanent — ${registered.length}/${regLimit} of Charisma capacity`}
                            sprites={registered}
                            onUpdate={onUpdate}
                            onRemove={onRemove}
                        />
                    )}
                    {dismissed.length > 0 && (
                        <SpriteStateSection
                            heading="Dismissed"
                            subtitle="Decompiled or released — kept for notes"
                            sprites={dismissed}
                            onUpdate={onUpdate}
                            onRemove={onRemove}
                        />
                    )}
                </>
            )}

            {referenceOpen && (
                <SpriteReferenceModal
                    previewLevel={previewLevel}
                    onPreviewLevelChange={setPreviewLevel}
                    onClose={() => setReferenceOpen(false)}
                />
            )}
            {compileOpen && (
                <CompileSpriteDialog
                    character={character}
                    onSubmit={onCompile}
                    onClose={() => setCompileOpen(false)}
                />
            )}
        </>
    );
};

/* -------- Roster section per state -------- */
window.SpriteStateSection = function SpriteStateSection({ heading, subtitle, sprites, onUpdate, onRemove }) {
    return (
        <div className="card" style={{ marginTop: 12 }}>
            <div className="card-header">
                <h3 className="card-title">{heading}</h3>
                <div className="card-subtitle muted">{subtitle}</div>
            </div>
            <div className="card-body" style={{ padding: 0 }}>
                <div className="sprite-head">
                    <span>Name / Type</span>
                    <span>Level</span>
                    <span>ATT</span>
                    <span>SLZ</span>
                    <span>DP</span>
                    <span>FW</span>
                    <span>Init</span>
                    <span>Tasks</span>
                    <span>State</span>
                    <span></span>
                </div>
                {sprites.map(s => (
                    <SpriteRow key={s.id} sprite={s} onUpdate={onUpdate} onRemove={onRemove} />
                ))}
            </div>
        </div>
    );
};

/* -------- One row in the roster -------- */
window.SpriteRow = function SpriteRow({ sprite, onUpdate, onRemove }) {
    const MX = SR5_MATRIX;
    const stats = MX.spriteStatsAtLevel(sprite.typeKey, sprite.level);
    if (!stats) return null;

    return (
        <div className={`sprite-row sprite-${sprite.typeKey}`}>
            <div className="sp-name">
                {sprite.name ? (
                    <>
                        <span className="sp-nickname">{sprite.name}</span>
                        <span className="sp-type muted">{stats.type.name}</span>
                    </>
                ) : (
                    <span className="sp-type">{stats.type.name}</span>
                )}
            </div>
            <div className="sp-level">
                <RatingStepper
                    value={sprite.level}
                    min={1}
                    max={12}
                    onChange={(n) => onUpdate(sprite.id, { level: n })}
                />
            </div>
            <div className="sp-stat">{stats.attack}</div>
            <div className="sp-stat">{stats.sleaze}</div>
            <div className="sp-stat">{stats.dataProcessing}</div>
            <div className="sp-stat">{stats.firewall}</div>
            <div className="sp-stat sp-init mono">{stats.initiativeFormula}</div>
            <div className="sp-tasks">
                <input type="number"
                       min="0"
                       max="99"
                       value={sprite.tasksRemaining || 0}
                       onChange={e => onUpdate(sprite.id, { tasksRemaining: parseInt(e.target.value, 10) || 0 })}
                       style={{ width: 50 }} />
            </div>
            <div className="sp-state">
                <select className="input-inline"
                        value={sprite.state}
                        onChange={e => onUpdate(sprite.id, { state: e.target.value })}>
                    {MX.SPRITE_STATES.map(st => (
                        <option key={st.key} value={st.key}>{st.label}</option>
                    ))}
                </select>
            </div>
            <button className="btn-row-remove"
                    onClick={() => onRemove(sprite.id)}
                    title="Remove">×</button>
            <div className="sp-details">
                <span className="muted">Skills: </span>
                <span className="mono">{stats.skills.join(', ')} (rating {stats.skillRating})</span>
                <span className="muted" style={{ marginLeft: 12 }}>Powers: </span>
                <span>{stats.powers.map(p => p.name).join(', ')}</span>
                {sprite.notes && (
                    <div style={{ marginTop: 4, fontStyle: 'italic', color: 'var(--text-secondary)' }}>{sprite.notes}</div>
                )}
            </div>
        </div>
    );
};

/* ============================================================
   Compile Sprite Dialog — pick type, Level, state, name
   ============================================================ */
window.CompileSpriteDialog = function CompileSpriteDialog({ character, onSubmit, onClose }) {
    const C = SR5_CALC;
    const MX = SR5_MATRIX;
    const resonance = C.specialAttributeValue(character, 'res');

    const [typeKey, setTypeKey] = useState('crack');
    const [level, setLevel] = useState(Math.min(resonance, 3));
    const [state, setState] = useState('compiled');
    const [name, setName] = useState('');
    const [notes, setNotes] = useState('');

    const stats = MX.spriteStatsAtLevel(typeKey, level);
    const compilingPool = C.compilingDicePool(character);
    const registeringPool = C.registeringDicePool(character);
    const fadingDV = level * 2;  /* worst case if sprite rolls Level hits */

    const footer = (
        <div className="footer-actions" style={{ width: '100%', justifyContent: 'flex-end' }}>
            <button className="btn btn-ghost" onClick={onClose}>Cancel</button>
            <button className="btn btn-primary"
                    onClick={() => onSubmit({
                        typeKey, level, state,
                        tasksRemaining: 0,
                        name: name.trim(),
                        notes: notes.trim(),
                    })}>
                Add to roster
            </button>
        </div>
    );

    return (
        <Modal title="Compile / Register Sprite" onClose={onClose} footer={footer}>
            <div style={{ padding: '20px 24px', width: '100%', overflowY: 'auto' }}>
                {/* Sprite type selector */}
                <FormRow label="Sprite type">
                    <div className="sprite-type-grid">
                        {MX.SPRITE_TYPES.map(t => (
                            <div key={t.key}
                                 className={`sprite-type-card ${typeKey === t.key ? 'selected' : ''} sprite-${t.key}`}
                                 onClick={() => setTypeKey(t.key)}>
                                <div className="stc-name">{t.name}</div>
                                <div className="stc-desc">{t.description}</div>
                                <div className="stc-powers mono">
                                    {t.powerKeys.map(k => MX.findSpritePower(k)?.name).join(' · ')}
                                </div>
                            </div>
                        ))}
                    </div>
                </FormRow>

                {/* Level + state + name */}
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 2fr', gap: 12 }}>
                    <FormRow label="Level" hint={`max = Resonance (${resonance})`}>
                        <RatingStepper
                            value={level}
                            min={1}
                            max={Math.max(1, resonance)}
                            onChange={setLevel}
                        />
                    </FormRow>
                    <FormRow label="State">
                        <select className="input" value={state} onChange={e => setState(e.target.value)}>
                            {MX.SPRITE_STATES.map(st => (
                                <option key={st.key} value={st.key}>{st.label}</option>
                            ))}
                        </select>
                    </FormRow>
                    <FormRow label="Nickname" hint="(optional)">
                        <TextInput value={name} onChange={setName} placeholder="e.g. Zippy" maxLength={40} />
                    </FormRow>
                </div>

                {/* Stat preview card */}
                <div className="sprite-preview-card" style={{ marginTop: 12 }}>
                    <div className="spc-head">
                        <span className="spc-name">{stats.type.name} sprite, Level {level}</span>
                        <span className="spc-init mono">Init {stats.initiativeFormula} · MCM {stats.matrixConditionMonitor}</span>
                    </div>
                    <div className="spc-grid">
                        <div className="spc-stat"><div className="spc-lbl">ATT</div><div className="spc-val">{stats.attack}</div></div>
                        <div className="spc-stat"><div className="spc-lbl">SLZ</div><div className="spc-val">{stats.sleaze}</div></div>
                        <div className="spc-stat"><div className="spc-lbl">DP</div><div className="spc-val">{stats.dataProcessing}</div></div>
                        <div className="spc-stat"><div className="spc-lbl">FW</div><div className="spc-val">{stats.firewall}</div></div>
                        <div className="spc-stat"><div className="spc-lbl">RES</div><div className="spc-val">{stats.resonance}</div></div>
                    </div>
                    <div className="spc-meta">
                        <span><strong>Skills:</strong> {stats.skills.join(', ')} (rating {stats.skillRating})</span><br />
                        <span><strong>Powers:</strong> {stats.powers.map(p => p.name).join(' · ')}</span>
                    </div>
                </div>

                {/* Compile / register context */}
                <div className="sprite-context" style={{ marginTop: 12 }}>
                    {state === 'compiled' && (
                        <>
                            <div><strong>Compiling</strong> ({compilingPool} dice, Resonance limit):
                                Compiling + Resonance vs. Sprite Level ({level}).
                                Each net hit = 1 task owed.</div>
                            <div>Fading DV: 2 × sprite hits, worst case 2 × {level} = <strong className="accent">{fadingDV}</strong>.
                                Resist with Willpower + Logic.</div>
                        </>
                    )}
                    {state === 'registered' && (
                        <>
                            <div><strong>Registering</strong> ({registeringPool} dice, Resonance limit):
                                Registering + Resonance vs. Sprite Level × 2 ({level * 2}).
                                Each net hit = 1 task owed.</div>
                            <div>Fading DV: 2 × sprite hits, worst case 2 × {level} = <strong className="accent">{fadingDV}</strong>.
                                Resist with Willpower + Logic.</div>
                        </>
                    )}
                    {state === 'dismissed' && (
                        <div className="muted">Dismissed sprites are kept for history; no active resources.</div>
                    )}
                </div>

                <FormRow label="Notes" hint="(optional)">
                    <TextArea value={notes} onChange={setNotes} rows={2}
                              placeholder="Linked tasks, remarks, GM notes..." />
                </FormRow>
            </div>
        </Modal>
    );
};

/* ============================================================
   Sprite Reference Modal — browse all 5 types with Level preview
   ============================================================ */
window.SpriteReferenceModal = function SpriteReferenceModal({ previewLevel, onPreviewLevelChange, onClose }) {
    const MX = SR5_MATRIX;

    const footer = (
        <div className="footer-actions" style={{ width: '100%', justifyContent: 'flex-end' }}>
            <button className="btn btn-primary" onClick={onClose}>Done</button>
        </div>
    );

    return (
        <Modal title="Sprite Reference" onClose={onClose} footer={footer}>
            <div style={{ padding: '20px 24px', width: '100%', overflowY: 'auto' }}>
                <div className="force-preview" style={{ marginBottom: 20 }}>
                    <span className="fp-label">Preview stats at Level:</span>
                    <RatingStepper
                        value={previewLevel}
                        min={1}
                        max={12}
                        onChange={onPreviewLevelChange}
                        size="md"
                    />
                </div>

                <div className="sprite-reference-grid">
                    {MX.SPRITE_TYPES.map(t => {
                        const stats = MX.spriteStatsAtLevel(t.key, previewLevel);
                        return (
                            <div key={t.key} className={`sprite-ref-card sprite-${t.key}`}>
                                <div className="src-name">{t.name} Sprite</div>
                                <div className="src-desc">{t.description}</div>
                                <div className="src-stats mono">
                                    <span>ATT <strong>{stats.attack}</strong></span>
                                    <span>SLZ <strong>{stats.sleaze}</strong></span>
                                    <span>DP <strong>{stats.dataProcessing}</strong></span>
                                    <span>FW <strong>{stats.firewall}</strong></span>
                                    <span>Init <strong>{stats.initiativeFormula}</strong></span>
                                    <span>MCM <strong>{stats.matrixConditionMonitor}</strong></span>
                                </div>
                                <div className="src-skills">
                                    <span className="muted">Skills (rating {previewLevel}):</span>{' '}
                                    {t.skills.join(', ')}
                                </div>
                                <div className="src-powers">
                                    <span className="muted">Powers:</span>
                                    <ul>
                                        {stats.powers.map(p => (
                                            <li key={p.key} title={p.description}>
                                                <strong>{p.name}</strong> — {p.summary}
                                            </li>
                                        ))}
                                    </ul>
                                </div>
                                <div className="src-source muted mono">{t.source}</div>
                            </div>
                        );
                    })}
                </div>
            </div>
        </Modal>
    );
};
