class HeaderFooterUtils {

    static addHeadersAndFooters(doc, data, config = {}) {
        const pageWidth = config.pageWidth || 210;
        const pageHeight = config.pageHeight || 297;
        const margin = config.margin || 15;
        const headerHeight = config.headerHeight || 20;
        const footerHeight = config.footerHeight || 15;

        const totalPages = doc.getNumberOfPages();

        for (let pageNum = 1; pageNum <= totalPages; pageNum++) {
            doc.setPage(pageNum);

            if (pageNum > 1) {
                this.addHeader(doc, data, pageWidth, margin, headerHeight);
                this.addFooter(doc, data, pageNum, pageWidth, pageHeight, margin, footerHeight);
            }
        }
    }

    static addHeader(doc, data, pageWidth, margin, headerHeight) {
        const headerY = margin / 2;
        const maxLogoWidth = 18;
        const maxLogoHeight = 16;

        if (data.companyLogo && data.companyLogo.length > 0) {
            const logoData = data.companyLogo[0];
            if (logoData && logoData.preview) {
                try {

                    const dimensions = this.calculateLogoDimensions(
                        logoData.preview,
                        maxLogoWidth,
                        maxLogoHeight
                    );

                    doc.addImage(
                        logoData.preview,
                        'PNG',
                        margin,
                        headerY,
                        dimensions.width,
                        dimensions.height
                    );
                } catch (e) {
                    console.warn('Failed to add logo to header:', e);
                }
            }
        }

        const centerX = pageWidth / 2;
        const brandColorRgb = PDFUtils.hexToRgb(data.brandColor || '#003366');
        doc.setTextColor(...brandColorRgb);
        doc.setFontSize(9);
        doc.setFont(undefined, 'bold');
        doc.text(data.companyName || 'Company Name', centerX, headerY + 3, { align: 'center' });
        doc.setTextColor(0, 0, 0);

        doc.setFontSize(7);
        doc.setFont(undefined, 'normal');
        const address = this.formatAddress(data);
        if (address) {
            doc.text(address, centerX, headerY + 8, { align: 'center' });
        }

        doc.setFontSize(8);
        doc.setFont(undefined, 'bold');
        const jobTitleX = pageWidth - margin;
        const jobTitle = data.jobTitle || 'Job Title';

        const wrappedJobTitle = doc.splitTextToSize(jobTitle, 30);
        doc.text(wrappedJobTitle, jobTitleX, headerY + 3, { align: 'right' });
    }

    static addFooter(doc, data, pageNum, pageWidth, pageHeight, margin, footerHeight) {
        const footerY = pageHeight - (margin / 2);

        doc.setFontSize(8);
        doc.setFont(undefined, 'normal');
        const dateText = this.formatDateToLongFormat(data.date);
        doc.text(dateText, margin, footerY - 2);

        const displayPageNum = pageNum;
        doc.text(`Page ${displayPageNum}`, pageWidth - margin, footerY - 2, { align: 'right' });
    }

    static formatDateToLongFormat(date) {
        if (!date) {
            return new Date().toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' });
        }

        if (typeof date === 'string') {

            if (/^\d{4}-\d{2}-\d{2}$/.test(date)) {
                const [year, month, day] = date.split('-').map(Number);
                const dateObj = new Date(year, month - 1, day);
                return dateObj.toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' });
            }

            const dateObj = new Date(date);
            return dateObj.toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' });
        }

        if (date instanceof Date) {
            return date.toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' });
        }

        return new Date().toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' });
    }

    static calculateLogoDimensions(imageData, maxWidth, maxHeight) {

        const img = new Image();
        img.src = imageData;

        const aspectRatio = img.naturalWidth && img.naturalHeight
            ? img.naturalWidth / img.naturalHeight
            : 1;

        let width = maxWidth;
        let height = maxWidth / aspectRatio;

        if (height > maxHeight) {
            height = maxHeight;
            width = maxHeight * aspectRatio;
        }

        return { width, height };
    }

    static formatAddress(data) {
        const parts = [];
        if (data.companyStreet) parts.push(data.companyStreet);
        if (data.companyCity) parts.push(data.companyCity);
        if (data.companyState) parts.push(data.companyState);
        if (data.companyZip) parts.push(data.companyZip);
        return parts.join(', ');
    }
}

window.HeaderFooterUtils = HeaderFooterUtils;