{% load lyric_extras %}
{# _bud_panel.html — bud btn + slide-out for the post-share flow on    #}
{# post.html. On success: appends a Line to #id_post_table, fires       #}
{# Brief.showBanner, + updates the .post-header shared-with prose.      #}
{# `sharer_name` (rendered onto data-sharer-name) is the author of the  #}
{# optimistically-appended Line so it matches the persisted post-refresh #}
{# state where Line.author == request.user.                              #}
{% include "apps/billboard/_partials/_bud_apparatus.html" with aria_label="Share with a bud" sharer_name=request.user|at_handle include_suggestions=True %}
<script>
(function () {
    'use strict';

    var panel = document.getElementById('id_bud_panel');

    // Author = the sharer (rendered server-side as data-sharer-name) so the
    // appended Line matches the post-refresh state, where the persisted
    // Line.author is request.user.
    function _appendLine(text) {
        var list = document.getElementById('id_post_table');
        if (!list) return;
        var li = document.createElement('li');
        li.className = 'post-line';
        var author = document.createElement('span');
        author.className = 'post-line-author';
        author.textContent = panel.dataset.sharerName || '';
        var body = document.createElement('span');
        body.className = 'post-line-text';
        body.textContent = text;
        var time = document.createElement('time');
        time.className = 'post-line-time';
        var now = new Date();
        time.dateTime = now.toISOString();
        time.textContent = now.toLocaleTimeString([], {hour: 'numeric', minute: '2-digit'});
        li.appendChild(author);
        li.appendChild(body);
        li.appendChild(time);
        var buffer = list.querySelector('.post-line-buffer');
        if (buffer) list.insertBefore(li, buffer);
        else list.appendChild(li);
    }

    // The shared-with header lives outside #id_bud_panel — two <p> siblings
    // under .post-header. State transitions:
    //   0 → 1+ recipients : "just me, X" → "shared between {chip}" + "& me, X"
    //   ≥1 → +1 recipients: append chip + ", " separator before existing.
    // `userId` is stamped onto the chip as data-user-id so a later duplicate-
    // share attempt can highlight this same element via .bud-duplicate-flash.
    // Insert the SERVER-RENDERED chip (`chipHtml` from share_post's
    // `_post_recipient.html`) so the async append carries the same
    // `post-recipient post-attribution` classes + @handle as a post-refresh —
    // fixes the chip rendering bare (no --quaUser) until reload.
    function _appendRecipientChip(chipHtml) {
        if (!chipHtml) return;
        var header = document.querySelector('.post-page .post-header');
        if (!header) return;
        var existingRecipients = header.querySelector('.post-shared-recipients');
        var selfLine = header.querySelector('.post-shared-self');

        var tpl = document.createElement('template');
        tpl.innerHTML = chipHtml.trim();
        var chip = tpl.content.firstElementChild;
        if (!chip) return;

        if (existingRecipients) {
            existingRecipients.appendChild(document.createTextNode(', '));
            existingRecipients.appendChild(chip);
            return;
        }

        var recipientsLine = document.createElement('p');
        recipientsLine.className = 'post-shared-recipients';
        recipientsLine.appendChild(document.createTextNode('shared between '));
        recipientsLine.appendChild(chip);
        if (selfLine) {
            header.insertBefore(recipientsLine, selfLine);
            // Flip ONLY the leading "just me," text node so the self line's
            // own .post-attribution span (the owner's handle) survives.
            var lead = selfLine.firstChild;
            if (lead && lead.nodeType === 3) {
                lead.textContent = lead.textContent.replace(/^\s*just me,/, '& me,');
            }
        } else {
            header.appendChild(recipientsLine);
        }
    }

    bindBudBtn({
        submitUrl: '{% url "billboard:share_post" post.id %}',
        autocompleteUrl: '{% url "billboard:search_buds" %}',
        onSuccess: function (data) {
            if (data.line_text) _appendLine(data.line_text);
            if (window.Brief && data.brief) Brief.showBanner(data.brief);
            if (data.recipient_chip_html) {
                _appendRecipientChip(data.recipient_chip_html);
            }
        },
        duplicateTargetSelector: function (data) {
            return '.post-recipient[data-user-id="' + data.recipient_user_id + '"]';
        },
    });
}());
</script>
