<?php
/**
 * Load SVG sprite and return inline SVG
 */
function lnj_load_sprite_svg($icon_id, $class = '', $width = null, $height = null) {
    $sprite_path = get_template_directory() . '/theme/svg/sprite.svg';

    if (!file_exists($sprite_path)) {
        return '';
    }

    $sprite_content = file_get_contents($sprite_path);

    // Extract the specific symbol from the sprite
    $pattern = '/<symbol[^>]*id="' . preg_quote($icon_id, '/') . '"[^>]*>(.*?)<\/symbol>/s';

    if (preg_match($pattern, $sprite_content, $matches)) {
        $svg_content = $matches[1];

        // Build the SVG element
        $attributes = array();

        if (!empty($class)) {
            $attributes['class'] = esc_attr($class);
        }

        if ($width) {
            $attributes['width'] = esc_attr($width);
        }

        if ($height) {
            $attributes['height'] = esc_attr($height);
        }

        $attributes['fill'] = 'currentColor';

        // Build attribute string
        $attr_string = '';
        foreach ($attributes as $name => $value) {
            $attr_string .= ' ' . $name . '="' . $value . '"';
        }

        return '<svg' . $attr_string . '>' . $svg_content . '</svg>';
    }

    return '';
}

/**
 * Load the entire sprite once and cache it
 */
function lnj_get_svg_sprite() {
    static $sprite_content = null;

    if ($sprite_content === null) {
        $sprite_path = get_template_directory() . '/theme/svg/sprite.svg';

        if (file_exists($sprite_path)) {
            $sprite_content = file_get_contents($sprite_path);
        } else {
            $sprite_content = '';
        }
    }

    return $sprite_content;
}

/**
 * Output the SVG sprite at the beginning of body
 */
function lnn_output_svg_sprite() {
    echo lnj_get_svg_sprite();
}
add_action('wp_body_open', 'lnn_output_svg_sprite');

/**
 * Legacy function for backward compatibility
 */
function lnj_load_inline_svg($filename, $class = '', $width = null, $height = null) {
    // Map old filenames to new icon IDs
    $icon_map = array(
        'plus.svg' => 'icon-plus',
        'arrow-right.svg' => 'icon-arrow-right',
        'arrow-left.svg' => 'icon-arrow-left',
        'arrow-up.svg' => 'icon-arrow-up',
        'arrow-down.svg' => 'icon-arrow-down',
        'circle-left.svg' => 'icon-circle-left',
        'circle-down.svg' => 'icon-circle-down',
        'burger-menu.svg' => 'icon-burger',
        'icon-instagram.svg' => 'icon-instagram',
        'icon-linkedin.svg' => 'icon-linkedin',
        'icon-mail.svg' => 'icon-mail',
        'scroll-top.svg' => 'icon-scroll-top',
        'scroll-up.svg' => 'icon-scroll-up',
        'logo-small.svg' => 'icon-logo-small',
    );

    // Remove .svg extension if present
    $icon_id = str_replace('.svg', '', $filename);

    // Use mapped ID if available
    if (isset($icon_map[$filename])) {
        $icon_id = $icon_map[$filename];
    }

    return lnj_load_sprite_svg($icon_id, $class, $width, $height);
}
?>
