<%- include('partials/header') %>
<%- include('partials/welcome', { 
    user: user,
    contextButtons: contextButtons || [
        { href: '/dashboard', text: 'Dashboard' }
    ]
}) %>

<main class="character-sheet">
    <div class="character-header">
        <h2><%= character.name %></h2>
        <div class="character-meta">
            <span class="archetype">
                <% if (character.archetype) { %>
                    <%= character.archetype.charAt(0).toUpperCase() + character.archetype.slice(1) %>
                <% } else { %>
                    Unknown Archetype
                <% } %>
                <%= character.concept || '' %>
                
            </span>
            <% if (character.campaign_name) { %>
                <span class="campaign">Campaign: <%= character.campaign_name %></span>
            <% } else { %>
                <span class="campaign">Not assigned to campaign</span>
            <% } %>
            <span class="player">Player: <%= character.player_name %></span>
        </div>
    </div>

    <div class="character-content">
        <!-- Core Stats -->
        <section class="character-section">
            <h3>Core Information</h3>
            <div class="stats-grid">
                <div class="stat-block">
                    <label>Archetype:</label>
                    <span class="archetype-display">
                        <strong><%= character.archetype.charAt(0).toUpperCase() + character.archetype.slice(1) %></strong> 
                        <%= character.concept %>
                    </span>
                    <small class="archetype-help">
                        <% if (character.archetype === 'agile') { %>
                            Rolls 3d6 for speed, dexterity, reflexes, stealth
                        <% } else if (character.archetype === 'brawny') { %>
                            Rolls 3d6 for strength, toughness, stamina, athletics
                        <% } else if (character.archetype === 'crafty') { %>
                            Rolls 3d6 for charisma, intellect, willpower, perception
                        <% } %>
                    </small>
                </div>
                
                <div class="stat-block">
                    <label>Combat Style:</label>
                    <span class="combat-style">
                        <%= character.combat_style.charAt(0).toUpperCase() + character.combat_style.slice(1) %>
                    </span>
                    <small>Preferred method of conflict resolution</small>
                </div>
            </div>
        </section>

        <!-- Resources -->
        <section class="character-section">
            <h3>Resources</h3>
            <div class="resource-block">
                <h4>Karma</h4>
                <div class="resource-counter">
                    <% if (isOwner) { %>
                    <button class="btn-adjust" onclick="adjustResource('karma', -1)">-</button>
                    <% } %>
                    <span class="current" id="karma_current"><%= character.karma_current %></span>
                    <span class="divider">/</span>
                    <span class="max" id="karma_max"><%= character.karma_max %></span>
                    <% if (isOwner) { %>
                    <button class="btn-adjust" onclick="adjustResource('karma', 1)">+</button>
                    <% } %>
                </div>
                <small>Luck and providence for enhancing abilities</small>
            </div>

            <div class="resource-block">
                <h4>Resolve</h4>
                <div class="resource-counter">
                    <% if (isOwner) { %>
                    <button class="btn-adjust" onclick="adjustResource('resolve', -1)">-</button>
                    <% } %>
                    <span class="current" id="resolve_current"><%= character.resolve_current %></span>
                    <span class="divider">/</span>
                    <span class="max" id="resolve_max"><%= character.resolve_max %></span>
                    <% if (isOwner) { %>
                    <button class="btn-adjust" onclick="adjustResource('resolve', 1)">+</button>
                    <% } %>
                </div>
                <small>Tenacity, spirit, health, and determination</small>
            </div>
        </section>

        <!-- Background -->
        <% if (character.background) { %>
        <section class="character-section">
            <h3>Background</h3>
            <div class="background-text">
                <%= character.background %>
            </div>
        </section>
        <% } %>

        <!-- Equipment -->
        <% if (character.equipment) { %>
        <section class="character-section">
            <h3>Equipment & Possessions</h3>
            <div class="background-text">
                <%= character.equipment %>
            </div>
        </section>
        <% } %>

        <!-- Perks and Quirks -->
        <section class="character-section">
            <h3>Supernatural Abilities</h3>

            <div class="abilities-display-grid">
                <div class="ability-column">
                    <h4>Perks (Abilities)</h4>
                    <div class="perks-list">
                        <% if (character.perks && character.perks.length > 0) { %>
                            <% character.perks.forEach(perkString => { 
                                // NEW: Split perk name from its detail
                                const parts = perkString.split(/:(.*)/s);
                                const basePerk = (parts[0] || '').trim();
                                const detail = (parts[1] || '').trim();

                                // Existing logic to find the level
                                const match = basePerk.match(/(.*) \(Level (\d+)\)/);
                                let perkName = basePerk;
                                let perkLevel = null;
                                if (match) {
                                    perkName = match[1].trim();
                                    perkLevel = match[2];
                                }
                            %>
                                <div class="perk-item">
                                    <h4 style="font-family: var(--font-header); color: var(--color-white); font-size: 1.1rem;">
                                        <%= perkName %>
                                        <% if (perkLevel) { %>
                                            <span class="level" style="font-family: var(--font-body); color: var(--color-cyan); font-size: 0.9rem;">(Level <%= perkLevel %>)</span>
                                        <% } %>
                                    </h4>
                                    <% if (detail) { %>
                                        <p class="perk-detail-display"> > <%= detail %></p>
                                    <% } %>
                                </div>
                            <% }); %>
                        <% } else { %>
                            <p class="no-abilities">No perks assigned.</p>
                        <% } %>
                    </div>
                </div>

                <div class="ability-column">
                    <h4>Quirks (Complications)</h4>
                    <div class="quirks-list">
                        <% if (character.quirks && character.quirks.length > 0) { %>
                            <% character.quirks.forEach(quirkString => { 
                                const parts = quirkString.split(/:(.*)/s);
                                const baseQuirk = (parts[0] || '').trim();
                                const detail = (parts[1] || '').trim();
                            %>
                                <div class="quirk-item">
                                    <h4 style="font-family: var(--font-header); color: var(--color-white); font-size: 1.1rem;">
                                        <%= baseQuirk %>
                                    </h4>
                                    <% if (detail) { %>
                                        <p class="perk-detail-display"> > <%= detail %></p>
                                    <% } %>
                                </div>
                            <% }); %>
                        <% } else { %>
                            <p class="no-abilities">No quirks assigned.</p>
                        <% } %>
                    </div>
                </div>
            </div>
        </section>

        <!-- Dice Rolling Section -->
        <section class="character-section">
            <h3>Dice Rolling Guide</h3>
            <div class="dice-guide">
                <div class="dice-rule">
                    <strong>3d6:</strong> Using your primary trait (<%= character.archetype %>) or <%= character.combat_style %> combat
                </div>
                <div class="dice-rule">
                    <strong>2d6:</strong> Using a trait that's not your primary
                </div>
                <div class="dice-rule">
                    <strong>1d6:</strong> Attempting something requiring specialized knowledge outside your concept/perks
                </div>
                <div class="difficulty-guide">
                    <strong>Target Numbers:</strong> 4 (Easy) | 5 (Standard) | 6 (Hard)
                </div>
            </div>
        </section>
        <% if (character.campaign_id) { %>
        <section class="character-section">
            <h3>Dice Roller</h3>
            <p class="section-help">Make a quick roll for your character. This will be broadcast to the campaign log.</p>

            <div id="personal-roller-ui" style="display: flex; gap: 15px; margin-bottom: 20px;">
                <button class="btn btn-secondary" onclick="makePersonalRoll(3)">Roll 3d6</button>
                <button class="btn btn-secondary" onclick="makePersonalRoll(2)">Roll 2d6</button>
                <button class="btn btn-secondary" onclick="makePersonalRoll(1)">Roll 1d6</button>
            </div>

            <h4>Your Last Roll</h4>
            <div id="last-roll-display">
                <% if (lastRoll) { %>
                    <div class="character-card">
                        <p><strong>Last Roll Result:</strong> [<%= JSON.parse(lastRoll.dice_results).join(', ') %>]</p>
                    </div>
                <% } else { %>
                    <p class="no-abilities">You haven't made any rolls yet.</p>
                <% } %>
            </div>
        </section>
        <% } %>
    </div>
</main>

<%- include('partials/footer') %>
<script>
    // This function must be defined OUTSIDE the DOMContentLoaded listener so that the `onclick` attributes in the HTML can find it.
    async function adjustResource(resource, amount) {
        const characterId = '<%= character.id %>';
        const currentElement = document.getElementById(`${resource}_current`);
        const maxElement = document.getElementById(`${resource}_max`);
        
        let currentValue = parseInt(currentElement.textContent);
        let max = parseInt(maxElement.textContent);
        let newValue = currentValue + amount;

        // Clamp the value between 0 and the max
        if (newValue < 0) newValue = 0;
        if (newValue > max) newValue = max;

        // Update the display immediately if the value has changed
        if (newValue !== currentValue) {
            currentElement.textContent = newValue;

            // Send the update to the server
            try {
                const response = await fetch(`/character/${characterId}/update-resource`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        resource: `${resource}_current`,
                        value: newValue
                    })
                });
                if (!response.ok) {
                    // Revert the display if the save fails
                    currentElement.textContent = currentValue;
                }
            } catch (error) {
                console.error('Failed to save resource change:', error);
                currentElement.textContent = currentValue; 
            }
        }
    }

    document.addEventListener('DOMContentLoaded', () => {
        // Only initialize sockets if the roller UI exists on the page
        if (document.getElementById('personal-roller-ui')) {
            const socket = io();
            const campaignId = '<%= character.campaign_id %>';
            const userId = '<%= user.id %>';
            const characterId = '<%= character.id %>';

            // Join the campaign room to broadcast rolls
            socket.emit('join-campaign-room', campaignId);

            window.makePersonalRoll = function(diceCount) {
                // Send only the essential data; the server will figure out the rest
                socket.emit('new-roll', {
                    campaignId: campaignId,
                    userId: userId,
                    characterId: characterId,
                    diceCount: diceCount
                });
            };

            // Listen for roll results and update this character's "last roll" display
            socket.on('roll-result', (roll) => {
                // Check if the incoming roll is for the character being viewed
                if (roll.character_id == characterId) {
                    const lastRollDisplay = document.getElementById('last-roll-display');
                    const successText = roll.success_count > 0 ? `${roll.success_count} Success(es)` : 'Failure';
                    const successClass = roll.success_count > 0 ? 'status-active' : 'status-recruiting';

                    // Display the full outcome
                    lastRollDisplay.innerHTML = `
                        <div class="character-card">
                            <p><strong>Result:</strong> [${JSON.parse(roll.dice_results).join(', ')}] vs Difficulty ${roll.difficulty}</p>
                            <p><strong>Outcome:</strong> <span class="status ${successClass}">${successText}</span></p>
                        </div>
                    `;
                }
            }); // End of socket.on('roll-result')
        } // End of if() statement
    }); // End of document.addEventListener
</script>