const DEFAULT_WIDTHS = [240, 480, 720, 960, 1280];
const ALLOWED_REMOTE_HOSTS = [
    'i.ibb.co',
    'ibb.co',
    'image.daiman.shop',
    'firebasestorage.googleapis.com',
    'storage.googleapis.com',
];

const normalizeUrl = (value) => String(value || '').trim();

const isHttpUrl = (url) => /^https?:\/\//i.test(url);

export const canUseVariantProxy = (url) => {
    const u = normalizeUrl(url);
    if (!isHttpUrl(u)) return false;
    try {
        const host = String(new URL(u).hostname || '').toLowerCase();
        return ALLOWED_REMOTE_HOSTS.some((suffix) => host === suffix || host.endsWith(`.${suffix}`));
    } catch (_) {
        return false;
    }
};

export const buildImageVariantUrl = (url, width, quality = 78) => {
    const src = normalizeUrl(url);
    const w = Math.max(64, Math.min(2400, Number(width) || 480));
    const q = Math.max(50, Math.min(92, Number(quality) || 78));
    if (!canUseVariantProxy(src)) return src;
    return `api/image-variant.php?url=${encodeURIComponent(src)}&w=${w}&q=${q}`;
};

export const getResponsiveImageSpec = (url, opts = {}) => {
    const src = normalizeUrl(url);
    const widths = Array.isArray(opts.widths) && opts.widths.length
        ? opts.widths.map((x) => Number(x)).filter((x) => Number.isFinite(x) && x > 0)
        : DEFAULT_WIDTHS;
    const q = Number.isFinite(Number(opts.quality)) ? Number(opts.quality) : 78;
    const fallbackWidth = Number.isFinite(Number(opts.fallbackWidth)) ? Number(opts.fallbackWidth) : widths[Math.min(1, widths.length - 1)];
    const sizes = normalizeUrl(opts.sizes) || '(max-width: 768px) 50vw, 25vw';

    const uniqueWidths = [...new Set(widths)].sort((a, b) => a - b);
    if (!canUseVariantProxy(src) || uniqueWidths.length === 0) {
        return { src, srcset: '', sizes };
    }
    const srcset = uniqueWidths.map((w) => `${buildImageVariantUrl(src, w, q)} ${w}w`).join(', ');
    return {
        src: buildImageVariantUrl(src, fallbackWidth, q),
        srcset,
        sizes
    };
};

export const collectImageOrigins = (settings = {}) => {
    const urls = [];
    const add = (value) => {
        const u = normalizeUrl(value);
        if (isHttpUrl(u)) urls.push(u);
    };
    add(settings.logoUrl);
    add(settings.footerLogoUrl);
    add(settings.imageCdnOrigin);
    const layout = settings.layout || {};
    add(layout.imageCdnOrigin);
    if (Array.isArray(settings.bannerUrls)) settings.bannerUrls.slice(0, 4).forEach(add);
    if (Array.isArray(settings.smallBanners)) settings.smallBanners.slice(0, 3).forEach(add);
    if (Array.isArray(settings.bannerSlides)) settings.bannerSlides.slice(0, 4).forEach((x) => add(x && x.imageUrl));
    add(settings.promoBanner1Url);
    add(settings.promoBanner2Url);
    return [...new Set(urls.map((u) => {
        try { return new URL(u).origin; } catch (_) { return ''; }
    }).filter(Boolean))].slice(0, 3);
};

export const ensureImagePreconnects = (origins = []) => {
    origins.forEach((origin) => {
        const key = String(origin || '').trim();
        if (!/^https?:\/\//i.test(key)) return;
        const id = 'img-preconnect-' + key.replace(/^https?:\/\//, '').replace(/[^a-z0-9]+/gi, '-').slice(0, 120);
        if (!document.getElementById(id)) {
            const pc = document.createElement('link');
            pc.id = id;
            pc.rel = 'preconnect';
            pc.href = key;
            pc.crossOrigin = '';
            document.head.appendChild(pc);
        }
        const dnsId = id + '-dns';
        if (!document.getElementById(dnsId)) {
            const dns = document.createElement('link');
            dns.id = dnsId;
            dns.rel = 'dns-prefetch';
            dns.href = key;
            document.head.appendChild(dns);
        }
    });
};
