<?php

// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedNamespaceFound -- APD is the established namespace shared with the Pro add-on and retained for backward compatibility.
namespace APD\Admin;

defined('ABSPATH') || exit;

class DashboardPage
{
    public function render() : void
    {
        if (! current_user_can('manage_asuka_designer')) {
            wp_die(esc_html__('You are not allowed to access this page.', 'asuka-product-designer'));
        }

        $overview = AdminOverview::snapshot();
        $settings = $overview['settings'];
        $steps = $this->setupSteps($overview);
        $completedSteps = count(array_filter($steps, static fn(array $step) : bool => $step['complete']));
        $nextStep = null;
        foreach ($steps as $step) {
            if (! $step['complete']) {
                $nextStep = $step;
                break;
            }
        }

        $license = $overview['license'];
        $licensePlan = $license['active']
            ? ucfirst((string) $license['plan'])
            : ($license['configured'] ? __('Action required', 'asuka-product-designer') : __('Not connected', 'asuka-product-designer'));
        $licenseState = $license['active'] ? 'ready' : 'warning';
        $wooState = $overview['woocommerce']['active'] ? 'ready' : 'warning';
        $theme = sanitize_html_class((string) ($settings['admin_theme'] ?? 'light'));
        ?>
        <div class="wrap apd-admin-shell apd-admin-theme-<?php echo esc_attr($theme); ?> apd-dashboard">
            <header class="apd-dashboard-header">
                <div class="apd-dashboard-header__copy">
                    <div class="apd-dashboard-identity">
                        <img src="<?php echo esc_url(ASUKA_PRODUCT_DESIGNER_ASSETS_URL . 'images/brand/asuka-designer-app-icon.svg?ver=soft-2'); ?>" alt="" aria-hidden="true">
                        <span class="apd-dashboard-eyebrow"><?php esc_html_e('Store workspace', 'asuka-product-designer'); ?></span>
                    </div>
                    <h1><?php esc_html_e('Asuka Product Designer', 'asuka-product-designer'); ?></h1>
                    <p><?php esc_html_e('Manage product configuration, storefront readiness, licensing, and production from one operational overview.', 'asuka-product-designer'); ?></p>
                    <div class="apd-dashboard-actions">
                        <a class="button button-primary" href="<?php echo esc_url(admin_url('post-new.php?post_type=apd_product_config')); ?>">
                            <?php esc_html_e('Create product config', 'asuka-product-designer'); ?>
                        </a>
                        <?php if (! empty($overview['bindings']['firstProductUrl'])) : ?>
                            <a class="button button-secondary" href="<?php echo esc_url((string) $overview['bindings']['firstProductUrl']); ?>" target="_blank" rel="noreferrer">
                                <?php esc_html_e('Open storefront test', 'asuka-product-designer'); ?>
                            </a>
                        <?php else : ?>
                            <a class="button button-secondary" href="<?php echo esc_url(admin_url('edit.php?post_type=product')); ?>">
                                <?php esc_html_e('Open WooCommerce products', 'asuka-product-designer'); ?>
                            </a>
                        <?php endif; ?>
                        <a class="button button-secondary" href="<?php echo esc_url(admin_url('admin.php?page=apd-support')); ?>">
                            <?php esc_html_e('Support center', 'asuka-product-designer'); ?>
                        </a>
                    </div>
                </div>

                <div class="apd-setup-summary">
                    <div class="apd-setup-summary__top">
                        <div>
                            <span><?php esc_html_e('Setup progress', 'asuka-product-designer'); ?></span>
                            <strong><?php echo esc_html(sprintf(/* translators: Placeholder values are populated from the current administration record. */ __('%1$d of %2$d complete', 'asuka-product-designer'), $completedSteps, count($steps))); ?></strong>
                        </div>
                        <span class="apd-setup-summary__percent"><?php echo esc_html((string) (int) round(($completedSteps / max(1, count($steps))) * 100)); ?>%</span>
                    </div>
                    <progress class="apd-progress" max="<?php echo esc_attr((string) count($steps)); ?>" value="<?php echo esc_attr((string) $completedSteps); ?>">
                        <?php echo esc_html((string) $completedSteps); ?>
                    </progress>
                    <?php if (is_array($nextStep)) : ?>
                        <p><?php echo esc_html(sprintf(/* translators: Placeholder values are populated from the current administration record. */ __('Next: %s', 'asuka-product-designer'), $nextStep['title'])); ?></p>
                        <a href="<?php echo esc_url($nextStep['url']); ?>"><?php echo esc_html($nextStep['action']); ?> <span aria-hidden="true">&rarr;</span></a>
                    <?php else : ?>
                        <p><?php esc_html_e('The essential storefront workflow is connected.', 'asuka-product-designer'); ?></p>
                        <a href="<?php echo esc_url(admin_url('admin.php?page=apd-production')); ?>"><?php esc_html_e('Open production', 'asuka-product-designer'); ?> <span aria-hidden="true">&rarr;</span></a>
                    <?php endif; ?>
                </div>
            </header>

            <?php $this->renderPriorityNotice($overview); ?>

            <section class="apd-dashboard-metrics" aria-label="<?php echo esc_attr__('Store status', 'asuka-product-designer'); ?>">
                <?php
                $this->renderMetric(
                    __('License', 'asuka-product-designer'),
                    $licensePlan,
                    $license['active']
                        ? sprintf(/* translators: Placeholder values are populated from the current administration record. */ _n('%d licensed feature', '%d licensed features', (int) $license['featureCount'], 'asuka-product-designer'), (int) $license['featureCount'])
                        : __('Open settings to restore premium access.', 'asuka-product-designer'),
                    $licenseState,
                    admin_url('admin.php?page=apd-settings')
                );
                $this->renderMetric(
                    __('WooCommerce', 'asuka-product-designer'),
                    $overview['woocommerce']['active'] ? __('Ready', 'asuka-product-designer') : __('Unavailable', 'asuka-product-designer'),
                    $overview['woocommerce']['active']
                        ? __('Product, cart, checkout, and order hooks are active.', 'asuka-product-designer')
                        : __('Activate WooCommerce before testing a storefront flow.', 'asuka-product-designer'),
                    $wooState,
                    admin_url('plugins.php')
                );
                $this->renderMetric(
                    __('Product configs', 'asuka-product-designer'),
                    (string) $overview['configs']['total'],
                    sprintf(
                        /* translators: Placeholder values are populated from the current administration record. */ __('%1$d published, %2$d draft', 'asuka-product-designer'),
                        (int) $overview['configs']['published'],
                        (int) $overview['configs']['draft']
                    ),
                    $overview['configs']['total'] > 0 ? 'ready' : 'neutral',
                    admin_url('edit.php?post_type=apd_product_config')
                );
                $this->renderMetric(
                    __('Production queue', 'asuka-product-designer'),
                    (string) $overview['production']['pending'],
                    sprintf(
                        /* translators: Placeholder values are populated from the current administration record. */ _n('%d customized item received', '%d customized items received', (int) $overview['production']['total'], 'asuka-product-designer'),
                        (int) $overview['production']['total']
                    ),
                    $overview['production']['pending'] > 0 ? 'attention' : 'neutral',
                    admin_url('admin.php?page=apd-production')
                );
                ?>
            </section>

            <div class="apd-dashboard-grid">
                <section class="apd-dashboard-card apd-dashboard-card--setup">
                    <div class="apd-dashboard-card__head">
                        <div>
                            <span class="apd-dashboard-kicker"><?php esc_html_e('Getting started', 'asuka-product-designer'); ?></span>
                            <h2><?php esc_html_e('Launch checklist', 'asuka-product-designer'); ?></h2>
                        </div>
                        <span class="apd-dashboard-count"><?php echo esc_html($completedSteps . '/' . count($steps)); ?></span>
                    </div>
                    <div class="apd-checklist">
                        <?php foreach ($steps as $index => $step) : ?>
                            <a class="apd-checklist__item<?php echo $step['complete'] ? ' is-complete' : ''; ?>" href="<?php echo esc_url($step['url']); ?>">
                                <span class="apd-checklist__status" aria-hidden="true"><?php echo $step['complete'] ? '&#10003;' : esc_html((string) ($index + 1)); ?></span>
                                <span class="apd-checklist__copy">
                                    <strong><?php echo esc_html($step['title']); ?></strong>
                                    <small><?php echo esc_html($step['copy']); ?></small>
                                </span>
                                <span class="apd-checklist__action"><?php echo esc_html($step['action']); ?> <span aria-hidden="true">&rarr;</span></span>
                            </a>
                        <?php endforeach; ?>
                    </div>
                </section>

                <section class="apd-dashboard-card">
                    <div class="apd-dashboard-card__head">
                        <div>
                            <span class="apd-dashboard-kicker"><?php esc_html_e('Connection health', 'asuka-product-designer'); ?></span>
                            <h2><?php esc_html_e('Runtime status', 'asuka-product-designer'); ?></h2>
                        </div>
                        <a class="apd-text-link" href="<?php echo esc_url(admin_url('admin.php?page=apd-qa-diagnostics')); ?>"><?php esc_html_e('Diagnostics', 'asuka-product-designer'); ?></a>
                    </div>
                    <dl class="apd-status-list">
                        <?php
                        $this->renderStatusRow(
                            __('License runtime', 'asuka-product-designer'),
                            $license['active'] ? __('Connected', 'asuka-product-designer') : __('Needs attention', 'asuka-product-designer'),
                            $licenseState
                        );
                        $this->renderStatusRow(
                            __('Licensed domain', 'asuka-product-designer'),
                            $license['domain'] !== '' ? (string) $license['domain'] : __('Automatic', 'asuka-product-designer'),
                            $license['active'] ? 'ready' : 'neutral'
                        );
                        $this->renderStatusRow(
                            __('Plugin runtime', 'asuka-product-designer'),
                            'v' . (string) $overview['pluginVersion'],
                            'ready'
                        );
                        $this->renderStatusRow(
                            __('Designer runtime', 'asuka-product-designer'),
                            'v' . (string) $overview['designerVersion'],
                            $overview['pluginVersion'] === $overview['designerVersion'] ? 'ready' : 'warning'
                        );
                        ?>
                    </dl>
                    <div class="apd-dashboard-card__actions">
                        <a class="button button-secondary" href="<?php echo esc_url(admin_url('admin.php?page=apd-settings')); ?>"><?php esc_html_e('Settings', 'asuka-product-designer'); ?></a>
                        <a class="button button-secondary" href="<?php echo esc_url(admin_url('admin.php?page=apd-tools')); ?>"><?php esc_html_e('Import and export', 'asuka-product-designer'); ?></a>
                    </div>
                </section>

                <section class="apd-dashboard-card">
                    <div class="apd-dashboard-card__head">
                        <div>
                            <span class="apd-dashboard-kicker"><?php esc_html_e('Product workspace', 'asuka-product-designer'); ?></span>
                            <h2><?php esc_html_e('Recent configurations', 'asuka-product-designer'); ?></h2>
                        </div>
                        <a class="apd-text-link" href="<?php echo esc_url(admin_url('edit.php?post_type=apd_product_config')); ?>"><?php esc_html_e('View all', 'asuka-product-designer'); ?></a>
                    </div>
                    <?php if (! empty($overview['configs']['recent'])) : ?>
                        <div class="apd-dashboard-list">
                            <?php foreach ($overview['configs']['recent'] as $config) : ?>
                                <a href="<?php echo esc_url(admin_url('post.php?post=' . (int) $config['id'] . '&action=edit')); ?>">
                                    <span>
                                        <strong><?php echo esc_html((string) $config['title']); ?></strong>
                                        <small><?php echo esc_html(sprintf(/* translators: Placeholder values are populated from the current administration record. */ __('Config #%d', 'asuka-product-designer'), (int) $config['id'])); ?></small>
                                    </span>
                                    <span aria-hidden="true">&rarr;</span>
                                </a>
                            <?php endforeach; ?>
                        </div>
                    <?php else : ?>
                        <div class="apd-dashboard-empty">
                            <strong><?php esc_html_e('No product configuration yet', 'asuka-product-designer'); ?></strong>
                            <p><?php esc_html_e('Create the first configuration to define views, modules, catalogs, and product behavior.', 'asuka-product-designer'); ?></p>
                            <a class="button button-primary" href="<?php echo esc_url(admin_url('post-new.php?post_type=apd_product_config')); ?>"><?php esc_html_e('Create config', 'asuka-product-designer'); ?></a>
                        </div>
                    <?php endif; ?>
                </section>

                <section class="apd-dashboard-card">
                    <div class="apd-dashboard-card__head">
                        <div>
                            <span class="apd-dashboard-kicker"><?php esc_html_e('Daily work', 'asuka-product-designer'); ?></span>
                            <h2><?php esc_html_e('Quick access', 'asuka-product-designer'); ?></h2>
                        </div>
                    </div>
                    <nav class="apd-quick-links" aria-label="<?php echo esc_attr__('Asuka Designer workspaces', 'asuka-product-designer'); ?>">
                        <a href="<?php echo esc_url(admin_url('admin.php?page=apd-assets')); ?>"><span class="dashicons dashicons-images-alt2" aria-hidden="true"></span><span><strong><?php esc_html_e('Asset library', 'asuka-product-designer'); ?></strong><small><?php esc_html_e('Designs, fonts, colors, and shapes', 'asuka-product-designer'); ?></small></span></a>
                        <a href="<?php echo esc_url(admin_url('admin.php?page=apd-commerce')); ?>"><span class="dashicons dashicons-cart" aria-hidden="true"></span><span><strong><?php esc_html_e('Commerce', 'asuka-product-designer'); ?></strong><small><?php esc_html_e('Pricing, saved designs, and production', 'asuka-product-designer'); ?></small></span></a>
                        <a href="<?php echo esc_url(admin_url('admin.php?page=apd-translations')); ?>"><span class="dashicons dashicons-translation" aria-hidden="true"></span><span><strong><?php esc_html_e('Translations', 'asuka-product-designer'); ?></strong><small><?php esc_html_e('Manage editor copy by locale', 'asuka-product-designer'); ?></small></span></a>
                        <a href="<?php echo esc_url(admin_url('admin.php?page=apd-qa-diagnostics')); ?>"><span class="dashicons dashicons-shield-alt" aria-hidden="true"></span><span><strong><?php esc_html_e('QA and diagnostics', 'asuka-product-designer'); ?></strong><small><?php esc_html_e('Validate runtime, REST, and WooCommerce health', 'asuka-product-designer'); ?></small></span></a>
                    </nav>
                </section>
            </div>
        </div>
        <?php
    }

    private function setupSteps(array $overview) : array
    {
        $firstProductUrl = (string) ($overview['bindings']['firstProductUrl'] ?? '');
        $storefrontTestUrl = $firstProductUrl !== '' ? $firstProductUrl : admin_url('edit.php?post_type=product');

        return [
            [
                'title' => __('Connect an active license', 'asuka-product-designer'),
                'copy' => __('Resolve the server-side license and premium entitlements.', 'asuka-product-designer'),
                'complete' => ! empty($overview['license']['active']),
                'url' => admin_url('admin.php?page=apd-settings'),
                'action' => __('License settings', 'asuka-product-designer'),
            ],
            [
                'title' => __('Enable WooCommerce', 'asuka-product-designer'),
                'copy' => __('Provide product, cart, checkout, and order infrastructure.', 'asuka-product-designer'),
                'complete' => ! empty($overview['woocommerce']['active']),
                'url' => admin_url('plugins.php'),
                'action' => __('Manage plugins', 'asuka-product-designer'),
            ],
            [
                'title' => __('Create a product configuration', 'asuka-product-designer'),
                'copy' => __('Define the designer views, modules, catalogs, and behavior.', 'asuka-product-designer'),
                'complete' => (int) ($overview['configs']['total'] ?? 0) > 0,
                'url' => admin_url('post-new.php?post_type=apd_product_config'),
                'action' => __('Create config', 'asuka-product-designer'),
            ],
            [
                'title' => __('Bind a WooCommerce product', 'asuka-product-designer'),
                'copy' => __('Attach a configuration to a product or variation.', 'asuka-product-designer'),
                'complete' => (int) ($overview['bindings']['count'] ?? 0) > 0,
                'url' => admin_url('edit.php?post_type=product'),
                'action' => __('Open products', 'asuka-product-designer'),
            ],
            [
                'title' => __('Complete a storefront test order', 'asuka-product-designer'),
                'copy' => __('Validate customization, pricing, cart restoration, and production data.', 'asuka-product-designer'),
                'complete' => (int) ($overview['production']['total'] ?? 0) > 0,
                'url' => $storefrontTestUrl,
                'action' => __('Run test flow', 'asuka-product-designer'),
            ],
        ];
    }

    private function renderPriorityNotice(array $overview) : void
    {
        if (empty($overview['license']['active'])) {
            echo '<div class="apd-dashboard-notice is-warning"><span class="dashicons dashicons-warning" aria-hidden="true"></span><div><strong>' . esc_html__('Premium runtime is not connected', 'asuka-product-designer') . '</strong><p>' . esc_html__('The core plugin remains available, but licensed modules stay hidden until the license resolves successfully.', 'asuka-product-designer') . '</p></div><a href="' . esc_url(admin_url('admin.php?page=apd-settings')) . '">' . esc_html__('Review license', 'asuka-product-designer') . '</a></div>';
            return;
        }

        if (empty($overview['woocommerce']['active'])) {
            echo '<div class="apd-dashboard-notice is-warning"><span class="dashicons dashicons-warning" aria-hidden="true"></span><div><strong>' . esc_html__('WooCommerce is not active', 'asuka-product-designer') . '</strong><p>' . esc_html__('Activate WooCommerce to enable product binding, cart validation, checkout, and production orders.', 'asuka-product-designer') . '</p></div><a href="' . esc_url(admin_url('plugins.php')) . '">' . esc_html__('Manage plugins', 'asuka-product-designer') . '</a></div>';
            return;
        }

        if ((int) ($overview['bindings']['count'] ?? 0) === 0) {
            echo '<div class="apd-dashboard-notice is-info"><span class="dashicons dashicons-info-outline" aria-hidden="true"></span><div><strong>' . esc_html__('No storefront product is connected yet', 'asuka-product-designer') . '</strong><p>' . esc_html__('Bind a product configuration from the Custom product tab in WooCommerce.', 'asuka-product-designer') . '</p></div><a href="' . esc_url(admin_url('edit.php?post_type=product')) . '">' . esc_html__('Open products', 'asuka-product-designer') . '</a></div>';
        }
    }

    private function renderMetric(string $label, string $value, string $copy, string $state, string $url) : void
    {
        ?>
        <a class="apd-dashboard-metric is-<?php echo esc_attr($state); ?>" href="<?php echo esc_url($url); ?>">
            <span class="apd-dashboard-metric__label"><?php echo esc_html($label); ?></span>
            <strong><?php echo esc_html($value); ?></strong>
            <small><?php echo esc_html($copy); ?></small>
            <span class="apd-dashboard-metric__arrow" aria-hidden="true">&rarr;</span>
        </a>
        <?php
    }

    private function renderStatusRow(string $label, string $value, string $state) : void
    {
        ?>
        <div>
            <dt><?php echo esc_html($label); ?></dt>
            <dd><span class="apd-status-dot is-<?php echo esc_attr($state); ?>" aria-hidden="true"></span><?php echo esc_html($value); ?></dd>
        </div>
        <?php
    }
}
