<?php

namespace Core\App\Services;

class LandingStructureBuilder
{
    private const ALLOWED_SECTION_TYPES = [
        'hero',
        'banner',
        'benefits',
        'features',
        'gallery',
        'pricing',
        'testimonials',
        'faq',
        'guarantee',
        'cta',
        'checkout',
        'social-proof',
        'stats',
    ];

    public function build(array $analysis, array $product): array
    {
        $hero = $this->normalizeHero($analysis['hero'] ?? [], $analysis, $product);
        $sections = $this->normalizeSections($analysis['sections'] ?? [], $product);

        if (!$this->hasSectionType($sections, 'cta')) {
            $sections[] = [
                'type' => 'cta',
                'headline' => $hero['headline'] ?: ($product['title'] ?? 'Landing Page CTA'),
                'subheadline' => $hero['subheadline'] ?: strip_tags((string)($product['short_description'] ?? '')),
                'cta' => $hero['cta'] ?? ['text' => 'اطلب الآن', 'style' => 'primary'],
                'notes' => ['Strong closing CTA section'],
            ];
        }

        if (!$this->hasSectionType($sections, 'checkout')) {
            $sections[] = [
                'type' => 'checkout',
                'headline' => 'اطلب الآن',
                'subheadline' => 'أكمل بياناتك وسنؤكد طلبك بسرعة.',
                'cta' => ['text' => 'ابدأ الطلب', 'style' => 'primary'],
                'notes' => ['Embed the real order form iframe using {{ORDER_FORM}} placeholder'],
            ];
        }

        return [
            'page_goal' => $analysis['page_goal'] ?? 'product-conversion',
            'layout_style' => $analysis['layout_style'] ?? 'modern-product',
            'direction' => $analysis['visual_system']['direction'] ?? 'rtl',
            'visual_system' => $this->normalizeVisualSystem($analysis['visual_system'] ?? []),
            'hero' => $hero,
            'sections' => array_values($sections),
            'copy_elements' => [
                'pain_points' => $this->normalizeStringList($analysis['copy_elements']['pain_points'] ?? []),
                'benefits' => $this->normalizeStringList($analysis['copy_elements']['benefits'] ?? []),
                'trust_signals' => $this->normalizeStringList($analysis['copy_elements']['trust_signals'] ?? []),
                'offer' => (string)($analysis['copy_elements']['offer'] ?? ''),
                'urgency' => (string)($analysis['copy_elements']['urgency'] ?? ''),
            ],
            'cta_candidates' => $this->normalizeStringList($analysis['cta_candidates'] ?? []),
            'detected_text' => $this->normalizeStringList($analysis['detected_text'] ?? []),
            'conversion_notes' => $this->normalizeStringList($analysis['conversion_notes'] ?? []),
            'product_context' => [
                'id' => (int)($product['id'] ?? 0),
                'title' => (string)($product['title'] ?? $product['name'] ?? ''),
                'price' => (string)($product['sale_price'] ?? $product['price'] ?? ''),
                'currency' => (string)($product['currency'] ?? 'DZD'),
            ],
        ];
    }

    private function normalizeHero(array $hero, array $analysis, array $product): array
    {
        $headline = trim((string)($hero['headline'] ?? ''));
        if ($headline === '') {
            $headline = (string)($product['title'] ?? $product['name'] ?? 'منتج مميز');
        }

        $subheadline = trim((string)($hero['subheadline'] ?? ''));
        if ($subheadline === '') {
            $subheadline = trim(strip_tags((string)($product['short_description'] ?? $product['description'] ?? '')));
        }

        $ctaText = trim((string)($hero['cta']['text'] ?? ''));
        if ($ctaText === '') {
            $ctaCandidates = $this->normalizeStringList($analysis['cta_candidates'] ?? []);
            $ctaText = $ctaCandidates[0] ?? 'اطلب الآن';
        }

        return [
            'headline' => $headline,
            'subheadline' => $subheadline,
            'media' => (string)($hero['media'] ?? 'product'),
            'badge' => (string)($hero['badge'] ?? ''),
            'cta' => [
                'text' => $ctaText,
                'style' => (string)($hero['cta']['style'] ?? 'primary'),
            ],
            'notes' => $this->normalizeStringList($hero['notes'] ?? []),
        ];
    }

    private function normalizeSections(array $sections, array $product): array
    {
        $normalized = [];

        foreach ($sections as $section) {
            if (!is_array($section)) {
                continue;
            }

            $type = strtolower(trim((string)($section['type'] ?? '')));
            if (!in_array($type, self::ALLOWED_SECTION_TYPES, true)) {
                continue;
            }

            $normalized[] = [
                'type' => $type,
                'label' => (string)($section['label'] ?? ucfirst(str_replace('-', ' ', $type))),
                'headline' => (string)($section['headline'] ?? ''),
                'subheadline' => (string)($section['subheadline'] ?? ''),
                'purpose' => (string)($section['purpose'] ?? ''),
                'items' => $this->normalizeMixedList($section['items'] ?? []),
                'cta' => [
                    'text' => (string)($section['cta']['text'] ?? ''),
                    'style' => (string)($section['cta']['style'] ?? 'primary'),
                ],
                'background' => (string)($section['background'] ?? ''),
                'notes' => $this->normalizeStringList($section['notes'] ?? []),
            ];
        }

        if (empty($normalized)) {
            $normalized = [
                [
                    'type' => 'features',
                    'label' => 'Features',
                    'headline' => 'لماذا هذا المنتج؟',
                    'subheadline' => '',
                    'purpose' => 'Highlight core benefits',
                    'items' => $this->normalizeStringList($product['features'] ?? []),
                    'cta' => ['text' => '', 'style' => 'secondary'],
                    'background' => '',
                    'notes' => [],
                ],
            ];
        }

        return $normalized;
    }

    private function normalizeVisualSystem(array $visualSystem): array
    {
        return [
            'direction' => in_array($visualSystem['direction'] ?? 'rtl', ['rtl', 'ltr'], true)
                ? (string)$visualSystem['direction']
                : 'rtl',
            'primary_color' => $this->normalizeHex((string)($visualSystem['primary_color'] ?? '#0f172a')),
            'secondary_color' => $this->normalizeHex((string)($visualSystem['secondary_color'] ?? '#1d4ed8')),
            'accent_color' => $this->normalizeHex((string)($visualSystem['accent_color'] ?? '#f59e0b')),
            'background_color' => $this->normalizeHex((string)($visualSystem['background_color'] ?? '#ffffff')),
            'text_color' => $this->normalizeHex((string)($visualSystem['text_color'] ?? '#111827')),
            'font_style' => (string)($visualSystem['font_style'] ?? 'modern'),
            'mood' => (string)($visualSystem['mood'] ?? 'clean'),
        ];
    }

    private function normalizeStringList($items): array
    {
        if (!is_array($items)) {
            return [];
        }

        $result = [];
        foreach ($items as $item) {
            $value = trim((string)$item);
            if ($value !== '') {
                $result[] = $value;
            }
        }
        return array_values(array_unique($result));
    }

    private function normalizeMixedList($items): array
    {
        if (!is_array($items)) {
            return [];
        }

        $result = [];
        foreach ($items as $item) {
            if (is_array($item)) {
                $clean = [];
                foreach ($item as $key => $value) {
                    if (is_scalar($value) || $value === null) {
                        $clean[(string)$key] = trim((string)$value);
                    }
                }
                if (!empty($clean)) {
                    $result[] = $clean;
                }
                continue;
            }

            $value = trim((string)$item);
            if ($value !== '') {
                $result[] = $value;
            }
        }

        return $result;
    }

    private function normalizeHex(string $color): string
    {
        $color = trim($color);
        if (!preg_match('/^#?[0-9a-fA-F]{6}$/', $color)) {
            return '#111827';
        }
        return strpos($color, '#') === 0 ? $color : '#' . $color;
    }

    private function hasSectionType(array $sections, string $type): bool
    {
        foreach ($sections as $section) {
            if (($section['type'] ?? '') === $type) {
                return true;
            }
        }

        return false;
    }
}
