const { __ } = wp.i18n;

import { showDrilldownUpsell } from './drilldown-upsell';
import { isPremiumUser } from '../utils/premium';
import { escapeHtml, escapeAttr } from '../utils/html';

/**
 * Render a link name that filters insights on click, with an external edit icon.
 *
 * @param {object} options
 * @param {number} options.linkId
 * @param {string} options.title
 * @param {string} options.editLink
 * @param {boolean} [options.isDeleted]
 * @returns {string}
 */
export function renderInsightLinkTitle({ linkId, title, editLink, isDeleted = false }) {
    if (isDeleted) {
        return escapeHtml(__('Deleted Link', 'linkcentral'));
    }

    return `<span class="linkcentral-insights-link-title">
        <button
            type="button"
            class="linkcentral-insights-link-filter"
            data-link-id="${escapeAttr(String(linkId))}"
            data-link-title="${escapeAttr(title)}"
        >${escapeHtml(title)}</button>
        <a
            href="${escapeAttr(editLink)}"
            class="linkcentral-insights-link-edit"
            target="_blank"
            rel="noopener noreferrer"
            aria-label="${escapeAttr(__('Edit link', 'linkcentral'))}"
        ><span class="dashicons dashicons-external" aria-hidden="true"></span></a>
    </span>`;
}

/**
 * Wire delegated click handling for link title filter buttons.
 *
 * @param {object} store
 * @param {import('./link-selector').default} linkSelector
 */
export function initLinkTitleFilters(store, linkSelector) {
    const insightsPage = document.querySelector('.linkcentral-insights');
    if (!insightsPage) {
        return;
    }

    insightsPage.addEventListener('click', (event) => {
        const filterButton = event.target.closest('.linkcentral-insights-link-filter');
        if (!filterButton) {
            return;
        }

        event.preventDefault();

        const linkId = parseInt(filterButton.dataset.linkId, 10);
        const linkTitle = filterButton.dataset.linkTitle || '';

        if (!linkId) {
            return;
        }

        if (!isPremiumUser()) {
            showDrilldownUpsell();
            return;
        }

        if (typeof store.setLinkSelection !== 'function') {
            return;
        }

        linkSelector.selectLink(linkId, linkTitle);
    });
}
