// --- Facebook Page feed: template, public product URL, Graph POST ---

const GRAPH_VERSION = 'v19.0';

export function stripHtml(html) {
    if (html == null || html === '') return '';
    if (typeof document === 'undefined') return String(html).replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim();
    const d = document.createElement('div');
    d.innerHTML = html;
    return (d.textContent || d.innerText || '').replace(/\s+/g, ' ').trim();
}

export function formatPriceForPost(amount) {
    const n = Number(amount);
    if (Number.isNaN(n)) return String(amount ?? '');
    try {
        return new Intl.NumberFormat('bn-BD', { style: 'currency', currency: 'BDT', minimumFractionDigits: 0, maximumFractionDigits: 0 }).format(n);
    } catch {
        return `${n} ৳`;
    }
}

/**
 * @param {string} template
 * @param {{ name: string, price: string, link: string, description: string }} vars
 */
export function applyPostTemplate(template, vars) {
    let t = template == null ? '' : String(template);
    t = t.replace(/\\n/g, '\n');
    const map = {
        '{name}': vars.name ?? '',
        '{price}': vars.price ?? '',
        '{link}': vars.link ?? '',
        '{description}': vars.description ?? ''
    };
    let out = t;
    Object.entries(map).forEach(([k, v]) => {
        out = out.split(k).join(v);
    });
    return out;
}

/**
 * Match customer-facing URLs (see shop-core getLandingPageUrlForProduct + script-classic hash).
 */
export function buildProductPublicUrl({ basePath, subdomain, productId, productData }) {
    const p = productData || {};
    const base = basePath.endsWith('/') ? basePath : `${basePath}/`;
    if (p.clickTarget === 'landing_page' && p.landingPageSlug) {
        const raw = p.landingPageCustomDomain;
        const d =
            raw != null && String(raw).trim()
                ? String(raw)
                      .trim()
                      .replace(/^https?:\/\//i, '')
                      .replace(/\/+$/, '')
                : '';
        if (d) return `https://${d}/`;
        const sub = subdomain != null && String(subdomain).trim() ? String(subdomain).trim() : '';
        const q = sub ? `?site=${encodeURIComponent(sub)}` : '';
        return `${base}view.html${q}#${p.landingPageSlug}`;
    }
    return `${base}shop.html?site=${encodeURIComponent(subdomain)}&p=${encodeURIComponent(productId)}#/product/${encodeURIComponent(productId)}`;
}

function normalizeGraphError(json) {
    if (!json?.error) return new Error('Facebook API error');
    const e = json.error;
    return new Error(e.error_user_msg || e.message || String(e.code || 'Request failed'));
}

/**
 * @param {{ pageId: string, accessToken: string, message: string, link: string }} opts
 */
export async function postToPageFeed({ pageId, accessToken, message, link }) {
    const id = String(pageId || '').trim();
    const token = String(accessToken || '').trim();
    if (!id || !token) throw new Error('Page ID and Page Access Token are required.');
    const url = `https://graph.facebook.com/${GRAPH_VERSION}/${id}/feed`;
    const body = new URLSearchParams();
    body.set('message', message);
    if (link) body.set('link', link);
    body.set('access_token', token);
    const res = await fetch(url, {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: body.toString()
    });
    const json = await res.json();
    if (json.error) throw normalizeGraphError(json);
    return json;
}
