const { __ } = wp.i18n;

let activeNotice = null;

const PREMIUM_UPSELL_MESSAGE = __(
    'Upgrade to filter insights by link, browser, device, location, referrer, and much more.',
    'linkcentral'
);

/**
 * Show a dismissible Premium upsell notice on the Insights page.
 */
export function showDrilldownUpsell() {
    if (activeNotice) {
        activeNotice.remove();
        activeNotice = null;
    }

    const noticesSlot = document.getElementById('linkcentral-insights-notices');
    if (!noticesSlot) {
        return;
    }

    const premiumUrl = 'https://www.designforwp.com/product/linkcentral-premium?utm_source=linkcentral_plugin&utm_medium=plugin&utm_campaign=upsell&utm_content=analytics_drilldown_link';

    const notice = document.createElement('div');
    notice.className = 'notice notice-info is-dismissible linkcentral-insights-upsell-notice';
    notice.innerHTML = `
        <p>
            ${PREMIUM_UPSELL_MESSAGE}
            <a href="${premiumUrl}" target="_blank" rel="noopener noreferrer">${__('Get Premium', 'linkcentral')}</a>
        </p>
        <button type="button" class="notice-dismiss">
            <span class="screen-reader-text">${__('Dismiss this notice.', 'linkcentral')}</span>
        </button>
    `;

    notice.querySelector('.notice-dismiss').addEventListener('click', () => {
        notice.remove();
        if (activeNotice === notice) {
            activeNotice = null;
        }
        if (noticesSlot.children.length === 0) {
            noticesSlot.hidden = true;
        }
    });

    noticesSlot.hidden = false;
    noticesSlot.appendChild(notice);
    activeNotice = notice;

    notice.classList.add('linkcentral-insights-notice-flash');
    notice.addEventListener(
        'animationend',
        () => notice.classList.remove('linkcentral-insights-notice-flash'),
        { once: true }
    );
}
