/* ═══════════════════════════════════════════════
   Article Editor — script.js
   Copy-as-Markdown for text cards
   ═══════════════════════════════════════════════ */

(function () {
    'use strict';

    /* ── Heading prefix map (avoids 4 identical branches) ── */

    const HEADING_PREFIX = { h1: '# ', h2: '## ', h3: '### ', h4: '#### ' };

    /* ── Event delegation: copy button ── */

    document.addEventListener('click', function (e) {
        const btn = e.target.closest('.btn-copy-md');
        if (!btn) return;
        copyCardAsMarkdown(btn);
    });

    /* ── Copy handler ── */

    function copyCardAsMarkdown(btn) {
        const card = btn.closest('.text-card');
        if (!card) return;

        const clone = card.cloneNode(true);
        const topBar = clone.querySelector('.card-top-bar');
        if (topBar) topBar.remove();

        const md = htmlToMarkdown(clone).replace(/\n{3,}/g, '\n\n').trim();

        if (!navigator.clipboard) return;
        navigator.clipboard.writeText(md).then(function () {
            const icon = btn.querySelector('i');
            icon.className = 'bi bi-check2';
            btn.classList.add('copied');
            btn.lastChild.textContent = ' Copied!';
            setTimeout(function () {
                icon.className = 'bi bi-clipboard';
                btn.classList.remove('copied');
                btn.lastChild.textContent = ' Copy';
            }, 2000);
        }).catch(function () {
            /* Clipboard API unavailable (e.g. insecure context) — fail silently */
        });
    }

    /* ── Block-level HTML → Markdown ── */

    function htmlToMarkdown(el) {
        let md = '';
        for (let i = 0; i < el.childNodes.length; i++) {
            const node = el.childNodes[i];

            /* Text node */
            if (node.nodeType === 3) {
                const t = node.textContent;
                if (/^\s*$/.test(t)) continue;
                md += t.replace(/\s+/g, ' ');
                continue;
            }
            if (node.nodeType !== 1) continue;

            const tag = node.tagName.toLowerCase();

            /* Headings */
            if (HEADING_PREFIX[tag]) {
                md += HEADING_PREFIX[tag] + inlineToMd(node).trim() + '\n\n';
            }
            /* Paragraph */
            else if (tag === 'p') {
                md += inlineToMd(node).trim() + '\n\n';
            }
            /* Lists */
            else if (tag === 'ul') { md += listToMd(node, false, 0) + '\n'; }
            else if (tag === 'ol') { md += listToMd(node, true, 0) + '\n'; }
            /* Blockquote */
            else if (tag === 'blockquote') {
                const lines = htmlToMarkdown(node).trim().split('\n');
                md += lines.map(function (l) { return '> ' + l; }).join('\n') + '\n\n';
            }
            /* Code block */
            else if (tag === 'pre') {
                const code = node.querySelector('code');
                md += '```\n' + (code ? code.textContent : node.textContent).trim() + '\n```\n\n';
            }
            /* Image */
            else if (tag === 'img') {
                md += '![' + (node.getAttribute('alt') || '') + '](' + (node.getAttribute('src') || '') + ')\n\n';
            }
            /* Image placeholder */
            else if (tag === 'div' && node.classList.contains('image-placeholder')) {
                const phDesc = node.querySelector('.ph-desc');
                const desc = phDesc ? phDesc.textContent.trim() : node.textContent.trim().replace(/\s+/g, ' ');
                md += '*[New image: ' + desc + ']*\n\n';
            }
            /* Generic container — recurse */
            else { md += htmlToMarkdown(node); }
        }
        return md;
    }

    /* ── Inline HTML → Markdown ── */

    function inlineToMd(el) {
        let r = '';
        for (let i = 0; i < el.childNodes.length; i++) {
            const n = el.childNodes[i];
            if (n.nodeType === 3) { r += n.textContent.replace(/\s+/g, ' '); continue; }
            if (n.nodeType !== 1) continue;

            const t = n.tagName.toLowerCase();
            const inner = inlineToMd(n);

            if (t === 'strong' || t === 'b') r += '**' + inner + '**';
            else if (t === 'em' || t === 'i') r += '*' + inner + '*';
            else if (t === 'code') r += '`' + n.textContent + '`';
            else if (t === 'a') r += '[' + inner + '](' + (n.getAttribute('href') || '') + ')';
            else if (t === 'del' || t === 's') r += '~~' + inner + '~~';
            else if (t === 'br') r += '\n';
            else r += inner;
        }
        return r;
    }

    /* ── List HTML → Markdown ── */

    function listToMd(el, ordered, depth) {
        let md = '';
        let count = 1;
        for (let i = 0; i < el.children.length; i++) {
            const li = el.children[i];
            if (li.tagName.toLowerCase() !== 'li') continue;

            const indent = '  '.repeat(depth);
            const prefix = ordered ? (count + '. ') : '- ';
            let content = '';

            for (let j = 0; j < li.childNodes.length; j++) {
                const ch = li.childNodes[j];
                if (ch.nodeType === 3) {
                    content += ch.textContent.replace(/\s+/g, ' ');
                } else if (ch.nodeType === 1) {
                    const ct = ch.tagName.toLowerCase();
                    if (ct === 'ul') content = content.trimEnd() + '\n' + listToMd(ch, false, depth + 1);
                    else if (ct === 'ol') content = content.trimEnd() + '\n' + listToMd(ch, true, depth + 1);
                    else content += inlineToMd(ch);
                }
            }
            md += indent + prefix + content.trim() + '\n';
            count++;
        }
        return md;
    }

    /* ── Checkbox & Copy Updates ── */

    var copyUpdatesBtn = document.getElementById('btnCopyUpdates');
    var updatesCountSpan = copyUpdatesBtn ? copyUpdatesBtn.querySelector('.copy-updates-count') : null;
    var updatesTextSpan = copyUpdatesBtn ? copyUpdatesBtn.querySelector('.copy-updates-text') : null;

    function updateCopyUpdatesButton() {
        var count = document.querySelectorAll('.change-checkbox:checked').length;
        var total = document.querySelectorAll('.change-checkbox').length;
        if (!copyUpdatesBtn || total === 0) return;
        copyUpdatesBtn.classList.add('visible');
        if (count > 0) {
            if (updatesTextSpan) updatesTextSpan.textContent = 'Copy updates';
            if (updatesCountSpan) { updatesCountSpan.textContent = count; updatesCountSpan.style.display = ''; }
        } else {
            if (updatesTextSpan) updatesTextSpan.textContent = 'Copy all';
            if (updatesCountSpan) updatesCountSpan.style.display = 'none';
        }
    }

    /* Show button on page load if there are change blocks */
    updateCopyUpdatesButton();

    document.addEventListener('change', function (e) {
        if (e.target.classList.contains('change-checkbox')) {
            updateCopyUpdatesButton();
        }
    });

    if (copyUpdatesBtn) {
        copyUpdatesBtn.addEventListener('click', function () {
            var md = buildUpdatesPrompt();
            if (!navigator.clipboard) return;
            navigator.clipboard.writeText(md).then(function () {
                var icon = copyUpdatesBtn.querySelector('i');
                copyUpdatesBtn.classList.add('copied');
                icon.className = 'bi bi-check2';
                if (updatesTextSpan) updatesTextSpan.textContent = 'Copied!';
                setTimeout(function () {
                    copyUpdatesBtn.classList.remove('copied');
                    icon.className = 'bi bi-clipboard-check';
                    updateCopyUpdatesButton();
                }, 2000);
            });
        });
    }

    function buildUpdatesPrompt() {
        /* Extract article metadata from the DOM */
        var title = document.querySelector('.about-card h1').textContent.trim();
        var metaItems = document.querySelectorAll('.about-meta-item');
        var publishedDate = '', updatedDate = '';
        for (var i = 0; i < metaItems.length; i++) {
            var text = metaItems[i].textContent.trim();
            if (text.indexOf('Published:') === 0) publishedDate = text.replace('Published:', '').trim();
            if (text.indexOf('Updated:') === 0) updatedDate = text.replace('Updated:', '').trim();
        }
        var summary = document.querySelector('.about-summary').textContent.trim();
        var articleRoute = document.body.getAttribute('data-article-route') || '[ARTICLE_ROUTE]';

        /* Full prompt (ADJUST-ARTICLE-PROMPT.md inlined) */
        var md = '';
        md += '# Adjust Article — Style-Matching Prompt\n\n';
        md += 'You are applying factual updates to an existing BRIX Templates blog post. The updates below were found by an AI research agent that verified every claim against current sources. The **data is correct**, but the **wording may not match** the article\'s original voice.\n\n';
        md += 'Your job: apply each update while preserving the article\'s exact writing style, tone, and structure. You are **updating**, not rewriting.\n\n';
        md += '---\n\n';
        md += '## Core Rules\n\n';
        md += '1. **Read the original article first.** Before changing anything, read the full article to internalize its voice — sentence length, vocabulary level, use of analogies, heading style, how it addresses the reader.\n';
        md += '2. **Change only what the update requires.** If an update says a price changed from $14 to $16, change the number. Don\'t rewrite the surrounding paragraph.\n';
        md += '3. **Preserve paragraph flow.** When a sentence changes mid-paragraph, make sure the updated sentence still reads naturally in context. Adjust connecting words if needed, but nothing more.\n';
        md += '4. **Don\'t add commentary.** No "As of 2026..." or "Recently updated to..." unless the original article already uses that pattern.\n';
        md += '5. **Don\'t fix existing style issues.** If the original article breaks a style rule below (e.g., a heading missing "Webflow"), leave it. You\'re here to update facts, not do editorial cleanup.\n';
        md += '6. **New content follows the rules below.** When a change requires adding new text (a new paragraph, a new section, new list items), that new text must follow the BRIX Templates style rules in this document.\n';
        md += '7. **Preserve existing formatting patterns.** If the article already uses a specific format for prices, lists, or any recurring element, keep that exact format. Only apply the style rules below to **completely new** text that has no existing pattern to follow.\n\n';
        md += '---\n\n';
        md += '## Style Rules (apply only to text you write or rewrite)\n\n';
        md += '### Tone\n\n';
        md += '- Professional but approachable — write like you\'re explaining to a colleague, not a technical manual\n';
        md += '- Direct and concise — get to the point without unnecessary words\n';
        md += '- Confident but humble — present solutions with certainty but acknowledge alternatives\n';
        md += '- Helpful without being condescending — assume the reader is intelligent but new to this specific topic\n';
        md += '- Conversational but not casual — use contractions and direct address but maintain professionalism\n\n';
        md += '### Formatting\n\n';
        md += '| Element | Rule | Example |\n';
        md += '|---------|------|---------|  \n';
        md += '| UI elements | Always bold | Click the **Save** button, open the **Settings** panel |\n';
        md += '| Field names | Always bold | Enter the URL in the **Redirect URL** field |\n';
        md += '| Headings | Sentence case only | "How to create a download button in Webflow" |\n';
        md += '| Headings | Include "Webflow" in all H2 and H3 | "Setting up redirects in Webflow" |\n';
        md += '| Code references | Bold, never backticks inline | Use **brix-attribute="value"** |\n';
        md += '| Prices | Match the article\'s existing price format exactly | Only use "$X/mo billed yearly \\| $X/mo billed monthly" for brand-new sections with no existing pattern |\n';
        md += '| Links | Descriptive anchor text | [Webflow\'s pricing page](https://webflow.com/pricing) |\n';
        md += '| Lists | Flat sequential numbering | Avoid deeply nested bullets; use clear step labels |\n\n';
        md += '### Structured information\n\n';
        md += 'When describing features, benefits, plans, or similar structured content, use this format:\n\n';
        md += '**Bold title or category**: Followed by the explanation or details\n\n';
        md += '### New Sections\n\n';
        md += 'When a change requires an entirely new section (e.g., a plan that didn\'t exist before, a feature that was added):\n\n';
        md += '1. **Mirror the existing pattern.** Look at how the article handles similar sections. If each plan gets an H3 + intro paragraph + bullet list, follow that exact structure.\n';
        md += '2. **Place it logically.** Insert the new section where it makes sense in the article\'s flow.\n';
        md += '3. **Don\'t over-write.** Match the depth and length of surrounding sections.\n';
        md += '4. **All style rules above apply** to new content since there\'s no existing style to preserve.\n\n';
        md += '---\n\n';
        md += '## Changes to Apply\n\n';

        /* Determine mode: selected changes vs all changes */
        var checkedBoxes = document.querySelectorAll('.change-checkbox:checked');
        var isAll = checkedBoxes.length === 0;
        var blocks;
        if (isAll) {
            blocks = document.querySelectorAll('.change-block');
            md += '**Note:** These are ALL the changes the research AI found. I copied them all without reviewing which ones are truly necessary. Some may be minor or debatable. Part of your task is to evaluate each change and recommend which ones should actually be applied and which ones can be skipped.\n\n';
        } else {
            blocks = [];
            for (var b = 0; b < checkedBoxes.length; b++) {
                var bl = checkedBoxes[b].closest('.change-block');
                if (bl) blocks.push(bl);
            }
        }

        md += 'The changes below were identified by a research AI agent. The data is **factually correct** — prices, plan names, feature limits, and dates have been verified against official sources. However, the wording and formatting **almost certainly don\'t match** the original article\'s style. Expect wrong heading case, missing bold on UI elements, different tone, and other formatting issues.\n\n';
        md += 'For each change, read the original text in the article, understand what the factual update is, and rewrite it so the new data fits naturally into the article\'s existing voice and formatting.\n\n';
        md += '### Output format\n\n';
        md += 'For each change, output your adjusted version using this exact format:\n\n';
        md += '**BEFORE** (copy the exact current text from the article):\n\n';
        md += '> [exact text as it currently appears in the article]\n\n';
        md += '**AFTER** (your version with the correct data AND proper style):\n\n';
        md += '> [adjusted text — factually updated, style-matched, ready to paste into the article]\n\n';
        md += 'Please deliver your full response in Markdown format.\n\n';
        md += '---\n\n';
        md += '**Article:** ' + title + '\n';
        md += '**Route:** `' + articleRoute + '`\n';
        md += '**Published:** ' + publishedDate + '\n';
        md += '**Updated:** ' + updatedDate + '\n';
        md += '**Summary:** ' + summary + '\n\n';
        md += '---\n\n';

        /* Build changes */
        for (var j = 0; j < blocks.length; j++) {
            var block = blocks[j];
            if (!block) continue;

            var location = block.querySelector('.change-location');
            var locationText = location ? location.textContent.trim() : 'Change';
            var changeNum = block.querySelector('.change-number');
            var changeLabel = changeNum ? changeNum.textContent.trim() : 'Change ' + (j + 1);

            md += '## ' + locationText + '\n\n';

            var cards = block.querySelectorAll('.text-card');
            var oldCard = null, newCard = null;
            for (var k = 0; k < cards.length; k++) {
                if (cards[k].querySelector('.badge-old')) oldCard = cards[k];
                if (cards[k].querySelector('.badge-new')) newCard = cards[k];
            }

            if (oldCard) {
                var oldClone = oldCard.cloneNode(true);
                var oldTopBar = oldClone.querySelector('.card-top-bar');
                if (oldTopBar) oldTopBar.remove();
                md += '[[' + changeLabel.toUpperCase() + ' - OLD TEXT]]\n\n';
                md += htmlToMarkdown(oldClone).replace(/\n{3,}/g, '\n\n').trim();
                md += '\n\n';
            }

            if (newCard) {
                var newClone = newCard.cloneNode(true);
                var newTopBar = newClone.querySelector('.card-top-bar');
                if (newTopBar) newTopBar.remove();
                md += '[[' + changeLabel.toUpperCase() + ' - NEW TEXT]]\n\n';
                md += htmlToMarkdown(newClone).replace(/\n{3,}/g, '\n\n').trim();
                md += '\n\n';
            }

            /* Reasoning + sources */
            var reasoning = block.querySelector('.reasoning');
            if (reasoning) {
                var reasonClone = reasoning.cloneNode(true);
                var sourcesDiv = reasonClone.querySelector('.reasoning-sources');
                var sourceLinks = [];
                if (sourcesDiv) {
                    var anchors = sourcesDiv.querySelectorAll('a');
                    for (var s = 0; s < anchors.length; s++) {
                        sourceLinks.push('[' + anchors[s].textContent.trim() + '](' + anchors[s].href + ')');
                    }
                    sourcesDiv.remove();
                }
                var reasonText = reasonClone.textContent.trim().replace(/^Reasoning for changes:\s*/i, '');
                md += '[[' + changeLabel.toUpperCase() + ' - SOURCES AND REASONING]]\n\n';
                md += reasonText + '\n';
                if (sourceLinks.length > 0) {
                    md += 'Sources: ' + sourceLinks.join(' | ') + '\n';
                }
                md += '\n';
            }

            md += '---\n\n';
        }

        return md.trim();
    }
})();
