/**
 * Detail view dialog functionality
 */
const DetailDialog = {
    async showDetail(itemId) {
        // Fetch latest item data
        const items = await Api.getItems();
        const item = items.find(i => i.id === itemId);
        if (!item) return;

        // If item is in review, show review dialog instead
        if (item.column_name === 'review') {
            return ReviewDialog.showReview(itemId);
        }

        // If item is in questions, reopen the questions dialog
        if (item.column_name === 'questions') {
            return ClarificationDialog.reopenClarification(itemId);
        }

        document.getElementById('detail-title').textContent = item.title;

        const columnLabels = {
            todo: '📝 Todo', doing: '🚧 Doing', questions: '❓ Questions',
            review: '👀 Review', done: '✅ Done', archive: '📦 Archive',
        };
        const badge = document.getElementById('detail-column-badge');
        badge.textContent = columnLabels[item.column_name] || item.column_name;

        const body = document.getElementById('detail-body');

        // Build content with description and model info
        let content = DialogUtils.renderMarkdown(item.description || '(no description)');

        // Add model information if available
        if (item.model) {
            const modelDisplayName = DialogUtils._getModelDisplayName(item.model);
            const providerBadge = DialogUtils._getProviderBadgeHtml(item.model);
            content += `<div class="detail-model-info"><strong>Model:</strong> ${modelDisplayName} ${providerBadge}</div>`;
        } else {
            // Show default model from config
            try {
                const config = await Api.request('GET', '/api/config');
                const defaultModel = config.model || window.__DEFAULT_MODEL__;
                const modelDisplayName = DialogUtils._getModelDisplayName(defaultModel);
                const providerBadge = DialogUtils._getProviderBadgeHtml(defaultModel);
                content += `<div class="detail-model-info"><strong>Model:</strong> ${modelDisplayName} ${providerBadge} (default)</div>`;
            } catch (err) {
                console.warn('Failed to fetch config for default model display:', err);
            }
        }

        // Show merge commit SHA for done/archive items
        if ((item.column_name === 'done' || item.column_name === 'archive') && item.merge_commit) {
            const shortSha = item.merge_commit.slice(0, 8);
            content += `<div class="detail-model-info detail-git-info"><div class="detail-info-row"><strong>Merge commit:</strong> <code class="sha-text" title="${item.merge_commit}">${shortSha}</code> <button type="button" class="copy-sha-btn" data-copy="${item.merge_commit}" title="Copy full SHA"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg></button></div></div>`;
        }

        body.innerHTML = content;
        DialogUtils.runMermaid(body);

        // Wire up copy buttons
        body.querySelectorAll('.copy-sha-btn').forEach(btn => {
            btn.addEventListener('click', async (e) => {
                e.stopPropagation();
                const text = btn.dataset.copy;
                try {
                    await navigator.clipboard.writeText(text);
                    const orig = btn.innerHTML;
                    btn.innerHTML = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>';
                    setTimeout(() => { btn.innerHTML = orig; }, 1500);
                } catch {
                    // Fallback for non-HTTPS contexts
                    const ta = document.createElement('textarea');
                    ta.value = text;
                    ta.style.position = 'fixed';
                    ta.style.opacity = '0';
                    document.body.appendChild(ta);
                    ta.select();
                    document.execCommand('copy');
                    document.body.removeChild(ta);
                    const orig = btn.innerHTML;
                    btn.innerHTML = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>';
                    setTimeout(() => { btn.innerHTML = orig; }, 1500);
                }
            });
        });

        // Header actions based on item state
        const editBtn = document.getElementById('detail-edit-btn');
        const deleteBtn = document.getElementById('detail-delete-btn');
        const actionsEl = document.getElementById('detail-header-actions');

        // Remove any previously added play/rerun/start-copy/copy-link buttons
        const oldPlay = document.getElementById('detail-play-btn');
        if (oldPlay) oldPlay.remove();
        const oldStartCopy = document.getElementById('detail-start-copy-btn');
        if (oldStartCopy) oldStartCopy.remove();
        const oldRerun = document.getElementById('detail-rerun-btn');
        if (oldRerun) oldRerun.remove();
        const oldCopyLink = document.getElementById('detail-copy-link-btn');
        if (oldCopyLink) oldCopyLink.remove();

        const isAgentActive = item.status === 'running' || item.status === 'resolving_conflicts' || item.status === 'paused';

        // Hide edit/delete when agent is active
        editBtn.style.display = isAgentActive ? 'none' : '';
        deleteBtn.style.display = isAgentActive ? 'none' : '';
        editBtn.onclick = () => {
            DialogCore.close('detail-dialog');
            ItemDialog.openEditItem(item);
        };
        deleteBtn.onclick = async () => {
            DialogCore.close('detail-dialog');
            const ok = await DialogCore.confirm(`Delete "${item.title}"?`);
            if (!ok) return;
            try {
                await Api.deleteItem(item.id);
                Board.removeCard(item.id);
            } catch (err) {
                console.error('Failed to delete item:', err);
            }
        };

        // Auto-approve toggle: visible while item is in Doing so the user can
        // change the mode mid-flight (it's read when the agent finishes).
        // Stored as tri-state int (0=Off, 1=With Review, 2=Direct). Older
        // items may have it as a boolean — coerce truthy → 1.
        const autoApproveWrap = document.getElementById('detail-auto-approve-wrap');
        const autoApproveSelect = document.getElementById('detail-auto-approve');
        if (autoApproveWrap && autoApproveSelect) {
            if (item.column_name === 'doing') {
                let mode;
                if (item.auto_approve === true) mode = 1;
                else if (item.auto_approve === false || item.auto_approve == null) mode = 0;
                else mode = parseInt(item.auto_approve, 10);
                if (![0, 1, 2].includes(mode)) mode = 0;
                autoApproveSelect.value = String(mode);
                autoApproveWrap.style.display = '';
                autoApproveSelect.onchange = async () => {
                    const newValue = parseInt(autoApproveSelect.value, 10);
                    const prev = mode;
                    try {
                        await Api.updateItem(item.id, { auto_approve: newValue });
                        item.auto_approve = newValue;
                        mode = newValue;
                    } catch (err) {
                        console.error('Failed to update auto_approve:', err);
                        autoApproveSelect.value = String(prev);
                    }
                };
            } else {
                autoApproveWrap.style.display = 'none';
                autoApproveSelect.onchange = null;
            }
        }

        // Add play button and start copy button in Todo
        if (item.column_name === 'todo') {
            const playBtn = document.createElement('button');
            playBtn.id = 'detail-play-btn';
            playBtn.className = 'btn btn-sm btn-primary';
            playBtn.textContent = '▶ Start Agent';
            playBtn.onclick = async () => {
                await Board.startAgent(item.id);
                DialogCore.close('detail-dialog');
            };
            actionsEl.insertBefore(playBtn, editBtn);

            const startCopyBtn = document.createElement('button');
            startCopyBtn.id = 'detail-start-copy-btn';
            startCopyBtn.className = 'btn btn-sm';
            startCopyBtn.textContent = '▶⧉ Start Copy';
            startCopyBtn.title = 'Start a copy (keep original in Todo)';
            startCopyBtn.onclick = async () => {
                await Board.startCopyAgent(item.id);
                DialogCore.close('detail-dialog');
            };
            actionsEl.insertBefore(startCopyBtn, editBtn);
        }

        // Add copy-link and re-run buttons in Done
        if (item.column_name === 'done') {
            const copyLinkBtn = document.createElement('button');
            copyLinkBtn.id = 'detail-copy-link-btn';
            copyLinkBtn.className = 'btn btn-sm';
            copyLinkBtn.innerHTML = '&#128279;';
            copyLinkBtn.title = 'Copy item detail link';
            copyLinkBtn.onclick = async () => {
                const url = `${window.location.origin}/api/items/${item.id}`;
                try {
                    await navigator.clipboard.writeText(url);
                    copyLinkBtn.textContent = '✓';
                    setTimeout(() => { copyLinkBtn.innerHTML = '&#128279;'; }, 1500);
                } catch (err) {
                    console.error('Failed to copy link:', err);
                }
            };
            actionsEl.insertBefore(copyLinkBtn, editBtn);

            const rerunBtn = document.createElement('button');
            rerunBtn.id = 'detail-rerun-btn';
            rerunBtn.className = 'btn btn-sm btn-primary';
            rerunBtn.textContent = '↻ Re-run';
            rerunBtn.onclick = async () => {
                await Board.rerunItem(item.id);
                DialogCore.close('detail-dialog');
            };
            actionsEl.insertBefore(rerunBtn, editBtn);
        }

        // Continue form: only visible for paused items. Lets the user send
        // an optional note that the agent receives on resume — replaces the
        // old "pause with note" dialog.
        const resumeForm = document.getElementById('detail-resume-form');
        const resumeMessage = document.getElementById('detail-resume-message');
        if (resumeForm && resumeMessage) {
            if (item.status === 'paused') {
                resumeForm.style.display = '';
                resumeForm.dataset.itemId = itemId;
                resumeMessage.value = '';
            } else {
                resumeForm.style.display = 'none';
                resumeForm.dataset.itemId = '';
            }
        }

        // Load work log
        const logEl = document.getElementById('detail-log');
        try {
            const log = await Api.getWorkLog(itemId);
            if (log.length > 0) {
                logEl.innerHTML = log.map(e =>
                    `<div class="log-entry log-entry-${e.entry_type}"><span class="log-meta">[${e.timestamp}] ${e.entry_type}:</span> <div class="log-content">${DialogUtils.renderMarkdown(e.content)}</div></div>`
                ).join('');
                DialogUtils.runMermaid(logEl);
                // Scroll to end after initial load
                DialogCore.forceAutoScroll(logEl);
            } else {
                logEl.innerHTML = '<div class="log-entry">No work log entries</div>';
            }
        } catch {
            logEl.innerHTML = '';
        }

        // Load attachments
        DialogCore._currentItemId = itemId;
        await Attachments._loadAttachments(itemId);

        // Preselect Work Log tab if agent is running or item is done, otherwise show description tab
        const defaultTab = (isAgentActive || item.column_name === 'done') ? 'detail-wlog' : 'detail-desc';
        this.switchDetailTab(defaultTab);

        DialogCore.open('detail-dialog');
    },

    async submitResume(event) {
        if (event) event.preventDefault();
        const form = document.getElementById('detail-resume-form');
        const messageEl = document.getElementById('detail-resume-message');
        const itemId = form ? form.dataset.itemId : '';
        if (!itemId) return;
        const message = (messageEl && messageEl.value || '').trim() || null;
        DialogCore.close('detail-dialog');
        await Board.resumeAgent(itemId, message);
    },

    switchDetailTab(tabName) {
        document.querySelectorAll('#detail-dialog .review-tab').forEach(t => {
            t.classList.toggle('active', t.dataset.tab === tabName);
        });
        document.querySelectorAll('#detail-dialog .review-tab-content').forEach(c => {
            c.style.display = 'none';
            c.classList.remove('active');
        });
        const active = document.getElementById(`detail-tab-${tabName}`);
        if (active) {
            active.style.display = '';
            active.classList.add('active');

            // Force scroll to end when switching to work log tab (explicit user action)
            if (tabName === 'detail-wlog') {
                const logEl = document.getElementById('detail-log');
                if (logEl && logEl.children.length > 0) {
                    DialogCore.forceAutoScroll(logEl);
                }
            }
        }
    },

    async _showDetailDirect(itemId) {
        const items = await Api.getItems();
        const item = items.find(i => i.id === itemId);
        if (!item) return;

        document.getElementById('detail-title').textContent = item.title;
        const detailBodyEl = document.getElementById('detail-body');
        detailBodyEl.innerHTML = DialogUtils.renderMarkdown(item.description || '(no description)');
        DialogUtils.runMermaid(detailBodyEl);

        const editBtn = document.getElementById('detail-edit-btn');
        const deleteBtn = document.getElementById('detail-delete-btn');
        const isQuestions = item.column_name === 'questions';
        editBtn.style.display = isQuestions ? 'none' : '';
        deleteBtn.style.display = isQuestions ? 'none' : '';
        editBtn.onclick = () => { DialogCore.close('detail-dialog'); ItemDialog.openEditItem(item); };

        const oldPlay = document.getElementById('detail-play-btn');
        if (oldPlay) oldPlay.remove();

        // Hide auto-approve toggle in the questions fallback view.
        const autoApproveWrap = document.getElementById('detail-auto-approve-wrap');
        const autoApproveSelect = document.getElementById('detail-auto-approve');
        if (autoApproveWrap) autoApproveWrap.style.display = 'none';
        if (autoApproveSelect) autoApproveSelect.onchange = null;

        // _showDetailDirect is the fallback for items in the questions column,
        // which are never paused — but defensively hide the resume form so it
        // never carries over from a previous open of a paused item.
        const resumeForm = document.getElementById('detail-resume-form');
        if (resumeForm) {
            resumeForm.style.display = 'none';
            resumeForm.dataset.itemId = '';
        }

        const logEl = document.getElementById('detail-log');
        try {
            const log = await Api.getWorkLog(itemId);
            logEl.innerHTML = log.length > 0
                ? log.map(e => `<div class="log-entry log-entry-${e.entry_type}"><span class="log-meta">[${e.timestamp}] ${e.entry_type}:</span> <div class="log-content">${DialogUtils.renderMarkdown(e.content)}</div></div>`).join('')
                : '<div class="log-entry">No work log entries</div>';
            // Scroll to end after initial load
            if (log.length > 0) {
                DialogUtils.runMermaid(logEl);
                DialogCore.forceAutoScroll(logEl);
            }
        } catch { logEl.innerHTML = ''; }

        // Preselect Work Log tab if agent is active or item is done, otherwise show description tab
        const isAgentActiveOrDone = item.status === 'running' || item.status === 'resolving_conflicts' || item.status === 'paused';
        const defaultTab = (isAgentActiveOrDone || item.column_name === 'done') ? 'detail-wlog' : 'detail-desc';
        this.switchDetailTab(defaultTab);

        DialogCore.open('detail-dialog');
    },
};