<?php

namespace UltraguardPro\modules\upgrade_manager\pages;

if ( ! defined( 'ABSPATH' ) ) { exit; }

use UltraguardPro\modules\core\BasePage;
use UltraguardPro\support\LicenseInfo;
use UltraguardPro\support\UpgradeManager;

abstract class UpgradeManagerPage extends BasePage {

    protected function feature_plan_keys( array $feature ): array {
        $plans = array_values( array_unique( array_filter( array_map( 'sanitize_key', (array) ( $feature['plans'] ?? [ 'pro', 'agency' ] ) ) ) ) );

        if ( empty( $plans ) ) {
            return [ 'pro', 'agency' ];
        }

        return $plans;
    }

    protected function feature_section_title( string $module, array $module_features, array $module_meta ): string {
        if ( isset( $module_meta[ $module ]['name'] ) ) {
            return (string) $module_meta[ $module ]['name'];
        }

        $first_feature = reset( $module_features );
        if ( is_array( $first_feature ) && ! empty( $first_feature['group_label'] ) ) {
            return (string) $first_feature['group_label'];
        }

        return ucwords( str_replace( '_', ' ', $module ) );
    }

    protected function feature_section_icon( string $module, array $module_features, array $module_meta ): string {
        if ( isset( $module_meta[ $module ]['icon'] ) ) {
            return (string) $module_meta[ $module ]['icon'];
        }

        $first_feature = reset( $module_features );
        if ( is_array( $first_feature ) && ! empty( $first_feature['icon'] ) ) {
            return (string) $first_feature['icon'];
        }

        return 'dashicons-star-filled';
    }

    protected function license_status(): array {
        $status = LicenseInfo::make()->force( true )->getStatus();
        $data   = is_array( $status['data'] ?? null ) ? $status['data'] : [];

        $expiry_raw  = (string) ( $status['expires_at'] ?? '' );
        $manage_url  = (string) ( $status['manage_url'] ?? '' );
        $upgrade_url = (string) ( $status['upgrade_url'] ?? '' );
        $plan_slug   = sanitize_key( (string) ( $status['plan'] ?? 'free' ) );
        $plan_label  = (string) ( $data['plan_label'] ?? $data['plan_name'] ?? $data['tier_name'] ?? $data['license_type_label'] ?? ucwords( str_replace( '_', ' ', $plan_slug ?: 'free' ) ) );

        return [
            'status'             => (string) ( $status['status'] ?? 'free' ),
            'plan'               => $plan_slug ?: 'free',
            'plan_label'         => $plan_label ?: __( 'Free', 'ultraguard-security-suite' ),
            'is_pro'             => (bool) ( $status['is_pro'] ?? false ),
            'is_valid'           => (bool) ( $status['is_valid'] ?? false ),
            'license_key'        => (string) ( $status['license_key'] ?? '' ),
            'license_key_masked' => (string) ( $status['key_masked'] ?? $data['key_masked'] ?? $status['license_key'] ?? '' ),
            'email'              => (string) ( $status['email'] ?? '' ),
            'expires_at'         => $expiry_raw,
            'expires_label'      => $this->format_date_value( $expiry_raw ),
            'manage_url'         => $manage_url ?: UpgradeManager::billing_portal_url(),
            'upgrade_url'        => $upgrade_url ?: UpgradeManager::external_upgrade_url(),
            'data'               => $data,
            'update_delay'       => (int) ( $status['update_delay'] ?? LicenseInfo::FREE_UPDATE_DELAY ),
        ];
    }

    protected function feature_modules(): array {
        $manager = $this->plugin->modules->get_module_manager();
        if ( ! $manager ) {
            return [];
        }

        $exclude = [ 'dashboard', 'settings', 'db_tables', 'onboarding', 'login_protect', 'upgrade_manager' ];
        $modules = [];

        foreach ( $manager->get_all_modules() as $id => $module ) {
            if ( in_array( $id, $exclude, true ) ) {
                continue;
            }

            $modules[ $id ] = $module;
        }

        uasort( $modules, static function ( array $left, array $right ): int {
            $left_group  = (string) ( $left['group'] ?? '' );
            $right_group = (string) ( $right['group'] ?? '' );

            if ( $left_group === $right_group ) {
                return strcasecmp( (string) ( $left['name'] ?? $left['id'] ?? '' ), (string) ( $right['name'] ?? $right['id'] ?? '' ) );
            }

            return strcasecmp( $left_group, $right_group );
        } );

        return $modules;
    }

    protected function free_locked_modules(): array {
        return array_filter( $this->feature_modules(), static function ( array $module ): bool {
            return ( $module['license_required'] ?? 'free' ) === 'pro';
        } );
    }

    protected function current_plan_modules(): array {
        $status = $this->license_status();

        return array_filter( $this->feature_modules(), static function ( array $module ) use ( $status ): bool {
            return 'free' === ( $module['license_required'] ?? 'free' ) || $status['is_pro'];
        } );
    }

    protected function build_module_rows( bool $only_pro = false ): array {
        $rows = [];

        foreach ( $this->feature_modules() as $module ) {
            $required = (string) ( $module['license_required'] ?? 'free' );
            if ( $only_pro && 'pro' !== $required ) {
                continue;
            }

            $rows[] = [
                'module'      => esc_html( (string) ( $module['name'] ?? $module['id'] ?? '' ) ),
                'group'       => esc_html( (string) ( $module['group'] ?? 'General' ) ),
                'license'     => [
                    'content' => [
                        'type'       => 'badge',
                        'content'    => 'pro' === $required ? __( 'Licensed', 'ultraguard-security-suite' ) : __( 'Free', 'ultraguard-security-suite' ),
                        'badge_type' => 'pro' === $required ? 'info' : 'secondary',
                    ],
                    'class'   => 'ultraguard-license-plan-cell',
                ],
                'description' => esc_html( (string) ( $module['description'] ?? '' ) ),
                'status'      => [
                    'content' => [
                        'type'       => 'badge',
                        'content'    => ! empty( $module['license_ok'] ) ? __( 'Available', 'ultraguard-security-suite' ) : __( 'License Required', 'ultraguard-security-suite' ),
                        'badge_type' => ! empty( $module['license_ok'] ) ? 'success' : 'warning',
                    ],
                    'class'   => ! empty( $module['license_ok'] )
                        ? 'ultraguard-license-access-cell ultraguard-license-access-cell--available'
                        : 'ultraguard-license-access-cell ultraguard-license-access-cell--locked',
                ],
            ];
        }

        return $rows;
    }

    protected function status_badge( array $status ): array {
        if ( $status['is_pro'] && $status['is_valid'] ) {
            return [
                /* translators: %s: string */
                'text'       => sprintf( __( '%s Active', 'ultraguard-security-suite' ), $status['plan_label'] ),
                'badge_type' => 'success',
            ];
        }

        if ( ! empty( $status['license_key'] ) && ! $status['is_valid'] ) {
            return [
                'text'       => __( 'Attention Needed', 'ultraguard-security-suite' ),
                'badge_type' => 'warning',
            ];
        }

        return [
            'text'       => __( 'Free Mode', 'ultraguard-security-suite' ),
            'badge_type' => 'warning',
        ];
    }

    protected function plan_overview_rows( array $status ): array {
        $rows = [
            [ 'item' => __( 'Plan', 'ultraguard-security-suite' ), 'value' => esc_html( $status['plan_label'] ) ],
            [ 'item' => __( 'Status', 'ultraguard-security-suite' ), 'value' => esc_html( ucfirst( $status['status'] ?: 'free' ) ) ],
            [ 'item' => __( 'License Key', 'ultraguard-security-suite' ), 'value' => esc_html( $status['license_key_masked'] ?: __( 'Not activated', 'ultraguard-security-suite' ) ) ],
            [ 'item' => __( 'Account Email', 'ultraguard-security-suite' ), 'value' => esc_html( $status['email'] ?: __( 'Not set', 'ultraguard-security-suite' ) ) ],
        ];

        if ( '' !== $status['expires_label'] ) {
            $rows[] = [ 'item' => __( 'Expires', 'ultraguard-security-suite' ), 'value' => esc_html( $status['expires_label'] ) ];
        }

        if ( isset( $status['data']['sites_used'] ) || isset( $status['data']['site_limit'] ) ) {
            $rows[] = [
                'item'  => __( 'Sites', 'ultraguard-security-suite' ),
                'value' => esc_html(
                    sprintf(
                        '%s / %s',
                        (string) ( $status['data']['sites_used'] ?? $status['data']['site_count'] ?? 0 ),
                        (string) ( $status['data']['site_limit'] ?? $status['data']['sites_allowed'] ?? '∞' )
                    )
                ),
            ];
        }

        return $rows;
    }

    protected function current_plan_key( array $status ): string {
        $plan = sanitize_key( (string) ( $status['plan'] ?? 'free' ) );

        if ( in_array( $plan, [ 'agency', 'agency_pro', 'agency-plan', 'agency_plan' ], true ) ) {
            return 'agency';
        }

        if ( $status['is_pro'] ) {
            return 'pro';
        }

        return 'free';
    }

    protected function build_plan_cards( array $status ): array {
        $current_plan = $this->current_plan_key( $status );
        $locked_count = count( $this->free_locked_modules() );

        $plans = [
            'free' => [
                'title'    => __( 'Free', 'ultraguard-security-suite' ),
                'price'    => __( '$0', 'ultraguard-security-suite' ),
                'subtitle' => __( 'Solid baseline protection for one WordPress site while you evaluate the full UltraGuard stack.', 'ultraguard-security-suite' ),
                'features' => [
                    __( 'Core firewall, login protection, audit logging, and malware defense basics', 'ultraguard-security-suite' ),
                    __( 'Preview premium security modules before you commit to a paid rollout', 'ultraguard-security-suite' ),
                    sprintf(
                        /* translators: %d: number of locked premium modules */
                        __( '%d advanced modules remain in preview-only mode', 'ultraguard-security-suite' ),
                        $locked_count
                    ),
                    __( 'Threat intelligence updates arrive with a delay on the free tier', 'ultraguard-security-suite' ),
                ],
                'class'    => 'info',
            ],
            'pro' => [
                'title'    => __( 'Pro', 'ultraguard-security-suite' ),
                'price'    => __( '$149 / year', 'ultraguard-security-suite' ),
                'subtitle' => __( 'Unlock the full premium scanning, monitoring, and response toolkit on one production site.', 'ultraguard-security-suite' ),
                'features' => [
                    __( 'File integrity scans, quarantine, restore, vulnerability scans, and database malware checks', 'ultraguard-security-suite' ),
                    __( 'Realtime intelligence, IP reputation, uptime monitoring, compliance reports, and WooCommerce security', 'ultraguard-security-suite' ),
                    __( 'Slack or webhook notifications, extended history, and deeper response tooling', 'ultraguard-security-suite' ),
                    __( 'Best fit for one serious business site or store that needs full-time protection', 'ultraguard-security-suite' ),
                ],
                'class'    => 'success',
                'badge'    => __( 'Most Popular', 'ultraguard-security-suite' ),
            ],
            'agency' => [
                'title'    => __( 'Agency', 'ultraguard-security-suite' ),
                'price'    => __( '$399 / year', 'ultraguard-security-suite' ),
                'subtitle' => __( 'Deploy the full Pro toolkit across client sites, multisite estates, or managed security portfolios.', 'ultraguard-security-suite' ),
                'features' => [
                    __( 'Everything in Pro', 'ultraguard-security-suite' ),
                    __( 'Cover up to 20 sites under one license', 'ultraguard-security-suite' ),
                    __( 'Ideal for agencies, freelancers, hosting teams, and security retainers', 'ultraguard-security-suite' ),
                    __( 'Standardize the same advanced protection stack across every managed install', 'ultraguard-security-suite' ),
                ],
                'class'    => 'warning',
            ],
        ];

        $items = [];

        foreach ( $plans as $plan_key => $plan ) {
            $list_items = [];

            foreach ( $plan['features'] as $feature ) {
                $list_items[] = [
                    'icon' => 'dashicons-yes-alt',
                    'text' => $feature,
                ];
            }

            $card_data = [
                [
                    'type'       => 'alert-box',
                    'alert_type' => $current_plan === $plan_key ? 'success' : 'info',
                    'title'      => $plan['price'],
                    'message'    => $plan['subtitle'],
                ],
                [
                    'type'  => 'list',
                    'items' => $list_items,
                ],
            ];

            if ( ! empty( $plan['badge'] ) ) {
                array_unshift(
                    $card_data,
                    [
                        'type'       => 'alert-box',
                        'alert_type' => 'success',
                        'title'      => (string) $plan['badge'],
                        'message'    => __( 'A strong fit for most single-site production installs.', 'ultraguard-security-suite' ),
                    ]
                );
            }

            $items[] = [
                'span'       => 4,
                'responsive' => [ 'lg' => 12 ],
                'component'  => [
                    'type'  => 'card',
                    'title' => $plan['title'],
                    'icon'  => 'dashicons-awards',
                    'class' => 'ultraguard-plan-card-' . $plan['class'],
                    'data'  => $card_data,
                ],
            ];
        }

        return $items;
    }

    protected function build_status_card( array $status ): array {
        $plan_key = $this->current_plan_key( $status );

        $message = __( 'You are currently in free mode. Activate a license key or move to a paid plan to unlock the advanced security modules listed below.', 'ultraguard-security-suite' );
        $type    = 'warning';

        if ( 'agency' === $plan_key && $status['is_valid'] ) {
            $message = __( 'Your Agency license is active. Premium security modules can be rolled out across up to 20 sites under the same plan.', 'ultraguard-security-suite' );
            $type    = 'success';
        } elseif ( 'pro' === $plan_key && $status['is_valid'] ) {
            $message = __( 'Your Pro license is active. This site can use the full premium security stack shown on this page.', 'ultraguard-security-suite' );
            $type    = 'success';
        } elseif ( ! empty( $status['license_key'] ) && ! $status['is_valid'] ) {
            $message = __( 'A license key is stored, but the last validation needs attention. Refresh or reactivate to restore premium entitlements.', 'ultraguard-security-suite' );
            $type    = 'warning';
        }

        return [
            'type'  => 'card',
            'title' => __( 'Current License Status', 'ultraguard-security-suite' ),
            'icon'  => 'dashicons-admin-network',
            'data'  => [
                [
                    'type'       => 'alert-box',
                    'alert_type' => $type,
                    'title'      => $this->status_badge( $status )['text'],
                    'message'    => $message,
                ],
                [
                    'type'       => 'data-table',
                    'id'         => 'ultraguard-upgrade-license-status',
                    'columns'    => [
                        'item'  => [ 'title' => __( 'Item', 'ultraguard-security-suite' ) ],
                        'value' => [ 'title' => __( 'Value', 'ultraguard-security-suite' ) ],
                    ],
                    'data'       => $this->plan_overview_rows( $status ),
                    'searchable' => false,
                    'pagination' => [ 'enabled' => false ],
                ],
            ],
        ];
    }

    protected function build_next_step_card( array $status ): array {
        $plan_key      = $this->current_plan_key( $status );
        $primary_label = __( 'Buy Pro License', 'ultraguard-security-suite' );
        $message       = __( 'Start with Pro to unlock the full premium security stack on one site. Move to Agency when you need the same protection across multiple installs or client environments.', 'ultraguard-security-suite' );
        $buttons       = [
            $this->create_url_button( $primary_label, $status['upgrade_url'], 'primary', 'dashicons-cart' ),
            $this->create_url_button( __( 'I already have a license key', 'ultraguard-security-suite' ), $this->get_page_url( 'upgrade-manager-free' ), 'secondary', 'dashicons-admin-network' ),
        ];

        if ( 'pro' === $plan_key && $status['is_valid'] ) {
            $message = __( 'You already have Pro on this site. Step up to Agency when you want to cover more installs, client projects, or managed security environments under one license.', 'ultraguard-security-suite' );
            $buttons = array_values( array_filter( [
                $this->create_url_button( __( 'See Agency Plan', 'ultraguard-security-suite' ), $status['upgrade_url'], 'primary', 'dashicons-chart-line' ),
                $status['manage_url'] ? $this->create_url_button( __( 'Manage Billing', 'ultraguard-security-suite' ), $status['manage_url'], 'secondary', 'dashicons-admin-links' ) : null,
            ] ) );
        } elseif ( 'agency' === $plan_key && $status['is_valid'] ) {
            $message = __( 'Agency already gives you the broadest UltraGuard rollout. Use billing to manage renewals and keep this dashboard as your entitlement reference.', 'ultraguard-security-suite' );
            $buttons = array_values( array_filter( [
                $status['manage_url'] ? $this->create_url_button( __( 'Open Billing Portal', 'ultraguard-security-suite' ), $status['manage_url'], 'primary', 'dashicons-admin-links' ) : null,
                $this->create_url_button( __( 'Review Subscription Details', 'ultraguard-security-suite' ), $this->get_page_url( 'upgrade-manager-paid' ), 'secondary', 'dashicons-visibility' ),
            ] ) );
        }

        return [
            'type'  => 'card',
            'title' => __( 'Next Step', 'ultraguard-security-suite' ),
            'icon'  => 'dashicons-arrow-right-alt',
            'data'  => [
                [
                    'type'       => 'alert-box',
                    'alert_type' => 'info',
                    'title'      => __( 'Choose the tier that matches your rollout', 'ultraguard-security-suite' ),
                    'message'    => $message,
                ],
                [
                    'type'  => 'list',
                    'items' => [
                        [
                            'icon' => 'dashicons-yes-alt',
                            'text' => __( 'Pro unlocks the complete advanced protection set on one production site.', 'ultraguard-security-suite' ),
                        ],
                        [
                            'icon' => 'dashicons-yes-alt',
                            'text' => __( 'Agency keeps the same premium toolkit and expands coverage up to 20 sites.', 'ultraguard-security-suite' ),
                        ],
                        [
                            'icon' => 'dashicons-yes-alt',
                            'text' => __( 'You can activate an existing key at any time without losing your configured data.', 'ultraguard-security-suite' ),
                        ],
                    ],
                ],
            ],
            'footer' => [
                'type'      => 'button-group',
                'alignment' => 'left',
                'buttons'   => $buttons,
            ],
        ];
    }

    protected function build_module_compare_rows(): array {
        $status = $this->license_status();
        $rows   = [];

        foreach ( $this->feature_modules() as $module ) {
            $required = (string) ( $module['license_required'] ?? 'free' );
            $included = ! empty( $module['license_ok'] );

            $rows[] = [
                'module'      => esc_html( (string) ( $module['name'] ?? $module['id'] ?? '' ) ),
                'group'       => esc_html( (string) ( $module['group'] ?? 'General' ) ),
                'free'        => [
                    'content' => [
                        'type'       => 'badge',
                        'content'    => 'pro' === $required ? __( 'Preview Only', 'ultraguard-security-suite' ) : __( 'Included', 'ultraguard-security-suite' ),
                        'badge_type' => 'pro' === $required ? 'warning' : 'success',
                    ],
                    'class'   => 'ultraguard-license-plan-cell',
                ],
                'pro'         => [
                    'content' => [
                        'type'       => 'badge',
                        'content'    => __( 'Included', 'ultraguard-security-suite' ),
                        'badge_type' => 'success',
                    ],
                    'class'   => 'ultraguard-license-plan-cell',
                ],
                'agency'      => [
                    'content' => [
                        'type'       => 'badge',
                        'content'    => 'pro' === $required ? __( 'Included (20 Sites)', 'ultraguard-security-suite' ) : __( 'Included', 'ultraguard-security-suite' ),
                        'badge_type' => 'success',
                    ],
                    'class'   => 'ultraguard-license-plan-cell',
                ],
                'description' => esc_html( (string) ( $module['description'] ?? '' ) ),
                'access'      => [
                    'content' => [
                        'type'       => 'badge',
                        'content'    => $included ? __( 'Available Now', 'ultraguard-security-suite' ) : ( $status['is_pro'] ? __( 'Needs Attention', 'ultraguard-security-suite' ) : __( 'Upgrade Required', 'ultraguard-security-suite' ) ),
                        'badge_type' => $included ? 'success' : ( $status['is_pro'] ? 'warning' : 'info' ),
                    ],
                    'class'   => $included
                        ? 'ultraguard-license-access-cell ultraguard-license-access-cell--available'
                        : 'ultraguard-license-access-cell ultraguard-license-access-cell--locked',
                ],
            ];
        }

        return $rows;
    }

    protected function build_feature_sections( array $status ): array {
        $features    = UpgradeManager::features();
        $module_meta = $this->feature_modules();
        $plan_key    = $this->current_plan_key( $status );
        $groups      = [];

        foreach ( $features as $feature_key => $feature ) {
            $module = (string) ( $feature['module'] ?? 'general' );
            if ( ! isset( $groups[ $module ] ) ) {
                $groups[ $module ] = [];
            }

            $groups[ $module ][ $feature_key ] = $feature;
        }

        $sections = [];

        foreach ( $groups as $module => $module_features ) {
            $module_name = $this->feature_section_title( $module, $module_features, $module_meta );
            $module_icon = $this->feature_section_icon( $module, $module_features, $module_meta );
            $items       = [];

            foreach ( $module_features as $feature_key => $feature ) {
                $benefits   = [];
                $plans      = $this->feature_plan_keys( $feature );
                $has_pro    = in_array( 'pro', $plans, true );
                $has_agency = in_array( 'agency', $plans, true );

                foreach ( (array) ( $feature['benefits'] ?? [] ) as $benefit ) {
                    $benefits[] = [
                        'icon' => 'dashicons-yes-alt',
                        'text' => (string) $benefit,
                    ];
                }

                if ( $has_pro && $has_agency ) {
                    $tier_alert = [
                        'type'       => 'alert-box',
                        'alert_type' => 'info',
                        'title'      => __( 'Included in Pro and Agency', 'ultraguard-security-suite' ),
                        'message'    => __( 'Unlock this on a single production site with Pro, or roll it out across up to 20 sites with Agency.', 'ultraguard-security-suite' ),
                    ];
                } elseif ( $has_agency ) {
                    $tier_alert = [
                        'type'       => 'alert-box',
                        'alert_type' => 'info',
                        'title'      => __( 'Included in Agency only', 'ultraguard-security-suite' ),
                        'message'    => __( 'This capability is reserved for broader multi-site or agency-style security rollouts.', 'ultraguard-security-suite' ),
                    ];
                } else {
                    $tier_alert = [
                        'type'       => 'alert-box',
                        'alert_type' => 'info',
                        'title'      => __( 'Included in Pro', 'ultraguard-security-suite' ),
                        'message'    => __( 'Unlock this with Pro on a single site and keep it when you move into a larger rollout.', 'ultraguard-security-suite' ),
                    ];
                }

                if ( 'pro' === $plan_key && $has_pro ) {
                    $tier_alert = [
                        'type'       => 'alert-box',
                        'alert_type' => 'success',
                        'title'      => __( 'Included in your current Pro plan', 'ultraguard-security-suite' ),
                        'message'    => __( 'This premium capability is already available on this site. Move to Agency only if you need broader site coverage.', 'ultraguard-security-suite' ),
                    ];
                } elseif ( 'pro' === $plan_key && $has_agency && ! $has_pro ) {
                    $tier_alert = [
                        'type'       => 'alert-box',
                        'alert_type' => 'warning',
                        'title'      => __( 'Upgrade to Agency to unlock this', 'ultraguard-security-suite' ),
                        'message'    => __( 'Your current Pro plan includes the premium toolkit, but this capability is reserved for larger site portfolios or agency-style deployments.', 'ultraguard-security-suite' ),
                    ];
                } elseif ( 'agency' === $plan_key ) {
                    $tier_alert = [
                        'type'       => 'alert-box',
                        'alert_type' => 'success',
                        'title'      => __( 'Included in your current Agency plan', 'ultraguard-security-suite' ),
                        'message'    => $has_agency
                            ? __( 'This capability is already unlocked and can be used across up to 20 licensed sites.', 'ultraguard-security-suite' )
                            : __( 'This capability is already unlocked as part of your current paid entitlement.', 'ultraguard-security-suite' ),
                    ];
                }

                $items[] = [
                    'span'       => 4,
                    'responsive' => [ 'lg' => 6, 'sm' => 12 ],
                    'component'  => [
                        'type'  => 'card',
                        'title' => (string) ( $feature['label'] ?? $feature_key ),
                        'icon'  => (string) ( $feature['icon'] ?? 'dashicons-lock' ),
                        'data'  => [
                            [
                                'type'       => 'alert-box',
                                'alert_type' => 'info',
                                'title'      => (string) ( $feature['headline'] ?? '' ),
                                'message'    => (string) ( $feature['description'] ?? '' ),
                            ],
                            [
                                'type'  => 'list',
                                'items' => $benefits,
                            ],
                            $tier_alert,
                        ],
                    ],
                ];
            }

            $sections[] = [
                'type'  => 'card',
                'title' => sprintf(
                    /* translators: %s: module name */
                    __( '%s Premium Features', 'ultraguard-security-suite' ),
                    $module_name
                ),
                'icon'  => $module_icon,
                'data'  => [
                    [
                        'type'       => 'alert-box',
                        'alert_type' => 'info',
                        'title'      => sprintf(
                            /* translators: %s: module name */
                            __( 'What %s adds to your protection stack', 'ultraguard-security-suite' ),
                            $module_name
                        ),
                        'message'    => __( 'Each card below explains the protection or response outcome you unlock, not just the module name. This makes it easier to match the upgrade with your real-world security needs.', 'ultraguard-security-suite' ),
                    ],
                    [
                        'type'    => 'grid',
                        'columns' => 12,
                        'gap'     => '16px',
                        'items'   => $items,
                    ],
                ],
            ];
        }

        return $sections;
    }

    protected function format_date_value( string $value ): string {
        if ( '' === trim( $value ) ) {
            return '';
        }

        $timestamp = strtotime( $value );
        if ( false === $timestamp ) {
            return $value;
        }

        return wp_date(
            (string) get_option( 'date_format', 'Y-m-d' ) . ' ' . (string) get_option( 'time_format', 'g:i a' ),
            $timestamp
        );
    }

    protected function benefit_cards( array $modules, string $button_text ): array {
        $items = [];
        $count = 0;

        foreach ( $modules as $module ) {
            $items[] = [
                'span'       => 4,
                'responsive' => [ 'md' => 6, 'sm' => 12 ],
                'component'  => [
                    'type'  => 'card',
                    'title' => esc_html( (string) ( $module['name'] ?? $module['id'] ?? '' ) ),
                    'icon'  => (string) ( $module['icon'] ?? 'dashicons-awards' ),
                    'data'  => [
                        [
                            'type'       => 'alert-box',
                            'alert_type' => 'info',
                            'title'      => esc_html( (string) ( $module['group'] ?? __( 'Feature', 'ultraguard-security-suite' ) ) ),
                            'message'    => esc_html( (string) ( $module['description'] ?? '' ) ),
                        ],
                        [
                            'type'    => 'button-group',
                            'buttons' => [
                                $this->create_url_button( $button_text, $this->license_status()['upgrade_url'], 'primary', 'dashicons-external' ),
                            ],
                        ],
                    ],
                ],
            ];
            $count++;
            if ( $count >= 6 ) {
                break;
            }
        }

        return $items;
    }

    protected function agency_upsell_cards(): array {
        $cards = [
            [
                'title'       => __( 'Protect Up To 20 Sites', 'ultraguard-security-suite' ),
                'icon'        => 'dashicons-admin-multisite',
                'headline'    => __( 'Turn one proven Pro setup into a portfolio-wide security standard.', 'ultraguard-security-suite' ),
                'description' => __( 'Agency expands the same premium UltraGuard stack you already trust on this site across up to 20 installs, so you do not need to buy and track separate licenses one by one.', 'ultraguard-security-suite' ),
                'benefits'    => [
                    __( 'One subscription for client sites, staging stacks, or managed portfolios', 'ultraguard-security-suite' ),
                    __( 'Simpler renewals and easier entitlement management', 'ultraguard-security-suite' ),
                    __( 'Ideal when you maintain multiple WordPress environments', 'ultraguard-security-suite' ),
                ],
            ],
            [
                'title'       => __( 'Standardize Every Rollout', 'ultraguard-security-suite' ),
                'icon'        => 'dashicons-shield-alt',
                'headline'    => __( 'Keep the same premium protection baseline everywhere you deploy.', 'ultraguard-security-suite' ),
                'description' => __( 'Agency helps teams repeat the same hardened UltraGuard playbook across stores, marketing sites, client projects, and multisite estates without feature compromises.', 'ultraguard-security-suite' ),
                'benefits'    => [
                    __( 'Use the same advanced scanning, monitoring, and response workflow on every site', 'ultraguard-security-suite' ),
                    __( 'Reduce missed modules and inconsistent client security setups', 'ultraguard-security-suite' ),
                    __( 'Scale faster when onboarding new installs', 'ultraguard-security-suite' ),
                ],
            ],
            [
                'title'       => __( 'Grow Without Reworking Licensing', 'ultraguard-security-suite' ),
                'icon'        => 'dashicons-chart-line',
                'headline'    => __( 'Upgrade once now instead of re-solving licensing every time you add another site.', 'ultraguard-security-suite' ),
                'description' => __( 'If you are already seeing value from Pro, Agency gives you room to add more protected installs immediately while keeping the same premium experience for every project you manage.', 'ultraguard-security-suite' ),
                'benefits'    => [
                    __( 'Support new client launches without waiting on another purchase decision', 'ultraguard-security-suite' ),
                    __( 'Keep Agency ready for incident response across multiple properties', 'ultraguard-security-suite' ),
                    __( 'A cleaner path for freelancers, agencies, and hosting teams', 'ultraguard-security-suite' ),
                ],
            ],
        ];

        $items = [];

        foreach ( $cards as $card ) {
            $benefits = [];

            foreach ( $card['benefits'] as $benefit ) {
                $benefits[] = [
                    'icon' => 'dashicons-yes-alt',
                    'text' => $benefit,
                ];
            }

            $items[] = [
                'span'       => 4,
                'responsive' => [ 'md' => 6, 'sm' => 12 ],
                'component'  => [
                    'type'   => 'card',
                    'title'  => $card['title'],
                    'icon'   => $card['icon'],
                    'data'   => [
                        [
                            'type'       => 'alert-box',
                            'alert_type' => 'info',
                            'title'      => $card['headline'],
                            'message'    => $card['description'],
                        ],
                        [
                            'type'  => 'list',
                            'items' => $benefits,
                        ],
                    ],
                    'footer' => [
                        'type'      => 'button-group',
                        'alignment' => 'left',
                        'buttons'   => [
                            $this->create_url_button( __( 'Upgrade To Agency', 'ultraguard-security-suite' ), $this->license_status()['upgrade_url'], 'primary', 'dashicons-chart-line' ),
                        ],
                    ],
                ],
            ];
        }

        return $items;
    }

    protected function agency_upsell_summary_card(): array {
        return [
            'type'  => 'card',
            'title' => __( 'Why Move From Pro To Agency', 'ultraguard-security-suite' ),
            'icon'  => 'dashicons-groups',
            'data'  => [
                [
                    'type'       => 'alert-box',
                    'alert_type' => 'info',
                    'title'      => __( 'Agency keeps the premium stack you already use and scales the license around it.', 'ultraguard-security-suite' ),
                    'message'    => __( 'This is the right next step when UltraGuard is working well on one site and you want the same advanced coverage across more projects, clients, or managed WordPress properties.', 'ultraguard-security-suite' ),
                ],
                [
                    'type'  => 'list',
                    'items' => [
                        [
                            'icon' => 'dashicons-yes-alt',
                            'text' => __( 'Cover up to 20 sites under one plan.', 'ultraguard-security-suite' ),
                        ],
                        [
                            'icon' => 'dashicons-yes-alt',
                            'text' => __( 'Keep the same Pro-grade modules and operational workflow everywhere.', 'ultraguard-security-suite' ),
                        ],
                        [
                            'icon' => 'dashicons-yes-alt',
                            'text' => __( 'Reduce per-site purchasing friction when your portfolio grows.', 'ultraguard-security-suite' ),
                        ],
                    ],
                ],
            ],
            'footer' => [
                'type'      => 'button-group',
                'alignment' => 'left',
                'buttons'   => [
                    $this->create_url_button( __( 'See Agency Pricing', 'ultraguard-security-suite' ), $this->license_status()['upgrade_url'], 'primary', 'dashicons-external' ),
                ],
            ],
        ];
    }
}
