<?php
namespace Components\Data\Mock;

use Components\Data\Contracts\ModuleProvider;
use Components\ModuleLoader;

class MockModuleProvider implements ModuleProvider
{
    public function all(): array
    {
        $all = [];
        foreach ($this->triggersByGroup() as $group => $mods) {
            foreach ($mods as $m) {
                $all[$m['key']] = $m;
            }
        }
        foreach ($this->serviceModulesByGroup() as $group => $mods) {
            foreach ($mods as $m) {
                $all[$m['key']] = $m;
            }
        }
        foreach ($this->filterModulesByGroup() as $group => $mods) {
            foreach ($mods as $m) {
                $all[$m['key']] = $m;
            }
        }
        foreach ($this->configModulesByGroup() as $group => $mods) {
            foreach ($mods as $m) {
                $all[$m['key']] = $m;
            }
        }
        return $all;
    }

    public function triggersByGroup(?bool $onlyInstalled = true): array
    {
        $groups = [
            'Acquisition' => [
                [
                    'key' => 'welcome_series',
                    'title' => 'Welcome Series',
                    'desc' => 'Greet new subscribers with a warm welcome and introduce your brand.',
                    'color' => 'bg-emerald-500 text-white',
                    'svg_icon' => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M12 20l-8-9 8-7 8 7-8 9z"/></svg>',
                ],
                [
                    'key' => 'browse_abandonment',
                    'title' => 'Browse Abandonment',
                    'desc' => 'Remind visitors of products they viewed but didn\'t add to cart.',
                    'color' => 'bg-sky-500 text-white',
                    'svg_icon' => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"/><path d="M21 21l-4.3-4.3"/></svg>',
                ],
            ],
            'Conversion' => [
                [
                    'key' => 'abandoned_cart',
                    'title' => 'Abandoned Cart',
                    'desc' => 'Recover lost revenue by nudging shoppers to complete checkout.',
                    'color' => 'bg-orange-500 text-white',
                    'svg_icon' => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M6 6h15l-1.5 9h-12z"/><path d="M6 6l-1-3H3"/><circle cx="9" cy="20" r="1.5"/><circle cx="18" cy="20" r="1.5"/></svg>',
                ],
            ],
            'Post-Purchase' => [
                [
                    'key' => 'product_review_invites',
                    'title' => 'Product Review Invites',
                    'desc' => 'Collect authentic product reviews to build trust and improve SEO.',
                    'color' => 'bg-purple-500 text-white',
                    'svg_icon' => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M12 17.27L18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21z"/></svg>',
                ],
                [
                    'key' => 'order_followup',
                    'title' => 'Order Follow-up',
                    'desc' => 'Thank customers, provide tips, and recommend complementary items.',
                    'color' => 'bg-brand text-white',
                    'svg_icon' => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="14" rx="2"/><path d="M3 7l9 6 9-6"/></svg>',
                ],
            ],
            'Retention & Loyalty' => [
                [
                    'key' => 'win_back',
                    'title' => 'Win Back',
                    'desc' => 'Re-engage inactive customers with targeted incentives and content.',
                    'color' => 'bg-rose-500 text-white',
                    'svg_icon' => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12a9 9 0 1 1-9-9"/><path d="M21 3v6h-6"/></svg>',
                ],
                [
                    'key' => 'birthday_greetings',
                    'title' => 'Birthday Greetings',
                    'desc' => 'Delight customers on their birthday with a personal message and offer.',
                    'color' => 'bg-pink-500 text-white',
                    'svg_icon' => '<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="size-6">
  <path stroke-linecap="round" stroke-linejoin="round" d="M12 8.25v-1.5m0 1.5c-1.355 0-2.697.056-4.024.166C6.845 8.51 6 9.473 6 10.608v2.513m6-4.871c1.355 0 2.697.056 4.024.166C17.155 8.51 18 9.473 18 10.608v2.513M15 8.25v-1.5m-6 1.5v-1.5m12 9.75-1.5.75a3.354 3.354 0 0 1-3 0 3.354 3.354 0 0 0-3 0 3.354 3.354 0 0 1-3 0 3.354 3.354 0 0 0-3 0 3.354 3.354 0 0 1-3 0L3 16.5m15-3.379a48.474 48.474 0 0 0-6-.371c-2.032 0-4.034.126-6 .371m12 0c.39.049.777.102 1.163.16 1.07.16 1.837 1.094 1.837 2.175v5.169c0 .621-.504 1.125-1.125 1.125H4.125A1.125 1.125 0 0 1 3 20.625v-5.17c0-1.08.768-2.014 1.837-2.174A47.78 47.78 0 0 1 6 13.12M12.265 3.11a.375.375 0 1 1-.53 0L12 2.845l.265.265Zm-3 0a.375.375 0 1 1-.53 0L9 2.845l.265.265Zm6 0a.375.375 0 1 1-.53 0L15 2.845l.265.265Z" />
</svg>
',
                ],
            ],
        ];

        if ($onlyInstalled === false) {
            $groups = [
                'New Modules' => [
                    [
                        'key' => 'uninstalled_module_1',
                        'title' => 'Newsletter Signup Follow-up',
                        'desc' => 'Engage new subscribers immediately after they join your list.',
                        'color' => 'bg-indigo-500 text-white',
                        'svg_icon' => '<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="size-6"><path stroke-linecap="round" stroke-linejoin="round" d="M6 12 3.269 3.125A59.769 59.769 0 0 1 21.485 12 59.768 59.768 0 0 1 3.27 20.875L5.999 12Zm0 0h7.5" /></svg>',
                    ],
                ]
            ];
        } elseif ($onlyInstalled === null) {
            $groups['New Modules'] = [
                [
                    'key' => 'uninstalled_module_1',
                    'title' => 'Newsletter Signup Follow-up',
                    'desc' => 'Engage new subscribers immediately after they join your list.',
                    'color' => 'bg-indigo-500 text-white',
                    'svg_icon' => '<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="size-6"><path stroke-linecap="round" stroke-linejoin="round" d="M6 12 3.269 3.125A59.769 59.769 0 0 1 21.485 12 59.768 59.768 0 0 1 3.27 20.875L5.999 12Zm0 0h7.5" /></svg>',
                ],
            ];
        }

        $out = [];
        foreach ($groups as $group => $mods) {
            foreach ($mods as $m) {
                $item = ModuleLoader::common(
                    $m['key'],
                    $m['title'],
                    $m['desc'] ?? '',
                    $group,
                    'campaign'
                );
                $item['flow'] = self::flowForKey($m['key']);
                if (isset($m['color'])) { $item['color'] = $m['color']; }
                if (isset($m['svg_icon'])) { $item['svg_icon'] = $m['svg_icon']; }
                $out[$group][] = $item;
            }
        }
        return $out;
    }

    public function triggerByKey(string $key, ?bool $onlyInstalled = true): ?array
    {
        $key = trim($key);
        if ($key === '') {
            return null;
        }

        foreach ($this->triggersByGroup($onlyInstalled) as $mods) {
            foreach ($mods as $m) {
                if (($m['key'] ?? '') === $key) {
                    return $m;
                }
            }
        }

        return null;
    }

    public function serviceModulesByGroup(): array
    {
        $groups = [
            'Services' => [
                ['key' => 'clean_list', 'title' => 'Clean List', 'desc' => 'Remove invalid or bounced emails from your list.'],
                ['key' => 'clean_archive', 'title' => 'Clean Archive', 'desc' => 'Archive inactive or unsubscribed contacts.'],
            ],
        ];
        $out = [];
        foreach ($groups as $group => $mods) {
            foreach ($mods as $m) {
                $item = ModuleLoader::common(
                    $m['key'],
                    $m['title'],
                    $m['desc'] ?? '',
                    $group,
                    'service'
                );
                $out[$group][] = $item;
            }
        }
        return $out;
    }

    public function filterModulesByGroup(): array
    {
        $groups = [
            'Filters' => [
                ['key' => 'customer_groups', 'title' => 'Customer Groups', 'desc' => 'Target specific customer segments.'],
                ['key' => 'throttling', 'title' => 'Throttling', 'desc' => 'Limit sending rate to manage deliverability.'],
            ],
        ];
        $out = [];
        foreach ($groups as $group => $mods) {
            foreach ($mods as $m) {
                $item = ModuleLoader::common(
                    $m['key'],
                    $m['title'],
                    $m['desc'] ?? '',
                    $group,
                    'filter'
                );
                $out[$group][] = $item;
            }
        }
        return $out;
    }

    public function configModulesByGroup(): array
    {
        // Return grouped configuration modules using the common module structure
        $groups = [
            'Overview' => [
                ['key' => 'overview', 'title' => 'Overview', 'desc' => '']
            ],
            'Setup' => [
                ['key' => 'email_engine', 'title' => 'Email Engine', 'desc' => ''],
                ['key' => 'analytics',    'title' => 'Analytics',    'desc' => ''],
                ['key' => 'reports',      'title' => 'Reports',      'desc' => ''],
            ],
            'Design' => [
                ['key' => 'template_designer', 'title' => 'Template Designer', 'desc' => ''],
                ['key' => 'editor',            'title' => 'Editor',            'desc' => ''],
            ],
            'Services' => [
                ['key' => 'service_modules', 'title' => 'Service Modules', 'desc' => ''],
                ['key' => 'filter_modules',  'title' => 'Filter Modules',  'desc' => ''],
            ],
        ];
        $out = [];
        foreach ($groups as $group => $mods) {
            foreach ($mods as $m) {
                $out[$group][] = ModuleLoader::common($m['key'], $m['title'], $m['desc'], $group, 'configuration');
            }
        }
        return $out;
    }

    public function extensions(string $module): array
    {
        $map = [
            'email_engine' => [
                ['key' => 'smtp_plus', 'title' => 'SMTP Plus', 'desc' => 'Advanced SMTP routing & failover for reliable delivery.', 'installed' => false, 'url' => '#'],
                ['key' => 'bounce_guard', 'title' => 'Bounce Guard', 'desc' => 'Automated bounce processing to keep lists clean.', 'installed' => true, 'url' => '#'],
            ],
            'analytics' => [
                ['key' => 'ga4_bridge', 'title' => 'GA4 Bridge', 'desc' => 'Enhanced event mapping to Google Analytics 4.', 'installed' => true, 'url' => '#'],
            ],
            'reports' => [
                ['key' => 'pdf_export', 'title' => 'PDF Export', 'desc' => 'Export any report as branded PDF.', 'installed' => false, 'url' => '#'],
            ],
        ];
        $fallback = [
            ['key' => $module . '_tools', 'title' => 'Tools Pack', 'desc' => 'Handy utilities to extend the module capabilities.', 'installed' => false, 'url' => '#'],
        ];
        return $map[$module] ?? $fallback;
    }

    public function title(string $key): ?string
    {
        // Build a quick title map from campaigns, services, filters, and configuration
        $titles = [];
        foreach ($this->triggersByGroup() as $group => $mods) {
            foreach ($mods as $m) { $titles[$m['key']] = $m['title']; }
        }
        foreach ($this->serviceModulesByGroup() as $group => $mods) {
            foreach ($mods as $m) { $titles[$m['key']] = $m['title']; }
        }
        foreach ($this->filterModulesByGroup() as $group => $mods) {
            foreach ($mods as $m) { $titles[$m['key']] = $m['title']; }
        }
        foreach ($this->configuration() as $m) { $titles[$m['key']] = $m['title']; }
        return $titles[$key] ?? null;
    }

    public function exists(string $key): bool
    {
        $all = $this->all();
        return isset($all[$key]);
    }

    public function canUninstall(string $key): bool
    {
        $all = $this->all();
        return (bool)($all[$key]['can_uninstall'] ?? false);
    }

    // Private helper: flattened configuration list with titles
    private function configuration(): array
    {
        $defs = [
            ['key' => 'email_engine',      'title' => 'Email Engine'],
            ['key' => 'analytics',         'title' => 'Analytics'],
            ['key' => 'reports',           'title' => 'Reports'],
            ['key' => 'template_designer', 'title' => 'Template Designer'],
            ['key' => 'editor',            'title' => 'Editor'],
        ];
        $out = [];
        foreach ($defs as $d) {
            $out[] = ModuleLoader::common(
                $d['key'],
                $d['title'],
                $d['desc'] ?? '',
                'Configuration',
                'configuration'
            );
        }
        return $out;
    }
    private static function flowForKey(string $key): array
    {
        $B = '\\Components\\Base';
        $FB = '\\Components\\CampaignFlow\\FlowBuilder';

        switch ($key) {
            case 'welcome_series':
                return $FB::make()
                    ->trigger('New Subscriber', ['icon' => $B::SVG_TRIGGER, 'color' => 'blue'])
                    ->subtitle('Trigger')
                    ->wait('1 day')
                    ->step('w1', 'Welcome Email 1', ['icon' => $B::SVG_MAIL, 'color' => 'indigo'])
                    ->subtitle('Step 1')
                    ->wait('3 days')
                    ->step('w2', 'Welcome Email 2', ['icon' => $B::SVG_MAIL, 'color' => 'yellow'])
                    ->subtitle('Step 2')
                    ->wait('7 days')
                    ->step('w3', 'Welcome Email 3', ['icon' => $B::SVG_MAIL, 'color' => 'green'])
                    ->subtitle('Step 3')
                    ->addButton()
                    ->toArray();

            case 'browse_abandonment':
                return $FB::make()
                    ->trigger('Browsed Products', ['icon' => $B::SVG_TRIGGER, 'color' => 'blue'])
                    ->subtitle('Trigger')
                    ->marker(' text-blue-500/70 ', 'Filter applied', $B::SVG_FILTER)
                    ->wait('2 hours')
                    ->step('b1', 'Browse Reminder', ['icon' => $B::SVG_MAIL, 'color' => 'indigo'])
                    ->subtitle('Email')
                    ->addButton()
                    ->toArray();

            case 'abandoned_cart':
                return $FB::make()
                    ->trigger('Cart Abandoned', ['icon' => $B::SVG_TRIGGER, 'color' => 'blue'])
                    ->subtitle('Trigger')
                    ->wait('3 hours')
                    ->step('c1', 'Cart Reminder 1', ['icon' => $B::SVG_MAIL, 'color' => 'indigo'])
                    ->subtitle('Step 1')
                    ->wait('1 day')
                    ->step('c2', 'Cart Reminder 2', ['icon' => $B::SVG_MAIL, 'color' => 'yellow'])
                    ->subtitle('Step 2')
                    ->addButton()
                    ->toArray();

            case 'product_review_invites':
                return $FB::make()
                    ->trigger('Order Completed', ['icon' => $B::SVG_TRIGGER, 'color' => 'blue'])
                    ->subtitle('Trigger')
                    ->wait('7 days')
                    ->step('r1', 'Review Request', ['icon' => $B::SVG_MAIL, 'color' => 'indigo'])
                    ->subtitle('Email')
                    ->addButton()
                    ->toArray();

            case 'order_followup':
                return $FB::make()
                    ->trigger('Order Completed', ['icon' => $B::SVG_TRIGGER, 'color' => 'blue'])
                    ->subtitle('Trigger')
                    ->wait('2 days')
                    ->step('f1', 'Thank You Email', ['icon' => $B::SVG_MAIL, 'color' => 'green'])
                    ->subtitle('Step 1')
                    ->wait('10 days')
                    ->step('f2', 'Cross-sell Offer', ['icon' => $B::SVG_MAIL, 'color' => 'yellow'])
                    ->subtitle('Step 2')
                    ->addButton()
                    ->toArray();

            case 'win_back':
                return $FB::make()
                    ->trigger('Last Order', ['icon' => $B::SVG_TRIGGER, 'color' => 'blue'])
                    ->subtitle('Trigger')
                    ->wait('90 days')
                    ->step('w1', 'Win-back Offer', ['icon' => $B::SVG_MAIL, 'color' => 'indigo'])
                    ->subtitle('Step 1')
                    ->wait('14 days')
                    ->step('w2', 'Second Attempt', ['icon' => $B::SVG_MAIL, 'color' => 'orange'])
                    ->subtitle('Step 2')
                    ->addButton()
                    ->toArray();

            case 'birthday_greetings':
                return $FB::make()
                    ->trigger('Birthday', ['icon' => $B::SVG_TRIGGER, 'color' => 'blue'])
                    ->subtitle('Trigger')
                    ->wait('On date')
                    ->step('bday1', 'Birthday Greeting', ['icon' => $B::SVG_MAIL, 'color' => 'pink'])
                    ->subtitle('Email')
//                    ->addButton()
                    ->toArray();
        }

        // Default simple two-step flow
        return $FB::make()
            ->trigger('Event', ['icon' => $B::SVG_TRIGGER, 'color' => 'blue'])
            ->subtitle('Trigger')
            ->wait('3 days')
            ->step('s1', 'Follow-up Email', ['icon' => $B::SVG_MAIL, 'color' => 'indigo'])
            ->subtitle('Step 1')
            ->addButton()
            ->toArray();
    }
}
