<?php

namespace App\Helpers;

class PerformanceHelper
{
    /**
     * Generate optimized image tag with WebP fallback
     */
    public static function optimizedImage($src, $alt = '', $width = null, $height = null, $fetchPriority = 'auto', $lazy = true)
    {
        $webpSrc = str_replace(['.jpg', '.jpeg', '.png'], '.webp', $src);
        $webpExists = file_exists(public_path(str_replace(asset(''), '', $webpSrc)));
        
        $widthAttr = $width ? "width=\"{$width}\"" : '';
        $heightAttr = $height ? "height=\"{$height}\"" : '';
        $loading = $lazy ? 'loading="lazy"' : 'loading="eager"';
        $fetchPriorityAttr = $fetchPriority !== 'auto' ? "fetchpriority=\"{$fetchPriority}\"" : '';
        
        if ($webpExists) {
            return "<picture>
                <source srcset=\"{$webpSrc}\" type=\"image/webp\">
                <img src=\"{$src}\" alt=\"{$alt}\" {$widthAttr} {$heightAttr} {$loading} {$fetchPriorityAttr}>
            </picture>";
        }
        
        return "<img src=\"{$src}\" alt=\"{$alt}\" {$widthAttr} {$heightAttr} {$loading} {$fetchPriorityAttr}>";
    }

    /**
     * Get LCP element attributes
     */
    public static function lcpAttributes($fetchPriority = 'high')
    {
        return "fetchpriority=\"{$fetchPriority}\" loading=\"eager\"";
    }
}

