<%- include('partials/header') %>
<%- include('partials/welcome', { 
    user: user,
    contextButtons: [
        { href: '/character/' + character.id, text: 'View Character', class: 'btn-secondary' },
        { href: '/dashboard', text: 'Dashboard' }
    ]
}) %>

<script type="application/json" id="all-settings-data"><%- JSON.stringify(allSettings) %></script>
<script type="application/json" id="character-abilities-data"><%- JSON.stringify({ perks: character.perks, quirks: character.quirks }) %></script>

<main class="character-creation">
    <h2>Edit Character</h2>
    <p class="creation-intro">Update your character's details. All fields are optional - you can save partial information and return later.</p>
    <% if (error) { %><div class="error"><%= error %></div><% } %>

    <form action="/character/<%= character.id %>/edit" method="POST" class="character-form">
        <input type="hidden" name="setting" value="<%= character.setting %>">

        <section class="form-section">
            <h3>Setting</h3>
            <div class="form-group">
                <label>Game Setting</label>
                <input type="text" value="<%= character.setting.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase()) %>" disabled>
                <small>The character's setting cannot be changed after creation.</small>
            </div>
        </section>

        <section class="form-section">
            <h3>Basic Information</h3>
            <div class="form-group">
                <label for="name">Character Name:</label>
                <input type="text" id="name" name="name" value="<%= character.name || '' %>" required>
            </div>
        </section>

        <section class="form-section">
            <h3>Archetype</h3>
            <div class="form-group">
                <label for="archetype">Primary Trait:</label>
                <select id="archetype" name="archetype" required>
                    <option value="agile" <%= character.archetype === 'agile' ? 'selected' : '' %>>Agile</option>
                    <option value="brawny" <%= character.archetype === 'brawny' ? 'selected' : '' %>>Brawny</option>
                    <option value="crafty" <%= character.archetype === 'crafty' ? 'selected' : '' %>>Crafty</option>
                </select>
            </div>
            <div class="form-group">
                <label for="concept">Concept:</label>
                <input type="text" id="concept" name="concept" value="<%= character.concept || '' %>" required>
            </div>
            <div class="form-group">
                <label for="combat_style">Combat Style:</label>
                <select id="combat_style" name="combat_style" required>
                    <option value="melee" <%= character.combat_style === 'melee' ? 'selected' : '' %>>Melee</option>
                    <option value="ranged" <%= character.combat_style === 'ranged' ? 'selected' : '' %>>Ranged</option>
                    <option value="mental" <%= character.combat_style === 'mental' ? 'selected' : '' %>>Mental</option>
                </select>
            </div>
        </section>

        <section class="form-section">
            <h3>Background</h3>
            <div class="form-group">
                <label for="background">Character Background:</label>
                <textarea id="background" name="background" rows="6"><%= character.background || '' %></textarea>
            </div>
        </section>

        <section class="form-section">
            <h3>Equipment & Possessions</h3>
            <div class="form-group">
                <label for="equipment">Equipment & Gear:</label>
                <textarea id="equipment" name="equipment" rows="6"><%= character.equipment || '' %></textarea>
            </div>
        </section>

        <section class="form-section">
            <h3>Resources</h3>
            <p class="section-help">Set your character's maximum Karma and Resolve pools.</p>
            <div class="resources-edit">
                <div class="form-group">
                    <label for="karma_max">Karma Max:</label>
                    <input type="number" id="karma_max" name="karma_max" value="<%= character.karma_max || 3 %>" min="3" max="6">
                </div>
                <div class="form-group">
                    <label for="resolve_max">Resolve Max:</label>
                    <input type="number" id="resolve_max" name="resolve_max" value="<%= character.resolve_max || 3 %>" min="3" max="6">
                </div>
            </div>
        </section>
        
        <div class="form-section" id="abilities-container">
            <input type="hidden" name="perks" id="perks-hidden-input">
            <input type="hidden" name="quirks" id="quirks-hidden-input">
            <h3>Abilities</h3>
            <div class="abilities-management">
                <div class="ability-section">
                    <h4>Perks</h4>
                    <div class="current-abilities-list" id="current-perks-list"></div>
                    <div class="add-ability">
                        <div id="perk-dropdown-wrapper">
                            <label for="perk-select">Add Perk</label>
                            <select id="perk-select"></select>
                            <button type="button" class="btn btn-secondary btn-small" onclick="addAbility('perk')">Add</button>
                            <hr>
                        </div>
                        <label for="custom-perk">Add Custom Perk</label>
                        <textarea id="custom-perk" class="custom-ability-textarea" placeholder="e.g., Fire Breath (Level 1)"></textarea>
                        <button type="button" class="btn btn-secondary btn-small" onclick="addCustomAbility('perk')">Add Custom</button>
                    </div>
                </div>
                <div class="ability-section">
                        <h4>Quirks</h4>
                        <div class="current-abilities-list" id="current-quirks-list"></div>
                        <div class="add-ability">
                            <div id="quirk-dropdown-wrapper">
                                <label for="quirk-select">Add Quirk</label>
                                <select id="quirk-select"></select>
                                <button type="button" class="btn btn-secondary btn-small" onclick="addAbility('quirk')">Add</button>
                                <hr>
                            </div>
                            <label for="custom-quirk">Add Custom Quirk</label>
                            <textarea id="custom-quirk" class="custom-ability-textarea" placeholder="e.g., Afraid of Heights"></textarea>
                            <button type="button" class="btn btn-secondary btn-small" onclick="addCustomAbility('quirk')">Add Custom</button>
                        </div>
                    </div>
            </div>
        </div>
        <div class="form-actions">
            <button type="submit" class="btn btn-primary">Update Character</button>
            <a href="/dashboard" class="btn btn-secondary">Cancel</a>
        </div>
    </form>
    <div class="delete-section" style="margin-top: 40px; text-align: center;">
        <hr style="border-color: #ff4444; margin-bottom: 20px;">
        <h3 style="color: #ff4444;">Danger Zone</h3>
        <p class="section-help">This action is permanent and cannot be undone. All information associated with this character will be lost forever.</p>
        <form action="/character/<%= character.id %>/delete" method="POST" onsubmit="return confirm('Are you absolutely sure you want to permanently delete this character?');">
            <div class="delete-section-actions">
                <button type="submit" class="btn btn-danger">Delete Permanently</button>
            </div>
        </form>
    </div>
</main>

<%- include('partials/footer') %>

<script>
    // These functions must be global for onclick attributes to find them.
    let perks = [];
    let quirks = [];
    
    function parseAbilityString(str) {
        if (!str) return { base: '', detail: '' };
        const parts = str.split(/:(.*)/s);
        return { base: (parts[0] || '').trim(), detail: (parts[1] || '').trim() };
    }

    function renderAbilities() {
        const perksListDiv = document.getElementById('current-perks-list');
        const quirksListDiv = document.getElementById('current-quirks-list');
        const perksHiddenInput = document.getElementById('perks-hidden-input');
        const quirksHiddenInput = document.getElementById('quirks-hidden-input');

        perksListDiv.innerHTML = perks.length ? '' : '<p class="no-abilities">No perks added.</p>';
        perks.forEach((perk, i) => {
            const p = parseAbilityString(perk);
            perksListDiv.innerHTML += `<div class="ability-item"><span>${p.base}</span><input type="text" class="perk-detail-input" value="${p.detail}" placeholder="Add detail..." oninput="updateAbilityDetail('perk', ${i}, this.value)"><button type="button" class="remove-ability" onclick="removeAbility('perk', ${i})">❌</button></div>`;
        });
        quirksListDiv.innerHTML = quirks.length ? '' : '<p class="no-abilities">No quirks added.</p>';
        quirks.forEach((quirk, i) => {
            const q = parseAbilityString(quirk);
            quirksListDiv.innerHTML += `<div class="ability-item"><span>${q.base}</span><input type="text" class="perk-detail-input" value="${q.detail}" placeholder="Add detail..." oninput="updateAbilityDetail('quirk', ${i}, this.value)"><button type="button" class="remove-ability" onclick="removeAbility('quirk', ${i})">❌</button></div>`;
        });
        perksHiddenInput.value = JSON.stringify(perks);
        quirksHiddenInput.value = JSON.stringify(quirks);
    }

    // CORRECTED: This function no longer re-renders, preventing focus loss.
    window.updateAbilityDetail = (type, index, detail) => {
        const list = type === 'perk' ? perks : quirks;
        const hiddenInput = document.getElementById(type === 'perk' ? 'perks-hidden-input' : 'quirks-hidden-input');
        const base = parseAbilityString(list[index]).base;
        list[index] = detail ? `${base}: ${detail}` : base;
        hiddenInput.value = JSON.stringify(list);
    };

    window.addAbility = (type) => {
        const selectEl = document.getElementById(type === 'perk' ? 'perk-select' : 'quirk-select');
        const val = selectEl.value;
        if (!val) return;

        if (type === 'perk') {
            const name = (val.match(/(.*)\s\(Level \d+\)/) || [null, val])[1].trim();
            perks = perks.filter(p => (p.match(/(.*)\s\(Level \d+\)/) || [null, p])[1].trim() !== name);
            perks.push(val);
        } else {
            if (!quirks.some(q => parseAbilityString(q).base === val)) quirks.push(val);
        }
        selectEl.value = '';
        renderAbilities();
    };

    window.addCustomAbility = (type) => {
        const input = document.getElementById(type === 'perk' ? 'custom-perk' : 'custom-quirk');
        const list = type === 'perk' ? perks : quirks;
        const val = input.value.trim();
        if (val && !list.some(item => parseAbilityString(item).base === val)) {
            list.push(val);
            input.value = '';
        }
        renderAbilities();
    };

    window.removeAbility = (type, index) => {
        (type === 'perk' ? perks : quirks).splice(index, 1);
        renderAbilities();
    };

    document.addEventListener('DOMContentLoaded', () => {
        // --- DEBUGGING STEP 1: Inspect the raw data from the HTML ---
        const abilitiesDataElement = document.getElementById('character-abilities-data');
        console.log('1. Raw content of abilities data tag:', abilitiesDataElement.textContent);
        // --- DATA INITIALIZATION ---
        const allSettingsData = JSON.parse(document.getElementById('all-settings-data').textContent);
        const initialAbilities = JSON.parse(abilitiesDataElement.textContent);
        
        perks = initialAbilities.perks || [];
        quirks = initialAbilities.quirks || [];
        const characterSetting = '<%= character.setting %>';

        // --- ELEMENT SELECTORS (including new wrappers) ---
        const perkSelect = document.getElementById('perk-select');
        const quirkSelect = document.getElementById('quirk-select');
        const perkDropdownWrapper = document.getElementById('perk-dropdown-wrapper');
        const quirkDropdownWrapper = document.getElementById('quirk-dropdown-wrapper');
        
        // --- FUNCTIONS ---
        function populateDropdowns(settingKey) {
            const settingData = allSettingsData[settingKey];
            perkSelect.innerHTML = '<option value="">-- Select a Perk --</option>';
            quirkSelect.innerHTML = '<option value="">-- Select a Quirk --</option>';

            if (settingData && settingData.perksData) {
                settingData.perksData.forEach(group => {
                    const optgroup = document.createElement('optgroup');
                    optgroup.label = group.category;
                    group.perks.forEach(perk => {
                        for (let i = 1; i <= perk.levels; i++) {
                            const option = document.createElement('option');
                            option.value = `${perk.name} (Level ${i})`;
                            option.textContent = `${perk.name} (Level ${i})`;
                            optgroup.appendChild(option);
                        }
                    });
                    perkSelect.appendChild(optgroup);
                });
            }
            
            if (settingData && settingData.quirksData) {
                settingData.quirksData.forEach(group => {
                    const optgroup = document.createElement('optgroup');
                    optgroup.label = group.category;
                    group.quirks.forEach(quirk => {
                        const option = document.createElement('option');
                        option.value = quirk;
                        option.textContent = quirk;
                        optgroup.appendChild(option);
                    });
                    quirkSelect.appendChild(optgroup);
                });
            }
        }

        // CORRECTED: This function checks the setting and hides dropdowns if needed.
        function setDropdownVisibility() {
            if (characterSetting.toLowerCase() === 'generic') {
                perkDropdownWrapper.style.display = 'none';
                quirkDropdownWrapper.style.display = 'none';
            } else {
                perkDropdownWrapper.style.display = 'block';
                quirkDropdownWrapper.style.display = 'block';
            }
        }
        
        // --- INITIALIZATION ON PAGE LOAD ---
        populateDropdowns(characterSetting);
        setDropdownVisibility(); // Hide/show dropdowns based on the character's setting.
        renderAbilities();       // Render the character's existing perks and quirks.
    });
</script>