<?php
/**
 * LayoutRenderer
 * Renders row-based page layouts
 */
namespace Core;

class LayoutRenderer
{

    /**
     * Layout presets
     */
    const PRESETS = [
        'full' => [
            'label' => 'Full Width',
            'columns' => [12]
        ],
        'content-sidebar' => [
            'label' => 'Content + Sidebar',
            'columns' => [8, 4]
        ],
        'sidebar-content' => [
            'label' => 'Sidebar + Content',
            'columns' => [4, 8]
        ],
        'two-equal' => [
            'label' => 'Two Equal',
            'columns' => [6, 6]
        ],
        'three-equal' => [
            'label' => 'Three Equal',
            'columns' => [4, 4, 4]
        ],
        'four-equal' => [
            'label' => 'Four Equal',
            'columns' => [3, 3, 3, 3]
        ],
        'narrow' => [
            'label' => 'Narrow Center',
            'columns' => [8],
            'centered' => true
        ]
    ];

    /**
     * Render a layout from JSON
     * 
     * @param string|array $layout JSON string or array
     * @return string HTML output
     */
    public static function render($layout)
    {
        if (is_string($layout)) {
            $layout = json_decode($layout, true);
        }

        if (!$layout || !isset($layout['rows'])) {
            return '';
        }

        $html = '';

        foreach ($layout['rows'] as $row) {
            $html .= self::renderRow($row);
        }

        return $html;
    }

    /**
     * Render a single row
     */
    public static function renderRow($row)
    {
        $preset = self::PRESETS[$row['layout'] ?? 'full'] ?? self::PRESETS['full'];
        $columns = $row['columns'] ?? [];

        // Row classes
        $rowClasses = ['layout-row'];
        $sectionClasses = ['section'];

        // Custom CSS Class
        if (!empty($row['cssClass'])) {
            $sectionClasses[] = htmlspecialchars($row['cssClass']);
        }

        // Background
        if (!empty($row['background'])) {
            if (in_array($row['background'], ['primary', 'info', 'success', 'warning', 'danger', 'dark', 'light', 'white'])) {
                $sectionClasses[] = 'has-background-' . $row['background'];
            }
        }

        // Padding
        if (!empty($row['padding'])) {
            if ($row['padding'] === 'none') {
                $sectionClasses[] = 'py-0';
            } elseif ($row['padding'] === 'small') {
                $sectionClasses[] = 'py-3';
            } elseif ($row['padding'] === 'large') {
                $sectionClasses[] = 'py-6';
            }
        }

        $html = '<section class="' . implode(' ', $sectionClasses) . '" data-row-id="' . ($row['id'] ?? '') . '">';

        // Container
        $containerClass = 'container';
        $isFullWidth = !empty($row['full_width']) || !empty($row['fullWidth']);

        if ($isFullWidth) {
            $containerClass = 'container is-fluid';
        }

        $html .= '<div class="' . $containerClass . '">';
        $html .= '<div class="columns is-multiline">';

        // Render columns
        foreach ($columns as $i => $column) {
            $colWidth = $preset['columns'][$i] ?? 12;
            $colClasses = ['column', 'is-' . $colWidth];

            // Centered preset
            if (!empty($preset['centered']) && count($columns) === 1) {
                $colClasses[] = 'is-offset-2';
            }

            $html .= '<div class="' . implode(' ', $colClasses) . '">';

            // Render components in column
            foreach ($column['components'] ?? [] as $component) {
                $html .= self::renderComponent($component);
            }

            $html .= '</div>';
        }

        $html .= '</div></div></section>';

        return $html;
    }

    /**
     * Render a component (shortcode or raw HTML)
     */
    public static function renderComponent($component)
    {
        if (is_string($component)) {
            // It's a shortcode or HTML
            return $component;
        }

        if (is_array($component) && isset($component['type'])) {
            // Build shortcode
            $shortcode = '[component:' . $component['type'];
            foreach ($component['attributes'] ?? [] as $key => $value) {
                if (is_array($value)) {
                    $value = json_encode($value);
                }
                $shortcode .= ' ' . $key . '="' . htmlspecialchars($value) . '"';
            }
            $shortcode .= ']';
            return $shortcode;
        }

        return '';
    }

    /**
     * Parse content with layout markers
     */
    public static function parseContentWithLayout($content)
    {
        // Check if content has layout JSON at the beginning
        if (strpos($content, '<!--LAYOUT:') === 0) {
            $endPos = strpos($content, '-->');
            if ($endPos !== false) {
                $layoutJson = substr($content, 11, $endPos - 11);
                $remainingContent = substr($content, $endPos + 3);

                $layout = json_decode($layoutJson, true);
                if ($layout) {
                    return [
                        'layout' => $layout,
                        'content' => $remainingContent
                    ];
                }
            }
        }

        return [
            'layout' => null,
            'content' => $content
        ];
    }

    /**
     * Create empty layout
     */
    public static function createEmptyLayout()
    {
        return [
            'rows' => [
                [
                    'id' => 'row-' . uniqid(),
                    'layout' => 'full',
                    'columns' => [
                        ['components' => []]
                    ]
                ]
            ]
        ];
    }

    /**
     * Add row to layout
     */
    public static function addRow(&$layout, $preset = 'full', $position = null)
    {
        $presetConfig = self::PRESETS[$preset] ?? self::PRESETS['full'];

        $columns = [];
        foreach ($presetConfig['columns'] as $width) {
            $columns[] = ['components' => []];
        }

        $row = [
            'id' => 'row-' . uniqid(),
            'layout' => $preset,
            'columns' => $columns
        ];

        if ($position === null) {
            $layout['rows'][] = $row;
        } else {
            array_splice($layout['rows'], $position, 0, [$row]);
        }

        return $row['id'];
    }

    /**
     * Remove row from layout
     */
    public static function removeRow(&$layout, $rowId)
    {
        foreach ($layout['rows'] as $i => $row) {
            if ($row['id'] === $rowId) {
                array_splice($layout['rows'], $i, 1);
                return true;
            }
        }
        return false;
    }

    /**
     * Add component to column
     */
    public static function addComponent(&$layout, $rowId, $columnIndex, $component)
    {
        foreach ($layout['rows'] as &$row) {
            if ($row['id'] === $rowId) {
                if (isset($row['columns'][$columnIndex])) {
                    $row['columns'][$columnIndex]['components'][] = $component;
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * Get preset list for UI
     */
    public static function getPresets()
    {
        return self::PRESETS;
    }

    /**
     * Convert layout to content string with marker
     */
    /**
     * Convert layout to content string with marker
     */
    public static function layoutToContent($layout, $additionalContent = '')
    {
        return '<!--LAYOUT:' . json_encode($layout) . '-->' . $additionalContent;
    }

    /**
     * Parse legacy content (shortcodes without layout marker)
     * Returns a valid layout array
     */
    public static function parseLegacyContent($content)
    {
        // Extract all components
        preg_match_all('/\[component:([a-z0-9_-]+)(.*?)\]/is', $content, $matches);

        $components = [];
        if (!empty($matches[0])) {
            foreach ($matches[0] as $fullShortcode) {
                $components[] = $fullShortcode;
            }
        }

        // If no components found, but content exists, try to wrap text?
        // For now, only extract recognized components

        if (empty($components)) {
            return null; // No components found
        }

        // Create a single Full Width row containing all components
        return [
            'rows' => [
                [
                    'id' => 'legacy-' . uniqid(),
                    'layout' => 'full',
                    'background' => null,
                    'padding' => 'normal',
                    'columns' => [
                        [
                            'components' => $components
                        ]
                    ]
                ]
            ]
        ];
    }
}
