/* ============================================================================
 * TraderAlign — Shared Account Picker JS (search / first-5 + Show More).
 *
 * Extracted verbatim from public/journal.php's "Right Now" workspace
 * (2026-07-29 session) — one real implementation, loaded by both
 * public/journal.php and public/trading-center.php via <script src>, so
 * there is exactly one copy of this behavior in the app, not two.
 * Operates purely on the .rn-account-picker* / .rn-account-item /
 * .rn-acct-extra / .rn-show-more-accts markup produced by
 * src/AccountPicker.php's apRenderAccountPicker() (and, on journal.php,
 * by renderRnAccountPicker(), which now delegates to that same function).
 * ============================================================================ */

function rnToggleAccountPicker(btn) {
    var panel = btn.nextElementSibling;
    if (!panel) return;
    var isOpen = panel.style.display !== 'none';
    document.querySelectorAll('.rn-account-picker-panel').forEach(function (p) { p.style.display = 'none'; });
    if (isOpen) return;
    panel.style.display = 'block';
    // Inline panels (apRenderAccountPicker($expanded=true)) are laid out
    // in-page (position:static, set by their own CSS), not a floating
    // dropdown — never computed here.
    if (!panel.classList.contains('rn-account-picker-panel-inline')) {
        // position:fixed has no "anchor to my parent" concept — compute
        // top/left from the trigger button's real on-screen position
        // instead (2026-08-06 fix), flipping above/left of the button
        // whenever the default below/right-aligned placement would run
        // off the viewport. A static right:0 anchor can't work for every
        // placement this shared picker is used at (some sit near the
        // page's left edge, others near the right), so this must be
        // computed per-open, the same technique already used for the
        // Impact-rating popover elsewhere in this app.
        var rect = btn.getBoundingClientRect();
        var panelRect = panel.getBoundingClientRect();
        var margin = 8;
        var left = rect.right - panelRect.width;
        if (left < margin) left = margin;
        if (left + panelRect.width > window.innerWidth - margin) left = window.innerWidth - margin - panelRect.width;
        var top = rect.bottom + 8;
        if (top + panelRect.height > window.innerHeight - margin) top = rect.top - panelRect.height - 8;
        if (top < margin) top = margin;
        panel.style.left = left + 'px';
        panel.style.top = top + 'px';
    }
    var search = panel.querySelector('.rn-account-search');
    if (search) { search.value = ''; search.focus({ preventScroll: true }); }
}
document.addEventListener('click', function (e) {
    if (!e.target.closest('.rn-account-picker')) {
        // Inline panels (apRenderAccountPicker($expanded=true)) have no
        // toggle button to reopen them with, so a stray click elsewhere on
        // the page must never hide one — only the collapsible-dropdown
        // panels close on outside-click.
        document.querySelectorAll('.rn-account-picker-panel:not(.rn-account-picker-panel-inline)').forEach(function (p) { p.style.display = 'none'; });
    }
});
// A position:fixed panel doesn't track its trigger as the page scrolls —
// closing on scroll (rather than repositioning on every scroll event) is
// the simpler, still-correct behavior for a short-lived dropdown like
// this one. MUST use capture:true to observe scroll at all here (scroll
// events don't bubble), but that means this fires for the account LIST's
// own internal overflow-y:auto scrolling too, not just real page scroll
// — a real, confirmed bug found live: it closed the panel the instant it
// opened (autofocusing the search box triggers a scroll-into-view) and
// again the moment a trader tried to scroll through the account list
// itself. Fixed by ignoring any scroll whose target is inside the panel
// — only a scroll OUTSIDE the open panel should ever close it.
window.addEventListener('scroll', function (e) {
    document.querySelectorAll('.rn-account-picker-panel:not(.rn-account-picker-panel-inline)').forEach(function (p) {
        if (p.style.display !== 'none' && !(e.target && p.contains(e.target))) p.style.display = 'none';
    });
}, true);
function rnFilterAccounts(input) {
    var panel = input.closest('.rn-account-picker-panel');
    var moreBtn = panel.querySelector('.rn-show-more-accts');
    var q = input.value.trim().toLowerCase();
    var items = panel.querySelectorAll('.rn-account-item');
    if (q === '') {
        var expanded = moreBtn ? moreBtn.getAttribute('data-expanded') === '1' : true;
        items.forEach(function (item) {
            var isExtra = item.classList.contains('rn-acct-extra');
            item.style.display = (isExtra && !expanded) ? 'none' : '';
        });
        if (moreBtn) moreBtn.style.display = '';
    } else {
        items.forEach(function (item) {
            var match = (item.getAttribute('data-search') || '').indexOf(q) !== -1;
            item.style.display = match ? '' : 'none';
        });
        if (moreBtn) moreBtn.style.display = 'none';
    }
}
function rnToggleAccountsMore(btn) {
    var panel = btn.closest('.rn-account-picker-panel');
    var expanded = btn.getAttribute('data-expanded') === '1';
    panel.querySelectorAll('.rn-acct-extra').forEach(function (item) { item.style.display = expanded ? 'none' : ''; });
    btn.setAttribute('data-expanded', expanded ? '0' : '1');
    btn.textContent = expanded ? btn.getAttribute('data-more-label') : 'Show Less';
}
