<?php

namespace Core;

class Component
{
    protected $name;
    protected $data;

    public function __construct($name, $data = [])
    {
        $this->name = $name;
        $this->data = $data;
    }

    public function render()
    {
        $theme = 'default'; // This could be dynamic later
        $path = __DIR__ . "/../../themes/{$theme}/components/{$this->name}.php";

        if (file_exists($path)) {
            extract($this->data);
            include $path;
        } else {
            echo "<!-- Component {$this->name} not found -->";
        }
    }

    /**
     * Render component shortcodes in content
     * Format: [component:name attr="value"]
     */
    public static function renderShortcodes($content)
    {
        return preg_replace_callback('/\[component:([a-z0-9_-]+)(.*?)\]/is', function ($matches) {
            $name = $matches[1];
            $attrStr = $matches[2];

            // Parse attributes
            $attrs = [];
            preg_match_all('/([a-z0-9_-]+)=["\']([^"\']*?)["\']/i', $attrStr, $attrMatches);

            foreach ($attrMatches[1] as $i => $key) {
                $value = $attrMatches[2][$i];
                // Try to decode JSON/HTML entities
                $value = html_entity_decode($value);
                // Basic JSON check
                if ((strpos($value, '[') === 0 || strpos($value, '{') === 0) && ($json = json_decode($value, true))) {
                    $value = $json;
                }
                $attrs[$key] = $value;
            }

            ob_start();
            $comp = new self($name, $attrs);
            $comp->render();
            return ob_get_clean();
        }, $content);
    }

    /**
     * Render block shortcodes
     * Placeholder for future block logic
     */
    public static function renderBlockShortcodes($content)
    {
        // Future: Implement [block]...[/block] logic
        return $content;
    }
}
