<div class="modal fade loot-offerwall-modal" id="offerwallModal" tabindex="-1" aria-labelledby="offerwallModalTitle" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-fullscreen-lg-down modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <div class="min-w-0">
                    <span class="loot-status success mb-50" id="offerwallModalProvider">Offer</span>
                    <h4 class="modal-title loot-section-title text-truncate" id="offerwallModalTitle">Loading offer</h4>
                    <p class="loot-muted mb-0" id="offerwallModalSubtitle">Review the milestone before starting.</p>
                </div>
                <div class="d-flex align-items-center gap-50">
                    <a class="btn btn-sm btn-outline-light d-none" id="offerwallExternalLink" href="#" target="_blank" rel="noopener">
                        Open new tab
                    </a>
                    <button type="button" class="btn-close loot-modal-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
            </div>
            <div class="modal-body p-0">
                <div class="loot-offer-preview" id="offerwallPreview">
                    <div class="loot-offer-preview-top">
                        <div class="loot-offer-preview-image">
                            <img id="offerwallPreviewImage" src="" alt="">
                            <div class="loot-card-platforms" id="offerwallPreviewDevices"></div>
                        </div>
                        <div class="loot-offer-preview-meta">
                            <span class="loot-pill" id="offerwallPreviewProvider"><i data-feather="send"></i>Provider</span>
                            <span class="loot-reward-pill"><i data-feather="dollar-sign"></i><strong id="offerwallPreviewReward">$0.00</strong></span>
                            <span class="loot-pill" id="offerwallPreviewCategory">Other</span>
                        </div>
                    </div>

                    <button class="btn btn-loot loot-start-offer-btn" type="button" id="offerwallStartButton">
                        <i data-feather="play"></i>Start Offer
                    </button>

                    <p class="loot-offer-requirements" id="offerwallPreviewRequirements"></p>

                    <div class="loot-offer-detail-block">
                        <h5 class="loot-section-title">Rewards</h5>
                        <div id="offerwallPreviewRewards" class="loot-offer-detail-list"></div>
                    </div>

                    <div class="loot-offer-detail-block">
                        <h5 class="loot-section-title">Steps</h5>
                        <div id="offerwallPreviewSteps" class="loot-offer-detail-list"></div>
                    </div>
                </div>

                <div class="loot-offerwall-loader d-none" id="offerwallLoader">
                    <span class="spinner-border spinner-border-sm"></span>
                    <strong>Preparing your tracked offer...</strong>
                </div>
                <iframe id="offerwallFrame" class="loot-offerwall-frame d-none" title="Offerwall" allow="clipboard-read; clipboard-write; fullscreen"></iframe>
                <div class="loot-offerwall-external d-none" id="offerwallExternal">
                    <i data-feather="external-link"></i>
                    <h3 class="loot-section-title">This provider opens in a new tab</h3>
                    <p class="loot-muted">We tracked your click. Use the button below if the provider did not open automatically.</p>
                    <a class="btn btn-loot" id="offerwallExternalButton" href="#" target="_blank" rel="noopener">Open provider</a>
                </div>
            </div>
        </div>
    </div>
</div>

@once
    @push('scripts')
        <script>
            (function () {
                const modal = document.getElementById('offerwallModal');
                const title = document.getElementById('offerwallModalTitle');
                const provider = document.getElementById('offerwallModalProvider');
                const subtitle = document.getElementById('offerwallModalSubtitle');
                const preview = document.getElementById('offerwallPreview');
                const previewImage = document.getElementById('offerwallPreviewImage');
                const previewProvider = document.getElementById('offerwallPreviewProvider');
                const previewReward = document.getElementById('offerwallPreviewReward');
                const previewCategory = document.getElementById('offerwallPreviewCategory');
                const previewDevices = document.getElementById('offerwallPreviewDevices');
                const previewRequirements = document.getElementById('offerwallPreviewRequirements');
                const previewRewards = document.getElementById('offerwallPreviewRewards');
                const previewSteps = document.getElementById('offerwallPreviewSteps');
                const startButton = document.getElementById('offerwallStartButton');
                const loader = document.getElementById('offerwallLoader');
                const frame = document.getElementById('offerwallFrame');
                const external = document.getElementById('offerwallExternal');
                const externalLink = document.getElementById('offerwallExternalLink');
                const externalButton = document.getElementById('offerwallExternalButton');

                let pendingEndpoint = null;
                let pendingName = null;
                const coinsPerUsd = @json(coins_per_usd());

                // Keep the fixed dialog relative to the viewport, never to a
                // transformed sidebar/content ancestor.
                if (modal && modal.parentElement !== document.body) {
                    document.body.appendChild(modal);
                }

                function parseJson(value, fallback) {
                    try {
                        return JSON.parse(value || 'null') || fallback;
                    } catch (error) {
                        return fallback;
                    }
                }

                function refreshIcons() {
                    if (window.BasketLootIcons) {
                        window.BasketLootIcons.refresh();
                    } else if (window.feather) {
                        window.feather.replace();
                    }
                }

                function platformLabel(platform) {
                    if (platform === 'android') {
                        return 'A';
                    }

                    if (platform === 'ios') {
                        return 'i';
                    }

                    return 'D';
                }

                function setPanel(panel) {
                    preview.classList.toggle('d-none', panel !== 'preview');
                    loader.classList.toggle('d-none', panel !== 'loader');
                    frame.classList.toggle('d-none', panel !== 'frame');
                    external.classList.toggle('d-none', panel !== 'external');
                }

                function renderList(target, items, emptyText, rewardMode) {
                    target.innerHTML = '';
                    const normalized = Array.isArray(items) ? items.filter(Boolean) : [];

                    if (!normalized.length) {
                        const row = document.createElement('div');
                        row.className = 'loot-offer-detail-row';
                        row.textContent = emptyText;
                        target.appendChild(row);
                        return;
                    }

                    normalized.forEach((item, index) => {
                        const row = document.createElement('div');
                        row.className = 'loot-offer-detail-row';

                        if (rewardMode) {
                            const coins = typeof item === 'object' ? (item.coins || item.points || 0) : 0;
                            const label = typeof item === 'object' ? (item.label || item.description || '') : String(item);
                            row.innerHTML = '<span class="loot-mini-coin">$' + (Number(coins) / coinsPerUsd).toFixed(2) + '</span><span></span>';
                            row.lastElementChild.textContent = label || emptyText;
                        } else {
                            row.innerHTML = '<span class="loot-step-number">' + (index + 1) + '</span><span></span>';
                            row.lastElementChild.textContent = typeof item === 'object'
                                ? (item.label || item.title || item.name || emptyText)
                                : String(item);
                        }

                        target.appendChild(row);
                    });
                }

                function setExternal(url) {
                    setPanel('external');
                    externalLink.classList.remove('d-none');
                    externalLink.href = url;
                    externalButton.href = url;
                    window.open(url, '_blank', 'noopener');
                    refreshIcons();
                }

                function setIframe(url) {
                    setPanel('frame');
                    frame.src = url;
                    externalLink.classList.remove('d-none');
                    externalLink.href = url;
                }

                function startTrackedOffer() {
                    if (!pendingEndpoint) {
                        return;
                    }

                    setPanel('loader');
                    subtitle.textContent = 'Keep this window open until the provider confirms completion.';
                    externalLink.classList.add('d-none');

                    fetch(pendingEndpoint, {
                        method: 'POST',
                        headers: {
                            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                            'Accept': 'application/json'
                        }
                    })
                        .then((response) => response.ok ? response.json() : Promise.reject(response))
                        .then((data) => {
                            title.textContent = pendingName || data.name || 'Offerwall';
                            provider.textContent = data.provider || provider.textContent || 'Offer';

                            if (data.launch_mode === 'external') {
                                setExternal(data.url);
                                return;
                            }

                            setIframe(data.url);
                        })
                        .catch(() => {
                            loader.innerHTML = '<strong>Could not open this offer. Please refresh and try again.</strong>';
                        });
                }

                window.previewTrackedOffer = function (button) {
                    if (!button) {
                        return;
                    }

                    pendingEndpoint = button.dataset.openUrl;
                    pendingName = button.dataset.offerName;

                    const devices = parseJson(button.dataset.offerDevices, []);
                    const rewards = parseJson(button.dataset.offerRewards, []);
                    const steps = parseJson(button.dataset.offerSteps, []);
                    const providerName = button.dataset.offerProvider || 'Offer';
                    const image = button.dataset.offerImage || '';

                    title.textContent = pendingName || 'Offer';
                    provider.textContent = providerName;
                    subtitle.textContent = 'Review the milestone before starting.';
                    previewProvider.innerHTML = '<i data-feather="send"></i>' + providerName;
                    previewReward.textContent = '$' + Number(button.dataset.offerReward || 0).toFixed(2);
                    previewCategory.textContent = button.dataset.offerCategory || 'Other';
                    previewRequirements.textContent = button.dataset.offerRequirements || button.dataset.offerDescription || 'This provider did not include requirement text in the synced feed.';
                    previewImage.src = image;
                    previewImage.alt = pendingName || 'Offer';
                    previewDevices.innerHTML = devices.map(function (device) {
                        return '<span title="' + device + '">' + platformLabel(device) + '</span>';
                    }).join('');
                    renderList(previewRewards, rewards, 'Complete the offer to earn the reward shown above.', true);
                    renderList(previewSteps, steps, previewRequirements.textContent || 'Follow the offer instructions to complete it.', false);

                    frame.removeAttribute('src');
                    externalLink.classList.add('d-none');
                    setPanel('preview');
                    refreshIcons();
                };

                window.openTrackedOfferwall = function (button) {
                    if (!button) {
                        return;
                    }

                    pendingEndpoint = button.dataset.openUrl;
                    pendingName = button.dataset.offerName || 'Provider';

                    title.textContent = pendingName;
                    provider.textContent = button.dataset.offerProvider || pendingName;
                    subtitle.textContent = 'Opening the provider wall...';
                    frame.removeAttribute('src');
                    externalLink.classList.add('d-none');
                    setPanel('loader');
                    startTrackedOffer();
                };

                startButton?.addEventListener('click', startTrackedOffer);

                modal?.addEventListener('hidden.bs.modal', function () {
                    frame.removeAttribute('src');
                    pendingEndpoint = null;
                    pendingName = null;
                    loader.innerHTML = '<span class="spinner-border spinner-border-sm"></span><strong>Preparing your tracked offer...</strong>';
                });
            })();
        </script>
    @endpush
@endonce
