<?php

/**
 * SEO Figure Element Template
 * 
 * Outputs semantic HTML5 <figure> element with:
 * - Modern <picture> element with AVIF/WebP support (for raster images)
 * - Simple <img> tag for SVG diagrams (no picture wrapper needed)
 * - Proper performance attributes (loading, decoding for raster only)
 * - Optional <figcaption> for accessibility
 * - Full YooTheme Pro integration
 */

// Container element (figure)
$el = $this->el('figure', [
    'class' => [
        'el-figure',
        'uk-margin-remove-first-child',
    ],
]);

// Get responsive breakpoint (default to 800px)
$breakpoint = $props['responsive_breakpoint'] ?: 800;

// Check if image is SVG
$is_svg = false;
if ($image_path = $props['image']) {
    $is_svg = strtolower(pathinfo($image_path, PATHINFO_EXTENSION)) === 'svg';
}

// Check for AVIF variants (skip for SVG files)
$has_avif = false;
$avif_sources = [];

if ($image_path && !$is_svg && $this->isImage($image_path)) {
    // Parse the image URL to get the file path
    $parsed_url = parse_url($image_path);
    $file_path = $_SERVER['DOCUMENT_ROOT'] . ($parsed_url['path'] ?? '');

    // Check if AVIF version exists (same name, different extension)
    $path_info = pathinfo($file_path);
    $avif_path = $path_info['dirname'] . '/' . $path_info['filename'] . '.avif';

    if (file_exists($avif_path)) {
        $has_avif = true;
        // Construct AVIF URL
        $avif_url = $path_info['dirname'] . '/' . $path_info['filename'] . '.avif';
        $avif_url = str_replace($_SERVER['DOCUMENT_ROOT'], '', $avif_url);
    }
}

// Image element using YooTheme's helper
$image = $this->el('image', [
    'class' => [
        'el-image',
        'uk-border-{image_border}',
        'uk-box-shadow-{image_box_shadow}',
    ],
    'src' => $props['image'],
    'alt' => $props['image_alt'],
    'loading' => $props['image_loading'] ? 'eager' : 'lazy',
    'fetchpriority' => $props['image_loading'] ? 'high' : 'auto',
    'width' => $props['image_width'],
    'height' => $props['image_height'],
    'focal_point' => $props['image_focal_point'],
    'thumbnail' => true,
]);

// Link wrapper if link is provided
$link = $this->el('a', [
    'class' => ['el-link'],
    'href' => ['{link}'],
    'aria-label' => ['{link_aria_label}'],
    'target' => ['_blank {@link_target: blank}'],
    'uk-scroll' => str_contains((string) $props['link'], '#'),
]);

// Caption element
$caption = $this->el('figcaption', [
    'class' => [
        'el-caption',
        'uk-margin-small-top {@caption_position: below}',
        'uk-margin-small-bottom {@caption_position: above}',
    ],
]);

?>

<?= $el($props, $attrs) ?>

<?php if ($props['caption'] && $props['caption_position'] === 'above'): ?>
    <?= $caption($props, $props['caption']) ?>
<?php endif ?>

<?php
// Get the image HTML from YooTheme's image helper
$image_html = $image($props);

// SVG files: Skip picture element wrapper (SVGs are resolution-independent)
// Raster images: Apply AVIF/WebP picture element enhancements
if (!$is_svg) {
    // If we have AVIF support or YooTheme has created picture element, we need to enhance it
    if ($has_avif && isset($avif_url)) {
        // Parse YooTheme's image output to see if it already created a picture element
        if (strpos($image_html, '<picture>') !== false) {
            // YooTheme already created picture, inject AVIF sources at the beginning
            $avif_source_large = sprintf(
                '<source srcset="%s" type="image/avif" media="(min-width: %dpx)">',
                esc_url($avif_url),
                $breakpoint
            );
            $avif_source_small = sprintf(
                '<source srcset="%s" type="image/avif">',
                esc_url($avif_url)
            );

            // Inject AVIF sources right after <picture> tag
            $image_html = str_replace(
                '<picture>',
                '<picture>' . "\n    " . $avif_source_large . "\n    " . $avif_source_small,
                $image_html
            );
        } else {
            // YooTheme didn't create picture, we need to wrap it
            $avif_source_large = sprintf(
                '<source srcset="%s" type="image/avif" media="(min-width: %dpx)">',
                esc_url($avif_url),
                $breakpoint
            );
            $avif_source_small = sprintf(
                '<source srcset="%s" type="image/avif">',
                esc_url($avif_url)
            );

            $image_html = '<picture>' . "\n    "
                . $avif_source_large . "\n    "
                . $avif_source_small . "\n    "
                . $image_html . "\n"
                . '</picture>';
        }
    }

    // Add decoding="async" attribute for raster images only (not applicable to SVG)
    $image_html = preg_replace(
        '/(<img[^>]+)(>)/',
        '$1 decoding="async"$2',
        $image_html
    );
}

// Output the image (with or without link wrapper)
if ($props['link']) {
    echo $link($props, $image_html);
} else {
    echo $image_html;
}
?>

<?php if ($props['caption'] && $props['caption_position'] === 'below'): ?>
    <?= $caption($props, $props['caption']) ?>
<?php endif ?>

<?= $el->end() ?>