<?php

namespace App\Support;

class HomePageHtml
{
    public static function parse(mixed $html): array
    {
        if (is_string($html)) {
            $decoded = json_decode($html, true);

            return self::mergeDefaults(is_array($decoded) ? $decoded : null);
        }

        if (is_array($html)) {
            return self::mergeDefaults($html);
        }

        return self::mergeDefaults(null);
    }

    public static function mergeDefaults(?array $html): array
    {
        $html = $html ?? [];
        $sections = $html['sections'] ?? [];

        if (! is_array($sections)) {
            $sections = [];
        }

        for ($i = 0; $i <= 6; $i++) {
            if (! isset($sections[$i]) || ! is_array($sections[$i])) {
                $sections[$i] = [];
            }
        }

        $sections[0] = array_merge(
            ['enabled' => true],
            $sections[0],
            [
                'kb_button' => array_merge(
                    ['enabled' => true, 'text' => 'Browse Knowledge Base', 'link' => '/kb'],
                    is_array($sections[0]['kb_button'] ?? null) ? $sections[0]['kb_button'] : []
                ),
            ]
        );

        if (empty($sections[0]['hero_overlays']) || ! is_array($sections[0]['hero_overlays'])) {
            $sections[0]['hero_overlays'] = self::defaultHeroOverlays();
        }

        if (empty($sections[0]['trust_indicators']) || ! is_array($sections[0]['trust_indicators'])) {
            $sections[0]['trust_indicators'] = [
                'Free 14-day trial',
                'No credit card required',
                '24/7 support',
            ];
        }

        if (empty($sections[0]['buttons']) || ! is_array($sections[0]['buttons'])) {
            $sections[0]['buttons'] = $sections[0]['buttons'] ?? [];
        }

        if (! isset($sections[1]['enabled'])) {
            $sections[1]['enabled'] = true;
        }
        if (empty($sections[1]['features']) || ! is_array($sections[1]['features'])) {
            $sections[1]['features'] = $sections[1]['features'] ?? [];
        }

        $sections[2] = array_merge(
            [
                'enable_ticket_section' => false,
                'form_badges' => ['Secure Submission', 'Ticket Tracking', 'Email Updates'],
            ],
            $sections[2]
        );

        $sections[2]['enable_ticket_section'] = self::toBool($sections[2]['enable_ticket_section'] ?? false);

        if (! is_array($sections[2]['form_badges']) || $sections[2]['form_badges'] === []) {
            $sections[2]['form_badges'] = ['Secure Submission', 'Ticket Tracking', 'Email Updates'];
        }

        if (! isset($sections[3]['enabled'])) {
            $sections[3]['enabled'] = true;
        }
        if (empty($sections[3]['stats']) || ! is_array($sections[3]['stats'])) {
            $sections[3]['stats'] = $sections[3]['stats'] ?? [];
        }

        if (! isset($sections[4]['enabled'])) {
            $sections[4]['enabled'] = true;
        }
        if (empty($sections[4]['testimonials']) || ! is_array($sections[4]['testimonials'])) {
            $sections[4]['testimonials'] = $sections[4]['testimonials'] ?? [];
        }

        $sections[5] = array_merge(
            ['enabled' => true, 'items' => self::defaultTrustStripItems()],
            $sections[5]
        );
        if (empty($sections[5]['items']) || ! is_array($sections[5]['items'])) {
            $sections[5]['items'] = self::defaultTrustStripItems();
        }

        $sections[6] = array_merge(
            [
                'enabled' => true,
                'title' => 'Choose Your Support Channel',
                'subtitle' => 'Give your customers multiple ways to reach your team and resolve issues quickly.',
                'channels' => self::defaultSupportChannels(),
            ],
            $sections[6]
        );
        if (empty($sections[6]['channels']) || ! is_array($sections[6]['channels'])) {
            $sections[6]['channels'] = self::defaultSupportChannels();
        }

        $html['sections'] = self::reindexSections($sections);

        return $html;
    }

    private static function toBool(mixed $value): bool
    {
        return filter_var($value, FILTER_VALIDATE_BOOLEAN);
    }

    public static function encode(mixed $html): string
    {
        return json_encode(self::parse($html));
    }

    private static function reindexSections(array $sections): array
    {
        $ordered = [];
        for ($i = 0; $i <= 6; $i++) {
            $ordered[$i] = $sections[$i] ?? [];
        }

        return $ordered;
    }

    private static function defaultHeroOverlays(): array
    {
        return [
            [
                'enabled' => true,
                'label' => 'Live Queue',
                'title' => '12 tickets active',
                'status' => 'Healthy',
                'show_check' => false,
            ],
            [
                'enabled' => true,
                'label' => 'SLA Compliance',
                'title' => '99.2% this week',
                'status' => '',
                'show_check' => true,
            ],
        ];
    }

    private static function defaultTrustStripItems(): array
    {
        return [
            ['icon' => 'clock', 'label' => 'Average First Response', 'value' => '< 2 Hours', 'theme' => 'primary'],
            ['icon' => 'shield', 'label' => 'Reliability', 'value' => 'Secure & Auditable', 'theme' => 'emerald'],
            ['icon' => 'zap', 'label' => 'Automation Ready', 'value' => 'Smart Ticket Routing', 'theme' => 'blue'],
            ['icon' => 'users', 'label' => 'Built For Teams', 'value' => 'Agent + Customer Portal', 'theme' => 'purple'],
        ];
    }

    private static function defaultSupportChannels(): array
    {
        return [
            [
                'icon' => 'ticket',
                'title' => 'Open A Ticket',
                'description' => 'Structured issue reporting with status tracking, attachments, and notifications.',
                'link_text' => 'Start secure submission',
                'route' => 'ticket_open',
                'link' => '',
                'theme' => 'primary',
            ],
            [
                'icon' => 'mail',
                'title' => 'Contact Team',
                'description' => 'For sales, onboarding, or support questions that need guided consultation.',
                'link_text' => 'Connect with experts',
                'route' => 'contact',
                'link' => '',
                'theme' => 'blue',
            ],
            [
                'icon' => 'help-circle',
                'title' => 'Self-Service FAQ',
                'description' => 'Enable users to solve common issues instantly with curated help content.',
                'link_text' => 'Resolve faster with docs',
                'route' => 'faq',
                'link' => '',
                'theme' => 'purple',
            ],
        ];
    }
}
