<?php

if (! defined('ABSPATH')) {
    exit;
} class PufferGo_Component_Loader
{
    public const TRANSIENT_MANIFEST = 'puffergo_patterns_manifest';

    public const TRANSIENT_TTL = DAY_IN_SECONDS;

    public const LOCAL_PATTERNS_DIR = '/templates/patterns';

    public static function get_components()
    {
        if (self::is_local_mode()) {
            return self::scan_local_manifest();
        } $cached = get_transient(self::TRANSIENT_MANIFEST);

        if (false !== $cached && is_array($cached)) {
            return $cached;
        } $patterns = self::fetch_manifest();

        if (! empty($patterns)) {
            set_transient(self::TRANSIENT_MANIFEST, $patterns, self::TRANSIENT_TTL);
        }

return $patterns;
    }

    public static function get_compiled($slug)
    {
        $slug = sanitize_text_field($slug);

        if (empty($slug) || substr_count($slug, '/') !== 1) {
            return new WP_Error('invalid_slug', __('Invalid pattern slug', 'puffergo'));
        }

if (self::is_local_mode()) {
            return self::read_local_compiled($slug);
        } $url = trailingslashit(self::get_base_url()) . 'api/patterns/' . $slug;
        $response = wp_remote_get($url, array('headers' => self::auth_headers(), 'timeout' => 15));

        if (is_wp_error($response)) {
            return $response;
        } $code = wp_remote_retrieve_response_code($response);

        if (200 !== (int) $code) {
            return new WP_Error('api_error', sprintf(__('siteForge API returned %1$s', 'puffergo'), $code));
        } $body = json_decode(wp_remote_retrieve_body($response), true);

        if (! is_array($body)) {
            return new WP_Error('parse_error', __('Failed to parse compiled pattern', 'puffergo'));
        }

return $body;
    }

    public static function invalidate_cache()
    {
        delete_transient(self::TRANSIENT_MANIFEST);
    }

    private static function is_local_mode()
    {
        return function_exists('wp_get_environment_type') && 'local' === wp_get_environment_type();
    }

    private static function scan_local_manifest()
    {
        $base = PUFFERGO_PLUGIN_DIR . self::LOCAL_PATTERNS_DIR;

        if (! is_dir($base)) {
            return array();
        } $patterns = array();

        foreach (scandir($base) as $category) {
            if ('.' === $category || '..' === $category || ! is_dir("$base/$category")) {
                continue;
            }

foreach (scandir("$base/$category") as $name) {
                if ('.' === $name || '..' === $name || ! is_dir("$base/$category/$name")) {
                    continue;
                } $meta_path = "$base/$category/$name/meta.json";

                if (! is_readable($meta_path)) {
                    continue;
                } $meta = json_decode(file_get_contents($meta_path), true);

                if (! is_array($meta)) {
                    continue;
                } $slug = "$category/$name";
                $preview_url = plugins_url(self::LOCAL_PATTERNS_DIR . "/$slug/preview.webp", PUFFERGO_PLUGIN_FILE);
                $preview_ver = isset($meta['previewVersion']) ? (string) $meta['previewVersion'] : '';

                if ('' === $preview_ver) {
                    $preview_path = "$base/$slug/preview.webp";
                    $preview_ver = is_readable($preview_path) ? (string) filemtime($preview_path) : '';
                }

if ('' !== $preview_ver) {
                    $preview_url .= '?v=' . rawurlencode($preview_ver);
                } $patterns[] = array('id' => $meta['id'] ?? $slug, 'slug' => $slug, 'title' => $meta['name'] ?? $name, 'description' => $meta['description'] ?? '', 'blockType' => $meta['blockType'] ?? '', 'preview' => $preview_url, 'version' => $meta['version'] ?? '1.0', 'source' => $meta['source'] ?? 'official', 'ai' => $meta['ai'] ?? array('eligible' => false), 'visualComposition' => $meta['visualComposition'] ?? null, 'localeSummary' => $meta['localeSummary'] ?? null, );
            }
        }

return $patterns;
    }

    private static function read_local_compiled($slug)
    {
        $path = PUFFERGO_PLUGIN_DIR . self::LOCAL_PATTERNS_DIR . '/' . $slug . '/compiled.json';

        if (! is_readable($path)) {
            return new WP_Error('not_found', sprintf(__('Local compiled.json not found: %s', 'puffergo'), $slug));
        } $category = explode('/', $slug)[0];
        $asset_base = plugins_url(self::LOCAL_PATTERNS_DIR . '/' . $category, PUFFERGO_PLUGIN_FILE);
        $raw = str_replace('{{PUFFERGO_CATEGORY_URL}}', $asset_base, file_get_contents($path));
        $data = json_decode($raw, true);

        if (! is_array($data)) {
            return new WP_Error('parse_error', __('Failed to parse compiled pattern', 'puffergo'));
        }

return $data;
    }

    private static function fetch_manifest()
    {
        $url = trailingslashit(self::get_base_url()) . 'api/patterns/manifest';
        $response = wp_remote_get($url, array('headers' => self::auth_headers(), 'timeout' => 15));

        if (is_wp_error($response) || 200 !== (int) wp_remote_retrieve_response_code($response)) {
            return array();
        } $body = json_decode(wp_remote_retrieve_body($response), true);

        if (! isset($body['patterns']) || ! is_array($body['patterns'])) {
            return array();
        } $patterns = array();

        foreach ($body['patterns'] as $item) {
            if (empty($item['slug'])) {
                continue;
            } $patterns[] = array('id' => $item['templateId'] ?? $item['slug'], 'slug' => $item['slug'], 'title' => self::translate_string($item['title'] ?? ''), 'description' => self::translate_string($item['description'] ?? ''), 'blockType' => $item['blockType'] ?? '', 'preview' => $item['preview'] ?? '', 'version' => $item['version'] ?? '1.0', 'source' => $item['source'] ?? 'official', 'ai' => $item['ai'] ?? array('eligible' => false), 'visualComposition' => $item['visualComposition'] ?? null, 'localeSummary' => $item['localeSummary'] ?? null, );
        }

return $patterns;
    }

    private static function get_base_url()
    {
        $url = defined('PUFFERGO_AI_PAGE_BUILDER_BASE_URL') ? PUFFERGO_AI_PAGE_BUILDER_BASE_URL : 'https://api.puffergo.com';

        return rtrim($url, '/');
    }

    private static function auth_headers()
    {
        $headers = array('Content-Type' => 'application/json');
        $api_key = get_option('puffergo_api_key', '');

        if (! empty($api_key)) {
            $headers['Authorization'] = 'Bearer ' . $api_key;
        }

return $headers;
    }

    private static function translate_string($text)
    {
        if (empty($text)) {
            return $text;
        }

return __($text, 'puffergo');
    }
}
