<?php

namespace App\Http\Controllers;

use App\Services\ComponentScannerService;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Twig\Environment;
use Twig\Loader\FilesystemLoader;
use Twig\TwigFunction;

class ComponentRegistryController extends Controller
{
    private ComponentScannerService $scannerService;
    private Environment $twig;

    public function __construct(ComponentScannerService $scannerService)
    {
        $this->scannerService = $scannerService;
        $this->initializeTwigEnvironment();
    }

    /**
     * Display the component registry main page
     */
    public function index(Request $request): Response
    {
        try {
            $template = $this->twig->load('component_registry.twig');
            $html = $template->render([
                // Pass any variables needed by the template
            ]);

            return response($html, 200, [
                'Content-Type' => 'text/html; charset=UTF-8',
            ]);

        } catch (\Exception $e) {
            \Log::error('Component Registry page error: ' . $e->getMessage());

            return response('<html><head><title>Component Registry Error</title></head><body><h1>Component Registry Error</h1><p>Unable to load component registry page.</p><p>Error: ' . htmlspecialchars($e->getMessage()) . '</p><p><a href="/component">← Try Again</a></p></body></html>', 500, [
                'Content-Type' => 'text/html; charset=UTF-8',
            ]);
        }
    }

    /**
     * Initialize Twig environment for template rendering
     */
    private function initializeTwigEnvironment(): void
    {
        $templatesPath = base_path('sites/default/templates');

        if (!is_dir($templatesPath)) {
            throw new \RuntimeException("Templates directory not found: $templatesPath");
        }

        $loader = new FilesystemLoader($templatesPath);
        $this->twig = new Environment($loader, [
            'cache' => false,
            'debug' => config('app.debug', false),
        ]);

        // Add debug extension if needed
        if (config('app.debug', false)) {
            $this->twig->addExtension(new \Twig\Extension\DebugExtension());
        }

        // Add Vite functions for asset loading (same as in core/includes/header.inc.php)
        $this->twig->addFunction(new \Twig\TwigFunction('vite', function($asset_filename) {
            if (config('site.vite_dev_server') === true) {
                $dev_server_url = config('site.vite_dev_server_url') ?: 'http://localhost:5173';
                return "{$dev_server_url}/public/build/sites/default/" . $asset_filename;
            }

            // Production mode - use the manifest file
            $manifest_path = base_path('public/build/manifest.json');
            if (!file_exists($manifest_path)) {
                throw new \Exception("Asset manifest not found: {$manifest_path}");
            }
            $manifest = json_decode(file_get_contents($manifest_path), true);
            $key = 'sites/default/' . $asset_filename;
            if (!isset($manifest[$key])) {
                throw new \Exception("Asset not found in Vite manifest: {$key}");
            }
            return '/public/build/' . $manifest[$key]['file'];
        }));

        $this->twig->addFunction(new \Twig\TwigFunction('vite_css', function($asset_filename) {
            // In dev, Vue HMR injects CSS automatically; no link tags needed.
            if (getenv('VITE_DEV_SERVER') === 'true') {
                return [];
            }

            $manifest_path = base_path('public/build/manifest.json');
            if (!file_exists($manifest_path)) {
                throw new \Exception("Asset manifest not found: {$manifest_path}");
            }
            $manifest = json_decode(file_get_contents($manifest_path), true);

            $key = 'sites/default/' . $asset_filename;
            if (!isset($manifest[$key])) {
                throw new \Exception("Asset not found in Vite manifest: {$key}");
            }

            $css_files = [];
            if (isset($manifest[$key]['css'])) {
                foreach ($manifest[$key]['css'] as $css_file) {
                    $css_files[] = '/public/build/' . $css_file;
                }
            }
            return $css_files;
        }));

        // Add other Twig functions that might be needed
        $this->addCommonTwigFunctions();
    }

    /**
     * Add common Twig functions that might be used in templates
     */
    private function addCommonTwigFunctions(): void
    {
        // Add hooks_do_action function (used in the template)
        $this->twig->addFunction(new \Twig\TwigFunction('hooks_do_action', function($action) {
            // Return empty string for now - this is just a placeholder for the component registry
            return '';
        }));

        // Add settings variable simulation
        $this->twig->addGlobal('settings', [
            'STATIC_URL' => '',
            'THEME_URL' => '/sites/default/themes/default',
        ]);
    }
}