'use client';

import React, { useLayoutEffect, useRef } from 'react';
import {
    fitPrintLogoSize,
    PRINT_LOGO_MAX_HEIGHT,
    PRINT_LOGO_MAX_WIDTH,
} from './fitPrintLogoSize';
import styles from './PrintDocumentLogo.module.scss';

export type PrintDocumentLogoProps = {
    logoUrl?: string | null;
    /** Inicial exibida quando não há logo (1.ª letra do nome da tenant). */
    fallbackInitial?: string;
    /** Cor de fundo do fallback (hex da tenant). */
    primaryColor?: string;
    className?: string;
};

/**
 * Espaço reservado para logomarca em documentos de impressão / PDF.
 * Qualquer proporção (paisagem, retrato, quadrado) cabe sem distorção.
 * Dimensionamento explícito — html2canvas não respeita object-fit.
 */
export function PrintDocumentLogo({
    logoUrl,
    fallbackInitial = 'G',
    primaryColor,
    className,
}: PrintDocumentLogoProps) {
    const imgRef = useRef<HTMLImageElement>(null);
    const initial = (fallbackInitial || 'G').trim().charAt(0).toUpperCase() || 'G';

    useLayoutEffect(() => {
        const img = imgRef.current;
        if (!img || !logoUrl) return;

        const apply = () => fitPrintLogoSize(img, PRINT_LOGO_MAX_WIDTH, PRINT_LOGO_MAX_HEIGHT);

        if (img.complete && img.naturalWidth > 0) {
            apply();
            return;
        }

        img.addEventListener('load', apply);
        return () => img.removeEventListener('load', apply);
    }, [logoUrl]);

    if (logoUrl) {
        return (
            <div
                className={[styles.logoBox, className].filter(Boolean).join(' ')}
                data-print-logo-slot
            >
                {/* eslint-disable-next-line @next/next/no-img-element -- logo tenant remota */}
                <img
                    ref={imgRef}
                    src={logoUrl}
                    alt=""
                    className={styles.logo}
                    data-print-logo
                    onLoad={(e) => {
                        fitPrintLogoSize(e.currentTarget, PRINT_LOGO_MAX_WIDTH, PRINT_LOGO_MAX_HEIGHT);
                    }}
                />
            </div>
        );
    }

    return (
        <div
            className={[styles.brandFallback, className].filter(Boolean).join(' ')}
            style={primaryColor ? { background: primaryColor } : undefined}
            aria-hidden
        >
            {initial}
        </div>
    );
}
