<%- include('partials/header') %>
<%- include('partials/welcome', { 
    user: user,
    contextButtons: [ { href: '/dashboard', text: 'Back to Dashboard' } ]
}) %>

<script type="application/json" id="all-settings-data">
    <%- JSON.stringify(allSettings) %>
</script>

<main class="character-creation">
    <h2>Create New Character</h2>
    <% if (error) { %><div class="error-message"><%= error %></div><% } %>

    <form action="/character/create" method="POST" class="character-form">
        
        <section class="form-section">
            <h3>Setting</h3>
            <p class="section-help">Choose the game world for your character. This determines the available Perks and Quirks.</p>
            <div class="form-group">
                <label for="setting-select">Game Setting:</label>
                <select id="setting-select" name="setting" required>
                    <option value="">-- Choose a World --</option>
                    <% availableSettings.forEach(setting => { %>
                        <option value="<%= setting.key %>"><%= setting.name %></option>
                    <% }); %>
                </select>
            </div>
        </section>

        <div id="character-sheet-fields" style="display: none;">
            <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" 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="">Choose...</option>
                        <option value="agile">Agile</option>
                        <option value="brawny">Brawny</option>
                        <option value="crafty">Crafty</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="concept">Concept:</label>
                    <input type="text" id="concept" name="concept" required>
                </div>
                <div class="form-group">
                    <label for="combat_style">Combat Style:</label>
                    <select id="combat_style" name="combat_style" required>
                        <option value="">Choose...</option>
                        <option value="melee">Melee</option>
                        <option value="ranged">Ranged</option>
                        <option value="mental">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="4" placeholder="Describe your character's life before their powers manifested..."></textarea>
                </div>
            </section>

            <section class="form-section">
                <h3>Equipment & Possessions</h3>
                <div class="form-group">
                    <label for="equipment">Starting Equipment:</label>
                    <textarea id="equipment" name="equipment" rows="4" placeholder="List your character's possessions, clothing, technology..."></textarea>
                </div>
            </section>

            <section class="form-section">
                <h3>Resources</h3>
                <p class="section-help">Set your character's starting Karma and Resolve.</p>
                <div class="resources-edit">
                    <div class="form-group">
                        <label for="karma_max">Karma:</label>
                        <input type="number" id="karma_max" name="karma_max" value="3" min="3" max="6">
                        <small>Luck and providence (starts at 3)</small>
                    </div>
                    <div class="form-group">
                        <label for="resolve_max">Resolve:</label>
                        <input type="number" id="resolve_max" name="resolve_max" value="3" min="3" max="6">
                        <small>Tenacity and health (starts at 3)</small>
                    </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>
                <p class="section-help">Add abilities from the lists, or create your own custom ones.</p>
                <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>

        <div class="form-actions">
            <button type="submit" class="btn btn-primary">Create Character</button>
            <a href="/dashboard" class="btn btn-secondary">Cancel</a>
        </div>
    </form>
</main>

<%- include('partials/footer') %>

<script>
    // These functions need to be global for onclick attributes to find them.
    let perks = [];
    let quirks = [];
    const allSettingsData = JSON.parse(document.getElementById('all-settings-data').textContent);

    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);
    }

    window.updateAbilityDetail = (type, index, detail) => {
        // Determine which array and hidden input to update
        const list = type === 'perk' ? perks : quirks;
        const hiddenInput = document.getElementById(type === 'perk' ? 'perks-hidden-input' : 'quirks-hidden-input');

        // Get the base name of the ability (everything before the colon)
        const base = parseAbilityString(list[index]).base;

        // Update the ability string in the array
        // If detail is not empty, combine them; otherwise, just use the base name.
        list[index] = detail ? `${base}: ${detail}` : base;

        // Update the hidden input's value with the latest data
        // This is the crucial part that keeps the form submittable
        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', () => {
    const settingSelect = document.getElementById('setting-select');
    const characterSheetFields = document.getElementById('character-sheet-fields');
    const perkSelect = document.getElementById('perk-select');
    const quirkSelect = document.getElementById('quirk-select');

    // Get the new wrapper elements
    const perkDropdownWrapper = document.getElementById('perk-dropdown-wrapper');
    const quirkDropdownWrapper = document.getElementById('quirk-dropdown-wrapper');

   settingSelect.addEventListener('change', () => {
        const selectedSettingKey = settingSelect.value;
        perks = [];
        quirks = [];

        // --- DEBUGGING LINE ---
        // This will show the exact value in your browser's developer console (F12).
        console.log('Selected Setting Value:', selectedSettingKey);

        if (!selectedSettingKey) {
            characterSheetFields.style.display = 'none';
            return;
        }

        // --- CORRECTED LOGIC ---
        // Use toLowerCase() for a case-insensitive check.
        if (selectedSettingKey.toLowerCase() === 'generic') {
            perkDropdownWrapper.style.display = 'none';
            quirkDropdownWrapper.style.display = 'none';
        } else {
            perkDropdownWrapper.style.display = 'block';
            quirkDropdownWrapper.style.display = 'block';
        }
        // --- END CORRECTED LOGIC ---

        const settingData = allSettingsData[selectedSettingKey];
        populateDropdowns(settingData);
        characterSheetFields.style.display = 'block';
        renderAbilities();
    });

// Also, trigger the change event on page load in case a value is already selected.
settingSelect.dispatchEvent(new Event('change'));

    function populateDropdowns(data) {
        // ... (the rest of your populateDropdowns function remains the same)
        perkSelect.innerHTML = '<option value="">-- Select a Perk --</option>';
        quirkSelect.innerHTML = '<option value="">-- Select a Quirk --</option>';

        if (data && data.perksData && data.perksData.length > 0) {
            data.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 (data && data.quirksData && data.quirksData.length > 0) {
            data.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);
            });
        }
    }
});
</script>