<%- include('partials/header') %>
<%- include('partials/welcome', { 
    user: user,
    contextButtons: contextButtons
}) %>

<main>
    <section class="character-header" style="margin-bottom: 20px; text-align: left;">
        <h2 style="text-align: center;"><%= campaign.name %></h2>
        <p style="font-size: 1.1rem; color: #cccccc;"><%= campaign.description %></p>
        <div class="campaign-meta" style="margin-top: 15px;">
            <span><strong>Status:</strong> <span class="status status-<%= campaign.status %>"><%= campaign.status %></span></span>
        </div>
    </section>

    <section class="character-section">
        <details id="dice-log-section" <%= preferences.diceCollapsed ? '' : 'open' %>>
            <summary style="font-size: 1.2rem; color: #ffff00; cursor: pointer;">Dice Roller & Log</summary>
            <div class="collapsible-content" style="margin-top: 20px;">
                <% if (isGM) { %>
                    <div class="form-section" style="border-color: #ff0080;">
                        <form action="/campaign/<%= campaign.id %>/set-difficulty" method="POST">
                            <div class="form-group">
                                <label for="difficulty">Set Campaign Difficulty</label>
                                <input type="number" id="difficulty" name="difficulty" class="form-control" value="<%= currentDifficulty %>" min="1" max="6">
                            </div>
                            <button type="submit" class="btn btn-primary">Set Difficulty</button>
                        </form>
                    </div>
                <% } %>
                <div class="form-section" style="border-color: #00ffff; margin-top: 20px;">
                    <h4 style="color: #00ffff;">Make a Roll</h4>
                    <div id="roller-ui" style="display: flex; gap: 15px; flex-wrap: wrap;">
                        <button id="roll-3d6" class="btn btn-secondary">Roll 3d6</button>
                        <button id="roll-2d6" class="btn btn-secondary">Roll 2d6</button>
                        <button id="roll-1d6" class="btn btn-secondary">Roll 1d6</button>
                    </div>
                </div>
                <div style="display: flex; justify-content: space-between; align-items: center; margin-top: 30px;">
                    <h4 style="color: #ffff00;">Roll History</h4>
                    <% if (isGM) { %>
                        <form action="/campaign/<%= campaign.id %>/clear-rolls" method="POST" onsubmit="return confirm('Are you sure?');">
                            <button type="submit" class="btn btn-small" style="border-color: #ff4444; color: #ff4444;">Clear History</button>
                        </form>
                    <% } %>
                </div>
                <div id="dice-log">
                     <% if (rolls && rolls.length > 0) { %>
                        <% rolls.forEach(roll => { 
                            const successText = roll.success_count > 0 ? `${roll.success_count} Success(es)` : 'Failure';
                            const successClass = roll.success_count > 0 ? 'status-active' : 'status-recruiting';
                        %>
                            <div class="character-card" style="margin-bottom: 10px;">
                                <p>
                                    <strong><%= roll.username %></strong> rolled as "<%= roll.description || 'an action' %>"
                                    <span style="color: #888;">(<%= new Date(roll.rolled_at).toLocaleTimeString() %>)</span>
                                </p>
                                <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>
                        <% }); %>
                    <% } else { %>
                        <p class="no-abilities">No rolls yet. Be the first!</p>
                    <% } %>
                </div>
            </div>
        </details>
    </section>

    <section class="character-section">
        <details id="players-section" <%= preferences.playersCollapsed ? '' : 'open' %>>
            <summary style="font-size: 1.2rem; color: #ffff00; cursor: pointer;">Players & Characters</summary>
            <div class="collapsible-content" style="margin-top: 20px;">
                <div class="characters-grid">
                    <% if (players && players.length > 0) { %>
                        <% players.forEach(player => { %>
                            <div class="character-card" style="min-height: 200px; display: flex; flex-direction: column;">
                                <h4><%= player.username %></h4>
                                
                                <% if (player.character_id) { %>
                                    <div class="character-summary" style="flex-grow: 1;">
                                        <p><strong>Character:</strong> <a href="/character/<%= player.character_id %>"><%= player.character_name %></a></p>
                                        
                                        <% if (player.character_archetype && player.character_concept) { %>
                                            <p><strong>Archetype:</strong> <%= player.character_archetype.charAt(0).toUpperCase() + player.character_archetype.slice(1) %> <%= player.character_concept %></p>
                                        <% } %>
                                        
                                        <% if (player.character_combat_style) { %>
                                            <p><strong>Combat:</strong> <%= player.character_combat_style.charAt(0).toUpperCase() + player.character_combat_style.slice(1) %></p>
                                        <% } %>
                                    </div>
                                    
                                    <% if (player.player_id === user.id) { %>
                                        <form action="/character/<%= player.character_id %>/unassign" method="POST" style="margin-top: auto;">
                                            <button type="submit" class="btn btn-small btn-secondary" style="width: 100%;">Change Character</button>
                                        </form>
                                    <% } %>
                                    
                                <% } else { %>
                                    <p style="color: #888; font-style: italic; flex-grow: 1;">No character assigned</p>
                                <% } %>
                            </div>
                        <% }); %>
                    <% } else { %>
                        <p class="no-abilities">No players have joined yet.</p>
                    <% } %>
                </div>
            </div>
        </details>
    </section>

    <% if (!isGM && !currentPlayerHasCharacter) { %>
    <section class="form-section">
        <details id="assign-section" <%= preferences.assignCollapsed ? '' : 'open' %>>
            <summary style="font-size: 1.2rem; color: #ffff00; cursor: pointer;">Assign Your Character</summary>
            <div class="collapsible-content" style="margin-top: 20px;">
                <% if (unassignedCharacters.length > 0) { %>
                    <p class="section-help">Choose one of your available characters to join this campaign.</p>
                    <form action="/campaign/<%= campaign.id %>/assign-character" method="POST">
                        <div class="form-group">
                            <label for="characterId">Your Available Characters:</label>
                            <select name="characterId" id="characterId">
                                <option value="">-- Select a Character --</option>
                                <% unassignedCharacters.forEach(character => { %>
                                    <option value="<%= character.id %>"><%= character.name %></option>
                                <% }); %>
                            </select>
                        </div>
                        <button type="submit" class="btn btn-primary">Assign to Campaign</button>
                    </form>
                <% } else { %>
                    <p class="no-abilities">You have no available characters. <a href="/character/create">Create one</a> to join this campaign.</p>
                <% } %>
            </div>
        </details>
    </section>
    <% } %>
    
    <section class="character-section">
        <details id="notes-section" <%= preferences.notesCollapsed ? '' : 'open' %>>
            <summary style="font-size: 1.2rem; color: #ffff00; cursor: pointer;">Session Notes</summary>
            <div class="collapsible-content" style="margin-top: 20px;">
                <details>
                    <summary style="font-size: 1.2rem; color: #00ffff; cursor: pointer; margin-bottom: 15px;">Add a New Note</summary>
                    <div class="form-section" style="border-color: #00ffff;">
                        <form action="/campaign/<%= campaign.id %>/note/create" method="POST">
                            <div class="form-group">
                                <label for="title">Note Title</label>
                                <input type="text" name="title" id="title" required placeholder="e.g., Session 1: The Meetup">
                            </div>
                            <div class="form-group">
                                <label for="content">Note Content</label>
                                <textarea name="content" id="content" rows="6" required placeholder="What happened during the session?"></textarea>
                            </div>
                            <div class="form-group">
                                <label>
                                    <input type="checkbox" name="visibility" value="private" id="private-note-checkbox">
                                    Make this note private
                                </label>
                            </div>
                            <div class="form-group" id="shared-with-container" style="display: none;">
                                <label for="shared_with">Share with (optional):</label>
                                <select name="shared_with" id="shared_with">
                                    <option value="">-- Only the GM --</option>
                                    <% players.forEach(player => { %>
                                        <% if (player.player_id !== user.id) { %>
                                            <option value="<%= player.player_id %>"><%= player.username %></option>
                                        <% } %>
                                    <% }); %>
                                </select>
                                <small style="color:#888;">Select one player to share this private note with.</small>
                            </div>
                            <button type="submit" class="btn btn-secondary">Post Note</button>
                        </form>
                    </div>
                </details>

                <div class="notes-list">
                    <% if (notes && notes.length > 0) { %>
                        <% notes.forEach(thread => { %>
                            <div class="character-card" style="margin-bottom: 20px;">
                                <div style="display: flex; justify-content: space-between; align-items: flex-start;">
                                    <h4 style="color: #ffff00;">
                                        <% if (thread.isNew) { %>
                                            <span class="status status-recruiting" style="font-size: 0.7rem; padding: 2px 5px; margin-right: 10px;">NEW</span>
                                        <% } %>
                                        <%= thread.title %>
                                        <% if (thread.visibility === 'private' && thread.shared_with_username) { %>
                                            <span style="color: #888; font-size: 0.9rem; font-style: italic;">(to: <%= thread.shared_with_username %>)</span>
                                        <% } else if (thread.visibility === 'private') { %>
                                            <span style="color: #888; font-size: 0.9rem; font-style: italic;">(to: GM)</span>
                                        <% } %>
                                    </h4>
                                    <% if (thread.visibility === 'private') { %>
                                        <span class="status" style="background-color: rgba(255,255,255,0.1); color: #ccc;">🔒 Private</span>
                                    <% } %>
                                </div>
                                <small style="color: #888; margin-top: -10px; display: block;">
                                    Posted by <%= thread.author_name %> on <%= new Date(thread.created_at).toLocaleDateString() %>
                                </small>
                                <p style="margin-top: 15px; white-space: pre-wrap;"><%= thread.content %></p>
                                <% if (thread.user_id === user.id) { %>
                                    <div class="form-actions" style="justify-content: flex-end; margin-top: 20px;">
                                        <a href="/note/<%= thread.id %>/edit" class="btn btn-small btn-secondary">Edit</a>
                                    </div>
                                <% } %>

                                <% if (thread.replies && thread.replies.length > 0) { %>
                                    <div class="replies-container" style="margin-left: 30px; margin-top: 15px; border-left: 2px solid #444; padding-left: 15px;">
                                        <% thread.replies.forEach(reply => { %>
                                            <div class="reply" style="margin-bottom: 15px;">
                                                <small style="color: #888;">
                                                    <strong><%= reply.author_name %></strong> replied on <%= new Date(reply.created_at).toLocaleDateString() %>
                                                </small>
                                                <p style="white-space: pre-wrap;"><%= reply.content %></p>
                                            </div>
                                        <% }); %>
                                    </div>
                                <% } %>

                                <details style="margin-top: 15px;">
                                    <summary style="font-size: 1rem; color: #00ffff; cursor: pointer;">Reply</summary>
                                    <form action="/note/<%= thread.id %>/reply" method="POST" style="margin-top: 10px;">
                                        <div class="form-group">
                                            <textarea name="content" rows="3" required placeholder="Write your reply..."></textarea>
                                        </div>
                                        <button type="submit" class="btn btn-small btn-secondary">Post Reply</button>
                                    </form>
                                </details>
                            </div>
                        <% }); %>
                    <% } else { %>
                        <p class="no-abilities">No session notes have been posted yet.</p>
                    <% } %>
                </div>
            </div>
        </details>
    </section>
</main>

<%- include('partials/footer') %>
<script>
    document.addEventListener('DOMContentLoaded', () => {
        // --- Socket.IO for Real-time Dice Rolls ---
        const socket = io();
        const campaignId = '<%= campaign.id %>';
        const userId = '<%= user.id %>';
        const diceLog = document.getElementById('dice-log');

        socket.emit('join-campaign-room', campaignId);

        document.getElementById('roll-3d6').addEventListener('click', () => socket.emit('new-roll', { campaignId, userId, diceCount: 3 }));
        document.getElementById('roll-2d6').addEventListener('click', () => socket.emit('new-roll', { campaignId, userId, diceCount: 2 }));
        document.getElementById('roll-1d6').addEventListener('click', () => socket.emit('new-roll', { campaignId, userId, diceCount: 1 }));

        socket.on('roll-result', (roll) => {
            if (diceLog.querySelector('.no-abilities')) {
                diceLog.innerHTML = '';
            }
            const successText = roll.success_count > 0 ? `${roll.success_count} Success(es)` : 'Failure';
            const successClass = roll.success_count > 0 ? 'status-active' : 'status-recruiting';
            const rollHtml = `
                <div class="character-card" style="margin-bottom: 10px;">
                    <p>
                        <strong>${roll.username}</strong> rolled for "${roll.description || 'an action'}"
                        <span style="color: #888;">(${new Date(roll.rolled_at).toLocaleTimeString()})</span>
                    </p>
                    <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>`;
            diceLog.insertAdjacentHTML('afterbegin', rollHtml);
            diceLog.scrollTop = 0;
        });

        // --- Logic for Private Note Player Selection ---
        const privateCheckbox = document.getElementById('private-note-checkbox');
        const sharedWithContainer = document.getElementById('shared-with-container');
        if (privateCheckbox) {
            privateCheckbox.addEventListener('change', () => {
                sharedWithContainer.style.display = privateCheckbox.checked ? 'block' : 'none';
            });
        }

        // --- Logic for Collapsible Section Preferences ---
        const preferences = JSON.parse('<%- JSON.stringify(preferences) %>');
        const sections = {
            dice: document.getElementById('dice-log-section'),
            players: document.getElementById('players-section'),
            notes: document.getElementById('notes-section'),
            assign: document.getElementById('assign-section')
        };

        const savePreferences = async () => {
            const currentPrefs = {
                diceCollapsed: sections.dice ? !sections.dice.open : true,
                playersCollapsed: sections.players ? !sections.players.open : true,
                notesCollapsed: sections.notes ? !sections.notes.open : true,
                assignCollapsed: sections.assign ? !sections.assign.open : true
            };
            try {
                await fetch(`/campaign/<%= campaign.id %>/preferences`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ preferences: currentPrefs })
                });
            } catch (error) {
                console.error('Could not save preferences:', error);
            }
        };

        Object.values(sections).forEach(section => {
            if (section) {
                section.addEventListener('toggle', savePreferences);
            }
        });
    });
</script>