<?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();
    }

    /**
     * Override callAction to skip parent's admin auth requirements.
     * This controller uses its own standalone Twig instance and doesn't need
     * the admin header/auth from the base Controller.
     */
    public function callAction($method, $parameters)
    {
        return $this->{$method}(...array_values($parameters));
    }

    /**
     * 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());
        }

        // Load shared Twig functions (including vite, vite_css)
        global $twig;
        $twig = $this->twig;
        include base_path('core/includes/functions.twig.php');
    }
}