<?php

namespace AleshaCMS\CMS\PageBuilder;

use AleshaCMS\CMS\Hook\HookManager;

class PageBuilderRenderer
{
    public function __construct(protected HookManager $hooks) {}

    public function render(array $sections): string
    {
        $html = '';

        foreach ($sections as $section) {
            $html .= $this->renderSection($section);
        }

        return $html;
    }

    protected function renderSection(array $section): string
    {
        $type = $section['type'] ?? 'unknown';
        $data = $section['data'] ?? [];
        $data['full_width'] = (bool)($section['full_width'] ?? false);

        $viewName = "components.builder.{$type}";

        if (view()->exists($viewName)) {
            return view($viewName, $data)->render();
        }

        $themeView = "theme-" . app(\AleshaCMS\CMS\Theme\ThemeManager::class)->getActive() . "::components.builder.{$type}";

        if (view()->exists($themeView)) {
            return view($themeView, $data)->render();
        }

        return '';
    }

    public function getAvailableSections(): array
    {
        $sections = [
            ['type' => 'hero', 'label' => 'Hero Banner', 'icon' => 'photo'],
            ['type' => 'text', 'label' => 'Text Block', 'icon' => 'document-text'],
            ['type' => 'image', 'label' => 'Image', 'icon' => 'photo'],
            ['type' => 'gallery', 'label' => 'Gallery', 'icon' => 'squares-2x2'],
            ['type' => 'columns', 'label' => 'Columns', 'icon' => 'view-columns'],
            ['type' => 'cta', 'label' => 'Call to Action', 'icon' => 'cursor-arrow-rays'],
            ['type' => 'testimonial', 'label' => 'Testimonial', 'icon' => 'chat-bubble-left'],
            ['type' => 'faq', 'label' => 'FAQ', 'icon' => 'question-mark-circle'],
        ];

        return $this->hooks->applyFilter('page_builder.sections', $sections);
    }
}
