/* ============================================================================
 * TraderAlign — Shared Trade Screenshot upload/view/delete modal.
 *
 * Restored 2026-08-18 as its own feature, separate from "View Trade"
 * (which stays exactly as-is — a disabled "Coming Soon" placeholder for
 * the future interactive chart-replay column, untouched by this file).
 * Loaded by both public/journal.php (Active Journeys' renderRnTradeTable())
 * and public/journal-validation.php's trade cards, via <script src>, so
 * there is exactly one implementation of "open the modal, list existing
 * screenshots, upload a new one, delete one" in the app, not two.
 *
 * Talks to POST /api/journal/upload-screenshot, GET /api/journal/trade-
 * screenshots, POST /api/journal/delete-screenshot. Every caller page
 * must render the same modal markup once, with these exact ids:
 *   #rn-screenshot-modal-backdrop, #rn-screenshot-modal-body,
 *   #rn-screenshot-modal-file, #rn-screenshot-modal-error
 * and mark each screenshot-cell/badge element with
 * class="rn-screenshot-badge" data-trade-id="<id>" so
 * rnUpdateScreenshotBadge() can find and refresh it after an
 * upload/delete without a full page reload.
 * ============================================================================ */

var _rnScreenshotCurrentTradeId = null;

function rnOpenScreenshotModal(tradeId) {
    _rnScreenshotCurrentTradeId = tradeId;
    document.getElementById('rn-screenshot-modal-error').style.display = 'none';
    document.getElementById('rn-screenshot-modal-file').value = '';
    var bd = document.getElementById('rn-screenshot-modal-backdrop');
    bd.style.display = 'flex';
    document.body.style.overflow = 'hidden';
    rnRefreshScreenshotList(tradeId);
}

function rnCloseScreenshotModal() {
    document.getElementById('rn-screenshot-modal-backdrop').style.display = 'none';
    document.body.style.overflow = '';
    _rnScreenshotCurrentTradeId = null;
}

function rnRefreshScreenshotList(tradeId) {
    var body = document.getElementById('rn-screenshot-modal-body');
    body.innerHTML = '<p style="font-size:.8rem;color:var(--foreground-dim)">Loading…</p>';
    fetch('/traderalign/api/journal/trade-screenshots?trade_id=' + encodeURIComponent(tradeId))
        .then(function (r) { return r.json(); })
        .then(function (data) {
            var screenshots = (data && data.success) ? data.screenshots : [];
            rnRenderScreenshotGrid(screenshots);
            rnUpdateScreenshotBadge(tradeId, screenshots.length);
        })
        .catch(function () {
            body.innerHTML = '<p style="font-size:.8rem;color:var(--negative)">Could not load screenshots.</p>';
        });
}

function rnRenderScreenshotGrid(screenshots) {
    var body = document.getElementById('rn-screenshot-modal-body');
    if (!screenshots.length) {
        body.innerHTML = '<p style="font-size:.8rem;color:var(--foreground-dim)">No screenshots uploaded yet for this trade.</p>';
        return;
    }
    var html = '<div class="rn-screenshot-grid">';
    screenshots.forEach(function (s) {
        html += '<div class="rn-screenshot-thumb">'
            + '<a href="' + s.url + '" target="_blank" rel="noopener"><img src="' + s.url + '" alt="Trade screenshot" loading="lazy"></a>'
            + '<button type="button" class="rn-screenshot-delete" title="Delete this screenshot" onclick="rnDeleteScreenshot(\'' + s.id + '\')">✕</button>'
            + '</div>';
    });
    html += '</div>';
    body.innerHTML = html;
}

function rnUploadScreenshot() {
    var tradeId = _rnScreenshotCurrentTradeId;
    var fileInput = document.getElementById('rn-screenshot-modal-file');
    var errEl = document.getElementById('rn-screenshot-modal-error');
    errEl.style.display = 'none';
    if (!tradeId || !fileInput.files || !fileInput.files.length) {
        errEl.textContent = 'Choose an image first.';
        errEl.style.display = 'block';
        return;
    }
    var fd = new FormData();
    fd.append('trade_id', tradeId);
    fd.append('screenshot', fileInput.files[0]);

    var btn = document.getElementById('rn-screenshot-upload-btn');
    btn.disabled = true;
    btn.textContent = 'Uploading…';

    fetch('/traderalign/api/journal/upload-screenshot', { method: 'POST', body: fd })
        .then(function (r) { return r.json(); })
        .then(function (data) {
            btn.disabled = false;
            btn.textContent = 'Upload';
            if (data && data.success) {
                fileInput.value = '';
                rnRefreshScreenshotList(tradeId);
            } else {
                errEl.textContent = (data && data.error) ? data.error : 'Could not upload screenshot.';
                errEl.style.display = 'block';
            }
        })
        .catch(function () {
            btn.disabled = false;
            btn.textContent = 'Upload';
            errEl.textContent = 'Could not upload screenshot.';
            errEl.style.display = 'block';
        });
}

function rnDeleteScreenshot(screenshotId) {
    if (!window.confirm('Delete this screenshot?')) return;
    var tradeId = _rnScreenshotCurrentTradeId;
    fetch('/traderalign/api/journal/delete-screenshot', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ screenshot_id: screenshotId })
    }).then(function (r) { return r.json(); }).then(function () {
        if (tradeId) rnRefreshScreenshotList(tradeId);
    });
}

/** Updates every screenshot badge for this trade on the current page (a trade can appear in more than one place, e.g. Active Journeys' phase table + Full Coaching Analysis) without a full reload. */
function rnUpdateScreenshotBadge(tradeId, count) {
    document.querySelectorAll('.rn-screenshot-badge[data-trade-id="' + tradeId + '"]').forEach(function (el) {
        el.textContent = count > 0 ? ('📷 ' + count) : '+ Add';
        el.classList.toggle('rn-screenshot-badge-empty', count === 0);
    });
}
