import axios from "axios";
import { configStore, selectedChatStore } from "../store/store";
import { getRemainingDays, isExpired } from "./dayjs";
export const getAddressAsText = (address) => {
    if (!address)
        return '';
    const addressStr = [];
    if (address.address)
        addressStr.push(address.address);
    if (address.province)
        addressStr.push(address.province);
    if (address.district)
        addressStr.push(address.district);
    if (address.sub_district)
        addressStr.push(address.sub_district);
    if (address.zip_code)
        addressStr.push(address.zip_code);
    return addressStr.join(', ');
};
export const isUrl = (value) => {
    try {
        new URL(value);
        return true;
    }
    catch (e) {
        return false;
    }
};
export const getFileNameFromUrl = (url) => {
    try {
        const pathname = new URL(url).pathname;
        return decodeURIComponent(pathname.split('/').pop() || 'Unknown File');
    }
    catch (e) {
        return 'Unknown File';
    }
};
export const getFileTypeAndMimeFromUrl = (url) => {
    try {
        const pathname = new URL(url).pathname;
        const pathnameSplitted = pathname.split('.').pop();
        const extension = pathnameSplitted ? pathnameSplitted.toLowerCase() : '';
        const mimeMap = {
            // Excel
            'xlsx': { type: 'excel', icon: 'excel', mime: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' },
            'xls': { type: 'excel', icon: 'excel', mime: 'application/vnd.ms-excel' },
            'xlsm': { type: 'excel', icon: 'excel', mime: 'application/vnd.ms-excel.sheet.macroEnabled.12' },
            // PDF
            'pdf': { type: 'pdf', icon: 'pdf', mime: 'application/pdf' },
            // Word
            'docx': { type: 'word', icon: 'word', mime: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' },
            'doc': { type: 'word', icon: 'word', mime: 'application/msword' },
            // PowerPoint
            'pptx': { type: 'powerpoint', icon: 'powerpoint', mime: 'application/vnd.openxmlformats-officedocument.presentationml.presentation' },
            'ppt': { type: 'powerpoint', icon: 'powerpoint', mime: 'application/vnd.ms-powerpoint' },
            'pptm': { type: 'powerpoint', icon: 'powerpoint', mime: 'application/vnd.ms-powerpoint.presentation.macroEnabled.12' },
            'ppsx': { type: 'powerpoint', icon: 'powerpoint', mime: 'application/vnd.openxmlformats-officedocument.presentationml.slideshow' },
            'pps': { type: 'powerpoint', icon: 'powerpoint', mime: 'application/vnd.ms-powerpoint' },
            // Others
            // 'zip': { type: 'archive', mime: 'application/zip' },
            'csv': { type: 'csv', icon: 'excel', mime: 'text/csv' },
        };
        return { ...(mimeMap[extension || ''] || { type: 'unknown', mime: 'application/octet-stream' }), extension };
    }
    catch (e) {
        return { type: 'unknown', mime: 'application/octet-stream' };
    }
};
const mimeToTypeMap = {
    // Excel
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': { type: 'excel', icon: 'excel', extension: 'xlsx' },
    'application/vnd.ms-excel': { type: 'excel', icon: 'excel', extension: 'xls' },
    'application/vnd.ms-excel.sheet.macroenabled.12': { type: 'excel', icon: 'excel', extension: 'xlsm' },
    // PDF
    'application/pdf': { type: 'pdf', icon: 'pdf', extension: 'pdf' },
    // Word
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document': { type: 'word', icon: 'word', extension: 'docx' },
    'application/msword': { type: 'word', icon: 'word', extension: 'doc' },
    // PowerPoint
    'application/vnd.openxmlformats-officedocument.presentationml.presentation': { type: 'powerpoint', icon: 'powerpoint', extension: 'pptx' },
    'application/vnd.ms-powerpoint': { type: 'powerpoint', icon: 'powerpoint', extension: 'ppt' },
    'application/vnd.ms-powerpoint.presentation.macroenabled.12': { type: 'powerpoint', icon: 'powerpoint', extension: 'pptm' },
    'application/vnd.openxmlformats-officedocument.presentationml.slideshow': { type: 'powerpoint', icon: 'powerpoint', extension: 'ppsx' },
    // CSV
    'text/csv': { type: 'csv', icon: 'excel', extension: 'csv' },
};
// Cache for blob URL file types to avoid repeated fetches
const blobUrlCache = new Map();
export const getFileTypeFromMime = (mimeType) => {
    const mime = mimeType.toLowerCase().trim();
    // Check exact match first
    if (mimeToTypeMap[mime]) {
        return mimeToTypeMap[mime];
    }
    // Universal handling for image/*, video/*, and audio/* MIME types
    if (mime.startsWith('image/')) {
        const extension = mime.split('/')[1] || 'unknown';
        return { type: 'image', icon: 'image', extension };
    }
    if (mime.startsWith('video/')) {
        const extension = mime.split('/')[1] || 'unknown';
        return { type: 'video', icon: 'video', extension };
    }
    if (mime.startsWith('audio/')) {
        const extension = mime.split('/')[1] || 'unknown';
        return { type: 'audio', icon: 'audio', extension };
    }
    return { type: 'unknown', icon: 'unknown' };
};
export const getFileTypeFromBlobUrl = async (blobUrl) => {
    // Check cache first for performance
    if (blobUrlCache.has(blobUrl)) {
        return blobUrlCache.get(blobUrl);
    }
    try {
        const response = await fetch(blobUrl);
        const blob = await response.blob();
        const result = getFileTypeFromMime(blob.type);
        // Cache the result
        blobUrlCache.set(blobUrl, result);
        return result;
    }
    catch (e) {
        const fallback = { type: 'unknown', icon: 'unknown' };
        blobUrlCache.set(blobUrl, fallback);
        return fallback;
    }
};
export function isValidTelNumber(value) {
    const cleaned = value.replace(/^tel:/, '').trim();
    // Allow +, digits, spaces, dashes, parentheses
    // Must have 7-15 digits total
    const formatRegex = /^\+?[\d\s\-()]+$/;
    if (!formatRegex.test(cleaned))
        return false;
    const digitsOnly = cleaned.replace(/\D/g, '');
    return digitsOnly.length >= 7 && digitsOnly.length <= 15;
}
export const downloadFileMessage = async (file) => {
    const fileName = file.name || 'Unknown file';
    try {
        const response = await axios.get(file.url, {
            responseType: 'blob',
            params: {
                _t: new Date().getTime()
            }
        });
        const blob = response.data;
        const blobUrl = URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = blobUrl;
        link.download = fileName;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        URL.revokeObjectURL(blobUrl);
    }
    catch (error) {
        try {
            const fallbackUrl = new URL(file.url);
            fallbackUrl.searchParams.set('response-content-disposition', `attachment; filename="${fileName}"`);
            openWindow(fallbackUrl.toString());
        }
        catch (e) {
            openWindow(file.url);
        }
    }
};
export const getConnectionId = (connection) => {
    const _connection = connection || selectedChatStore.get('selectedChat')?.connection;
    return _connection?.zwiz_connection?.id || _connection?.id;
};
export const getConnectionItem = (chatItem) => {
    const selectedChat = chatItem || selectedChatStore.get('selectedChat');
    const connectionId = getConnectionId(selectedChat?.connection);
    const connectionItem = configStore.get('connectionList').find(connection => connection.id === connectionId);
    return connectionItem;
};
export const getZwizPackageData = (chatItem) => {
    const connectionItem = getConnectionItem(chatItem);
    const zwizPackageData = connectionItem?.type === 'zwiz' && connectionItem?.platform === 'sme'
        ? connectionItem?.zwiz_package_data
        : null;
    return zwizPackageData;
};
export const getZwizPackageType = (zwizCheckBotPage) => {
    let packageName = 'free';
    let remainingDays = 0;
    let isLocked = true;
    if (zwizCheckBotPage.business_expireat !== null && !isExpired(zwizCheckBotPage.business_expireat)) {
        packageName = 'business';
        remainingDays = getRemainingDays(zwizCheckBotPage.business_expireat);
        isLocked = false;
    }
    else if (zwizCheckBotPage.advanced_expireat !== null && !isExpired(zwizCheckBotPage.advanced_expireat)) {
        packageName = 'advanced';
        remainingDays = getRemainingDays(zwizCheckBotPage.advanced_expireat);
        isLocked = false;
    }
    else if (zwizCheckBotPage.expireat !== null && !isExpired(zwizCheckBotPage.expireat)) {
        packageName = 'premium';
        remainingDays = getRemainingDays(zwizCheckBotPage.expireat);
    }
    return {
        package_data: {
            package_name: packageName,
            remaining_days: remainingDays,
            ...(zwizCheckBotPage.connect_zrm_business_profile_id !== null && zwizCheckBotPage.connect_zrm_shop_profile_setting_id !== null ? {
                zrmz: {
                    business_id: zwizCheckBotPage.connect_zrm_business_profile_id,
                    shop_id: zwizCheckBotPage.connect_zrm_shop_profile_setting_id
                }
            } : undefined),
            ...(zwizCheckBotPage.connect_zerva_business_profile_id !== null && zwizCheckBotPage.connect_zerva_shop_profile_setting_id !== null ? {
                zerva: {
                    business_id: zwizCheckBotPage.connect_zerva_business_profile_id,
                    shop_id: zwizCheckBotPage.connect_zerva_shop_profile_setting_id
                }
            } : undefined)
        },
        is_locked: isLocked
    };
};
export const convertBytesToGB = (bytes, decimals = 2) => {
    if (bytes === 0)
        return 0;
    return Number((bytes / (1024 ** 3)).toFixed(decimals));
};
export const openWindow = (url, windowName = '_blank') => {
    // Use an anchor tag to open the URL. This approach:
    // - Works reliably inside cross-origin iframes (no SecurityError)
    // - Opens exactly once (window.open + noopener returns null, causing double-open)
    // - Properly sets noopener/noreferrer for security
    const anchor = document.createElement('a');
    anchor.href = url;
    anchor.target = windowName;
    anchor.rel = 'noopener noreferrer';
    anchor.click();
};
export const getSenderName = (sender) => {
    return sender?.display_name || sender?.nickname || sender?.name || sender?.id || '';
};
