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


/* ============================================================
   PHASE 5c — Complex Forms (Technomancer view)
   ============================================================ */

window.ComplexFormsSection = function ComplexFormsSection({ character, onChange }) {
    const C = SR5_CALC;
    const M = SR5_MAGIC;

    const [pickerOpen, setPickerOpen] = useState(false);
    const [customOpen, setCustomOpen] = useState(false);
    const [previewLevel, setPreviewLevel] = useState(4);

    const inCareer = C.isCareerMode(character);
    const karmaAvailable = inCareer ? C.karmaCurrent(character) : 0;
    const pendingDelta = inCareer ? C.pendingKarmaDelta(character) : 0;
    const karmaRemaining = inCareer ? karmaAvailable - pendingDelta : 0;
    const pendingCh = inCareer ? C.pendingChanges(character) : {};
    const pendingNewForms = pendingCh.newComplexForms || [];

    const resonance = C.specialAttributeValue(character, 'res');
    const forms = C.characterComplexForms(character);
    const total = C.complexFormSlotsTotal(character);
    const used = C.complexFormSlotsUsed(character);
    const remaining = C.complexFormSlotsRemaining(character);
    const threadPool = C.threadingDicePool(character);
    const fadePool = C.fadingDicePool(character);

    function onPick(tpl, opts) {
        if (inCareer) {
            if (pendingDelta + C.KARMA_COST_NEW_COMPLEX_FORM > karmaAvailable) {
                alert(`Not enough karma: a complex form costs ${C.KARMA_COST_NEW_COMPLEX_FORM} karma, you have ${karmaRemaining} remaining.`);
                return;
            }
            onChange(C.stagePendingNewComplexForm(character, tpl));
            setPickerOpen(false);
        } else {
            /* Phase 17 — creation: allow complex forms past free-priority count,
               each additional costs 4 karma. */
            if (used >= total) {
                const kt = C.karmaTotals(character);
                if (kt.remaining < 4) {
                    alert(`Free complex form slots exhausted. An additional form costs 4 karma, but you only have ${kt.remaining} remaining.`);
                    return;
                }
                if (used === total) {
                    if (!confirm(`Your ${total} priority-free complex form slots are full. Additional forms cost 4 karma each from your leftover karma pool. Add this form for 4 karma?`)) {
                        return;
                    }
                }
            }
            onChange(C.addComplexFormFromTemplate(character, tpl.key, opts || {}));
            setPickerOpen(false);
        }
    }
    function onAddCustom(payload) {
        onChange(C.addCustomComplexForm(character, payload));
        setCustomOpen(false);
    }
    function onRemove(id) {
        if (inCareer) {
            alert("Complex forms can't be unlearned in career mode.");
            return;
        }
        onChange(C.removeComplexForm(character, id));
    }
    function onUnstagePendingForm(tempId) {
        onChange(C.unstagePendingNewComplexForm(character, tempId));
    }
    function onUpdate(id, patch) {
        if (inCareer) return;
        onChange(C.updateComplexForm(character, id, patch));
    }

    return (
        <>
            {/* Stats ribbon — threading pool, fading pool, form slots */}
            <div className="card">
                <div className="card-body">
                    <div className="magic-ribbon">
                        <div className="mr-stat">
                            <div className="mr-label">Resonance</div>
                            <div className="mr-value accent">{resonance}</div>
                        </div>
                        <div className="mr-stat">
                            <div className="mr-label">Threading pool</div>
                            <div className="mr-value">{threadPool}</div>
                            <div className="mr-hint">Software + Resonance</div>
                        </div>
                        <div className="mr-stat">
                            <div className="mr-label">Fading resist</div>
                            <div className="mr-value">{fadePool}</div>
                            <div className="mr-hint">Willpower + Logic</div>
                        </div>
                        <div className="mr-stat">
                            <div className="mr-label">Form slots</div>
                            <div className="mr-value" style={{
                                color: used > total ? 'var(--bad)' : used === total ? 'var(--good)' : 'var(--text-primary)',
                            }}>{used}<span className="muted" style={{ fontSize: 13 }}>/{total}</span></div>
                            <div className="mr-hint">Resonance × 2 at creation</div>
                        </div>
                    </div>
                </div>
            </div>

            {/* Level preview — like the spell Force preview */}
            <div className="card">
                <div className="card-header">
                    <h3 className="card-title">Level preview</h3>
                </div>
                <div className="card-body">
                    <div className="force-preview">
                        <span className="fp-label">Preview fade at Level:</span>
                        <RatingStepper
                            value={previewLevel}
                            min={1}
                            max={12}
                            onChange={setPreviewLevel}
                            size="md"
                        />
                        <span className="muted" style={{ fontSize: 12 }}>
                            (the Level you thread at — higher = more effect, more fade)
                        </span>
                    </div>
                </div>
            </div>

            {/* Slot counter action bar */}
            <div className="spell-actions-bar">
                <div className="sab-info">
                    <span className="sab-slots">
                        <strong style={{
                            color: used > total ? 'var(--bad)' : used === total ? 'var(--good)' : 'var(--text-primary)',
                        }}>{used}/{total}</strong> forms learned
                    </span>
                    <span className="muted" style={{ fontSize: 12 }}>
                        {remaining > 0 ? `${remaining} free slots remaining` : used > total ? `${used - total} over budget` : 'all slots used'}
                    </span>
                </div>
                <div className="sab-actions">
                    <button className="btn btn-primary" onClick={() => setPickerOpen(true)}>
                        + Browse Core Rulebook Forms {inCareer ? '(4 karma each)' : ''}
                    </button>
                    {!inCareer && (
                        <button className="btn btn-ghost" onClick={() => setCustomOpen(true)}>
                            + Custom Form
                        </button>
                    )}
                </div>
            </div>

            {/* Form list */}
            {forms.length === 0 && pendingNewForms.length === 0 ? (
                <div className="spell-empty">
                    No complex forms yet. Technomancers start with {total} free forms (Resonance × 2).
                    Each form can be threaded at any Level from 1 up to your Resonance attribute.
                </div>
            ) : (
                <div className="card">
                    <div className="card-body" style={{ padding: 0 }}>
                        <div className="cf-head">
                            <span>Name</span>
                            <span>Target</span>
                            <span>Duration</span>
                            <span>Fade</span>
                            <span>Fade @ L{previewLevel}</span>
                            <span></span>
                        </div>
                        {forms.map(form => {
                            const isCustom = !form.key;
                            const fadeAtPreview = M.computeFadeValue(form.fade, previewLevel);
                            return (
                                <div key={form.id} className="cf-row">
                                    <div className="cf-name">
                                        <span className="cf-name-text">{form.name}</span>
                                        {form.selection && <span className="cf-selection">({form.selection})</span>}
                                        {isCustom && <span className="linked-badge">Custom</span>}
                                    </div>
                                    <div className="cf-target">{form.target}</div>
                                    <div className="cf-duration" title={durationLabel(form.duration)}>{form.duration}</div>
                                    <div className="cf-fade">{form.fade}</div>
                                    <div className="cf-fade-preview" style={{
                                        color: fadeAtPreview >= fadePool ? 'var(--bad)' : 'var(--accent)',
                                    }}>{fadeAtPreview}</div>
                                    <button className="btn-row-remove"
                                            onClick={() => onRemove(form.id)}
                                            title={inCareer ? "Can't remove in career mode" : 'Remove'}>×</button>
                                    {form.description && (
                                        <div className="cf-desc">{form.description}</div>
                                    )}
                                </div>
                            );
                        })}
                        {pendingNewForms.map(pf => (
                            <div key={pf.tempId} className="cf-row pending-new">
                                <div className="cf-name">
                                    <span className="cf-name-text" style={{ color: 'var(--accent)' }}>{pf.name}</span>
                                    <span style={{ marginLeft: 6, fontSize: 10, letterSpacing: '0.1em', color: 'var(--accent)' }}>
                                        — pending ({pf.karmaCost} karma)
                                    </span>
                                </div>
                                <div className="cf-target">{pf.target || '—'}</div>
                                <div className="cf-duration">{pf.duration || '—'}</div>
                                <div className="cf-fade">{pf.fv || '—'}</div>
                                <div className="cf-fade-preview muted">—</div>
                                <button className="btn-row-remove"
                                        onClick={() => onUnstagePendingForm(pf.tempId)}
                                        title="Discard this pending form">×</button>
                            </div>
                        ))}
                    </div>
                </div>
            )}

            <div className="phase-note" style={{ marginTop: 20 }}>
                <strong>Phase 5c.</strong> Complex Forms for technomancers. All 20 Core Rulebook forms available;
                threading is Software + Resonance, fading resistance is Willpower + Logic. The Level preview above
                shows what fade DV each form would cost at any Level. Minimum fade is 2 per the rulebook — the UI
                respects this automatically. Sprites, echoes, and submersion are out of scope for character creation
                and will come in a later phase.
            </div>

            {pickerOpen && (
                <ComplexFormPickerModal
                    character={character}
                    onPick={onPick}
                    onClose={() => setPickerOpen(false)}
                    previewLevel={previewLevel}
                />
            )}

            {customOpen && (
                <CustomComplexFormDialog
                    onSubmit={onAddCustom}
                    onClose={() => setCustomOpen(false)}
                />
            )}
        </>
    );
};


window.durationLabel = function durationLabel(d) {
    return { I: 'Instant', S: 'Sustained', P: 'Permanent', E: 'Extended' }[d] || d;
}
