<?php

namespace App\Campaigns;

class TikTokCampaignFlow
{
    /** @return array<string, array{label: string, fields: list<array{key: string, label: string}>}> */
    public function stages(array $draft): array
    {
        $objective = strtolower((string) ($draft['objective'] ?? ''));
        $destination = strtolower((string) ($draft['promotion_type'] ?? ''));
        $optimizationGoal = strtolower((string) ($draft['optimization_goal'] ?? ''));
        $campaignType = strtolower((string) ($draft['campaign_type'] ?? ''));
        $budgetOptimization = strtolower((string) ($draft['campaign_budget_optimization'] ?? ''));
        $targetingMode = strtolower((string) ($draft['targeting_mode'] ?? ''));
        $identityMode = strtolower((string) ($draft['identity_mode'] ?? ''));
        $creativeSource = strtolower((string) ($draft['creative_source'] ?? ''));
        $trackingEnabled = strtolower((string) ($draft['tracking_enabled'] ?? ''));

        return [
            'advertiser' => ['label' => 'Advertiser account', 'fields' => [
                ['key' => 'advertiser_id', 'label' => 'Verified advertiser account'],
            ]],
            'objective' => ['label' => 'Objective', 'fields' => [
                ['key' => 'objective', 'label' => 'Campaign objective'],
            ]],
            'campaign_type' => ['label' => 'Campaign type', 'fields' => [
                ['key' => 'campaign_type', 'label' => 'Campaign type'],
            ]],
            'destination' => ['label' => 'Destination / promotion', 'fields' => [
                ['key' => 'promotion_type', 'label' => 'Destination / promotion type'],
            ]],
            'campaign_settings' => ['label' => 'Campaign settings', 'fields' => [
                ['key' => 'campaign_name', 'label' => 'Campaign name'],
                ['key' => 'budget_type', 'label' => 'Budget type'],
                ['key' => 'campaign_budget_optimization', 'label' => 'Campaign budget optimization'],
                ...($budgetOptimization === 'on' ? [['key' => 'campaign_budget', 'label' => 'Campaign budget']] : []),
            ]],
            'optimization' => ['label' => 'Optimization', 'fields' => [
                ['key' => 'optimization_location', 'label' => 'Optimization location'],
                ['key' => 'optimization_goal', 'label' => 'Optimization goal'],
                ...($optimizationGoal === 'conversion' ? [
                    ['key' => 'conversion_event', 'label' => 'Conversion event'],
                    ['key' => 'pixel_id', 'label' => 'Pixel'],
                    ['key' => 'value_optimization', 'label' => 'Value optimization'],
                ] : []),
                ...($destination === 'app' ? [['key' => 'app_event', 'label' => 'App event']] : []),
            ]],
            'ad_group' => ['label' => 'Ad group', 'fields' => $this->adGroupFields($budgetOptimization, $targetingMode, $objective)],
            'keywords' => ['label' => 'Keywords', 'fields' => $campaignType === 'search_campaign' ? [
                ['key' => 'keywords', 'label' => 'Keywords'],
                ['key' => 'keyword_match_type', 'label' => 'Match / targeting configuration'],
                ['key' => 'negative_keywords', 'label' => 'Negative keywords'],
            ] : []],
            'identity' => ['label' => 'Identity', 'fields' => [
                ['key' => 'identity_mode', 'label' => 'Identity type'],
                ['key' => 'identity_id', 'label' => 'Authorized TikTok identity'],
            ]],
            'creative_source' => ['label' => 'Creative source', 'fields' => [
                ['key' => 'creative_source', 'label' => 'Creative source'],
            ]],
            'creative' => ['label' => 'Creative', 'fields' => $this->creativeFields($identityMode, $creativeSource, $objective)],
            'ad_content' => ['label' => 'Ad content', 'fields' => $this->adContentFields($destination)],
            'tracking' => ['label' => 'Tracking', 'fields' => [
                ['key' => 'tracking_enabled', 'label' => 'Conversion tracking'],
                ...($trackingEnabled === 'yes' ? [
                    ['key' => 'tracking_pixel_id', 'label' => 'Tracking pixel'],
                    ['key' => 'tracking_events', 'label' => 'Tracked events'],
                    ['key' => 'tracking_url_parameters', 'label' => 'URL parameters'],
                    ...($destination === 'app' ? [['key' => 'app_tracking', 'label' => 'App tracking']] : []),
                ] : []),
            ]],
            'validation' => ['label' => 'Validation', 'fields' => [
                ['key' => 'validation_status', 'label' => 'Campaign validation'],
            ]],
        ];
    }

    /** @return array{stage: string, stage_label: string, field: string, label: string}|null */
    public function next(array $draft): ?array
    {
        foreach ($this->stages($draft) as $stage => $definition) {
            foreach ($definition['fields'] as $field) {
                if (! filled($draft[$field['key']] ?? null)) {
                    return ['stage' => $stage, 'stage_label' => $definition['label'], 'field' => $field['key'], 'label' => $field['label']];
                }
            }
        }

        return null;
    }

    public function stageComplete(string $stage, array $draft): bool
    {
        $definition = $this->stages($draft)[$stage] ?? null;

        return is_array($definition) && collect($definition['fields'])->every(fn (array $field): bool => filled($draft[$field['key']] ?? null));
    }

    /** @return list<array{key: string, label: string}> */
    private function adGroupFields(string $budgetOptimization, string $targetingMode, string $objective): array
    {
        $fields = [
            ['key' => 'adgroup_name', 'label' => 'Ad group name'],
            ['key' => 'placement', 'label' => 'Placement'],
            ['key' => 'targeting_mode', 'label' => 'Targeting mode'],
            ['key' => 'location_id', 'label' => 'Location'],
        ];
        if ($targetingMode === 'manual') {
            $fields = [...$fields,
                ['key' => 'age_groups', 'label' => 'Age'],
                ['key' => 'gender', 'label' => 'Gender'],
                ['key' => 'languages', 'label' => 'Language'],
                ['key' => 'interest_categories', 'label' => 'Interests'],
                ['key' => 'behaviors', 'label' => 'Behaviors'],
                ['key' => 'custom_audience_id', 'label' => 'Custom audience'],
                ['key' => 'lookalike_audience_id', 'label' => 'Lookalike audience'],
            ];
        }
        if ($targetingMode === 'expansion') {
            $fields[] = ['key' => 'targeting_expansion', 'label' => 'Automatic targeting / expansion'];
        }
        if ($budgetOptimization !== 'on') {
            $fields[] = ['key' => 'daily_budget', 'label' => 'Ad-group budget'];
        }
        if ($objective === 'reach') {
            $fields[] = ['key' => 'frequency_cap', 'label' => 'Frequency cap'];
        }

        return [...$fields,
            ['key' => 'schedule', 'label' => 'Schedule'],
            ['key' => 'bidding_strategy', 'label' => 'Bid strategy'],
            ['key' => 'bid_cap', 'label' => 'Bid / cost cap'],
            ['key' => 'adgroup_optimization_goal', 'label' => 'Ad-group optimization'],
            ['key' => 'delivery_settings', 'label' => 'Delivery settings'],
        ];
    }

    /** @return list<array{key: string, label: string}> */
    private function creativeFields(string $identityMode, string $creativeSource, string $objective): array
    {
        $fields = [['key' => 'creative_format', 'label' => 'Creative format']];
        if ($identityMode === 'spark' || $creativeSource === 'tiktok_post') {
            $fields[] = ['key' => 'tiktok_item_id', 'label' => 'Existing TikTok post'];
        } elseif (filled($creativeSource)) {
            $fields[] = ['key' => 'creative_asset_ids', 'label' => 'Selected creative or upload'];
        }
        if ($objective === 'sales' && $creativeSource === 'catalog') {
            $fields[] = ['key' => 'catalog_creative_id', 'label' => 'Catalog creative'];
        }

        return $fields;
    }

    /** @return list<array{key: string, label: string}> */
    private function adContentFields(string $destination): array
    {
        $fields = [
            ['key' => 'ad_text', 'label' => 'Ad text'],
            ['key' => 'call_to_action', 'label' => 'Call to action'],
            ['key' => 'display_name', 'label' => 'Display name'],
            ['key' => 'profile_image_id', 'label' => 'Profile image'],
        ];
        if ($destination === 'website') {
            $fields[] = ['key' => 'landing_page_url', 'label' => 'Destination URL'];
        } elseif ($destination === 'app') {
            $fields[] = ['key' => 'app_store_url', 'label' => 'App store URL'];
            $fields[] = ['key' => 'deep_link_url', 'label' => 'Deep link'];
        } elseif ($destination === 'instant_form') {
            $fields[] = ['key' => 'instant_form_id', 'label' => 'Instant form'];
        } elseif ($destination === 'tiktok_shop') {
            $fields[] = ['key' => 'product_id', 'label' => 'Product'];
            $fields[] = ['key' => 'product_set_id', 'label' => 'Product set'];
        }

        return $fields;
    }
}
