<?php

namespace GriffinForms\Admin\Html\Pages;

class Pro extends \GriffinForms\Admin\Html\Pages\Format
{
    protected $package_state_resolver;

    protected function setPackageStateResolver()
    {
        $this->package_state_resolver = \GriffinForms\Includes\Packages\PackageStateResolver::getInstance();
    }

    public function html()
    {
        $state = $this->package_state_resolver->getState();
        $pro_state = is_array($state['packages']['pro'] ?? null) ? $state['packages']['pro'] : [];
        $diagnostics_url = admin_url('admin.php?page=' . $this->config::PREFIX . '-diagnostics');
        $libraries_url = admin_url('admin.php?page=' . $this->config::PREFIX . '-libraries');
        $status_model = $this->buildStatusModel($pro_state);
        $surface_model = $this->buildLibrariesSurfaceModel($pro_state);

        echo '<div class="wrap gf-pro-page-wrap">';
        $this->pageHeading(__('GriffinForms Pro', 'griffinforms-form-builder'), __('Internal package preview', 'griffinforms-form-builder'));

        echo '<div class="card" style="max-width:1040px;">';
        echo '<div class="card-body">';
        echo '<p class="mb-4 text-muted">' . esc_html__('This internal page reflects the current normalized Pro package state from Core. It exists to support package-foundation testing before any public Pro launch.', 'griffinforms-form-builder') . '</p>';
        echo '<div class="gf-pro-status-hero" style="padding:20px 22px;border:1px solid #dbe4f0;border-radius:16px;background:linear-gradient(135deg,#f8fbff 0%,#eef5ff 100%);margin-bottom:20px;">';
        echo '<div style="display:flex;flex-wrap:wrap;align-items:flex-start;justify-content:space-between;gap:16px;">';
        echo '<div style="flex:1 1 560px;min-width:280px;">';
        echo '<div style="display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-bottom:10px;">';
        echo wp_kses_post($this->getProBadgeHtml('light'));
        echo '<span style="display:inline-flex;align-items:center;border-radius:999px;padding:6px 12px;background:#111827;color:#fff;font-size:12px;font-weight:600;letter-spacing:.02em;text-transform:uppercase;">' . esc_html($status_model['badge']) . '</span>';
        echo '<span style="display:inline-flex;align-items:center;border-radius:999px;padding:6px 12px;background:#dbeafe;color:#1e3a8a;font-size:12px;font-weight:600;">' . esc_html(sprintf(__('Version %s', 'griffinforms-form-builder'), $this->formatValue((string) ($pro_state['package_version'] ?? '')))) . '</span>';
        echo '</div>';
        echo '<h2 style="margin:0 0 8px 0;font-size:24px;line-height:1.2;">' . esc_html($status_model['title']) . '</h2>';
        echo '<p style="margin:0 0 12px 0;color:#475569;max-width:760px;">' . esc_html($status_model['message']) . '</p>';
        echo '<p style="margin:0;color:#0f172a;"><strong>' . esc_html__('Next action:', 'griffinforms-form-builder') . '</strong> ' . esc_html($status_model['action_text']) . '</p>';
        echo '</div>';
        echo '<div style="display:flex;gap:10px;align-items:center;flex-wrap:wrap;">';
        echo '<a class="button button-secondary" href="' . esc_url($libraries_url) . '">' . esc_html__('Open Libraries Catalog', 'griffinforms-form-builder') . '</a>';
        echo '<a class="button button-secondary" href="' . esc_url($diagnostics_url) . '">' . esc_html__('Open Package Diagnostics', 'griffinforms-form-builder') . '</a>';
        echo '</div>';
        echo '</div>';
        echo '</div>';

        echo '<div style="padding:18px;border:1px solid #e5e7eb;border-radius:14px;background:#fff;margin-bottom:20px;">';
        echo '<h3 style="margin:0 0 12px 0;font-size:16px;">' . esc_html__('Package-Aware Surface Preview', 'griffinforms-form-builder') . '</h3>';
        echo '<div style="display:flex;flex-wrap:wrap;gap:16px;">';
        echo '<div style="flex:1 1 340px;min-width:280px;padding:16px;border:1px solid #e5e7eb;border-radius:12px;background:#f8fafc;">';
        echo '<div style="display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin-bottom:10px;">';
        echo wp_kses_post($this->getProBadgeHtml('light'));
        echo '<span style="display:inline-flex;align-items:center;border-radius:999px;padding:4px 10px;background:#111827;color:#fff;font-size:11px;font-weight:600;letter-spacing:.02em;text-transform:uppercase;">' . esc_html($surface_model['badge']) . '</span>';
        echo '</div>';
        echo '<h4 style="margin:0 0 8px 0;font-size:15px;">' . esc_html__('Libraries Catalog Surface', 'griffinforms-form-builder') . '</h4>';
        echo '<p style="margin:0 0 8px 0;color:#475569;">' . esc_html($surface_model['message']) . '</p>';
        echo '<p style="margin:0 0 12px 0;"><strong>' . esc_html__('Current mode:', 'griffinforms-form-builder') . '</strong> ' . esc_html($surface_model['mode_label']) . '</p>';
        echo '<a class="button button-secondary" href="' . esc_url($libraries_url) . '">' . esc_html__('Inspect Libraries Surface', 'griffinforms-form-builder') . '</a>';
        echo '</div>';
        echo '</div>';
        echo '</div>';

        echo '<div class="row" style="margin-bottom:20px;">';
        echo '<div class="col-lg-6" style="margin-bottom:16px;">';
        echo '<div style="padding:18px;border:1px solid #e5e7eb;border-radius:14px;background:#fff;height:100%;">';
        echo '<h3 style="margin:0 0 12px 0;font-size:16px;">' . esc_html__('Availability', 'griffinforms-form-builder') . '</h3>';
        echo '<table class="widefat striped" style="margin:0;">';
        echo '<tbody>';
        $this->tableRowHtml(__('Present', 'griffinforms-form-builder'), !empty($pro_state['is_present']) ? __('Yes', 'griffinforms-form-builder') : __('No', 'griffinforms-form-builder'));
        $this->tableRowHtml(__('Active', 'griffinforms-form-builder'), !empty($pro_state['is_active']) ? __('Yes', 'griffinforms-form-builder') : __('No', 'griffinforms-form-builder'));
        $this->tableRowHtml(__('Approval', 'griffinforms-form-builder'), $this->formatStateLabel((string) ($pro_state['approval_status'] ?? 'unknown')));
        $this->tableRowHtml(__('Compatibility', 'griffinforms-form-builder'), $this->formatStateLabel((string) ($pro_state['compatibility_state'] ?? 'unknown')));
        $this->tableRowHtml(__('Integrity', 'griffinforms-form-builder'), $this->formatStateLabel((string) ($pro_state['integrity_state'] ?? 'unknown')));
        $this->tableRowHtml(__('Update state', 'griffinforms-form-builder'), $this->formatStateLabel((string) ($pro_state['update_state'] ?? 'unknown')));
        echo '</tbody>';
        echo '</table>';
        echo '</div>';
        echo '</div>';

        echo '<div class="col-lg-6" style="margin-bottom:16px;">';
        echo '<div style="padding:18px;border:1px solid #e5e7eb;border-radius:14px;background:#fff;height:100%;">';
        echo '<h3 style="margin:0 0 12px 0;font-size:16px;">' . esc_html__('Entitlement', 'griffinforms-form-builder') . '</h3>';
        echo '<table class="widefat striped" style="margin:0;">';
        echo '<tbody>';
        $this->tableRowHtml(__('Entitlement state', 'griffinforms-form-builder'), $this->formatStateLabel((string) ($pro_state['entitlement_state'] ?? 'unknown')));
        $this->tableRowHtml(__('Verification state', 'griffinforms-form-builder'), $this->formatStateLabel((string) ($pro_state['verification_state'] ?? 'unknown')));
        $this->tableRowHtml(__('License key present', 'griffinforms-form-builder'), !empty($pro_state['license_key_present']) ? __('Yes', 'griffinforms-form-builder') : __('No', 'griffinforms-form-builder'));
        $this->tableRowHtml(__('Recommended action', 'griffinforms-form-builder'), $status_model['action_text']);
        $this->tableRowHtml(__('Warning layer', 'griffinforms-form-builder'), $this->formatValue((string) ($pro_state['warning_layer_key'] ?? '')));
        $this->tableRowHtml(__('Blocking reason', 'griffinforms-form-builder'), $this->formatValue((string) ($pro_state['blocking_reason_key'] ?? '')));
        echo '</tbody>';
        echo '</table>';
        echo '</div>';
        echo '</div>';
        echo '</div>';

        echo '<h3 style="margin:0 0 12px 0;font-size:16px;">' . esc_html__('Verification timeline', 'griffinforms-form-builder') . '</h3>';
        echo '<table class="widefat striped" style="max-width:100%;margin-bottom:20px;">';
        echo '<tbody>';
        $this->tableRowHtml(__('Last verified', 'griffinforms-form-builder'), $this->formatDateTimeValue((string) ($pro_state['last_verified_at'] ?? '')));
        $this->tableRowHtml(__('Last successful verification', 'griffinforms-form-builder'), $this->formatDateTimeValue((string) ($pro_state['last_successful_verification_at'] ?? '')));
        $this->tableRowHtml(__('Last failed verification', 'griffinforms-form-builder'), $this->formatDateTimeValue((string) ($pro_state['last_failed_verification_at'] ?? '')));
        $this->tableRowHtml(__('Next retry', 'griffinforms-form-builder'), $this->formatDateTimeValue((string) ($pro_state['next_retry_at'] ?? '')));
        $this->tableRowHtml(__('Grace started', 'griffinforms-form-builder'), $this->formatDateTimeValue((string) ($pro_state['grace_started_at'] ?? '')));
        $this->tableRowHtml(__('Grace expires', 'griffinforms-form-builder'), $this->formatDateTimeValue((string) ($pro_state['grace_expires_at'] ?? '')));
        $this->tableRowHtml(__('License expires', 'griffinforms-form-builder'), $this->formatDateTimeValue((string) ($pro_state['license_expires_at'] ?? '')));
        $this->tableRowHtml(__('Verification failures', 'griffinforms-form-builder'), (string) max(0, absint($pro_state['verification_failure_count'] ?? 0)));
        echo '</tbody>';
        echo '</table>';

        echo '<h3 style="margin:0 0 12px 0;font-size:16px;">' . esc_html__('Technical identifiers', 'griffinforms-form-builder') . '</h3>';
        echo '<table class="widefat striped" style="max-width:100%;">';
        echo '<tbody>';
        $this->tableRowHtml(__('Package ID', 'griffinforms-form-builder'), (string) ($pro_state['package_id'] ?? 'pro'));
        $this->tableRowHtml(__('Package Type', 'griffinforms-form-builder'), (string) ($pro_state['package_type'] ?? 'pro'));
        $this->tableRowHtml(__('Version', 'griffinforms-form-builder'), $this->formatValue((string) ($pro_state['package_version'] ?? '')));
        echo '</tbody>';
        echo '</table>';

        echo '</div>';
        echo '</div>';
        echo '</div>';
    }

    protected function tableRowHtml(string $label, string $value)
    {
        echo '<tr>';
        echo '<th scope="row" style="width:240px;">' . esc_html($label) . '</th>';
        echo '<td>' . esc_html($value) . '</td>';
        echo '</tr>';
    }

    protected function buildStatusModel(array $pro_state): array
    {
        $compatibility_state = (string) ($pro_state['compatibility_state'] ?? 'unknown');
        $entitlement_state = (string) ($pro_state['entitlement_state'] ?? 'unknown');
        $recommended_action = (string) ($pro_state['recommended_user_action'] ?? '');

        if (empty($pro_state['is_present'])) {
            return [
                'badge' => __('Not Installed', 'griffinforms-form-builder'),
                'title' => __('GriffinForms Pro is not installed', 'griffinforms-form-builder'),
                'message' => __('Core can expose the Pro shell state only after a recognized Pro package is installed on this site.', 'griffinforms-form-builder'),
                'action_text' => $this->formatActionLabel($recommended_action !== '' ? $recommended_action : 'install_pro'),
            ];
        }

        if (empty($pro_state['is_active'])) {
            return [
                'badge' => __('Installed', 'griffinforms-form-builder'),
                'title' => __('GriffinForms Pro is installed but not active', 'griffinforms-form-builder'),
                'message' => __('The Pro package is present, but Core is not currently receiving any active runtime providers or entitlement signals from it.', 'griffinforms-form-builder'),
                'action_text' => $this->formatActionLabel($recommended_action !== '' ? $recommended_action : 'activate_pro'),
            ];
        }

        if ($compatibility_state !== 'compatible') {
            return [
                'badge' => __('Needs Attention', 'griffinforms-form-builder'),
                'title' => __('GriffinForms Pro is active but not compatible', 'griffinforms-form-builder'),
                'message' => __('Core recognizes the Pro package, but the compatibility contract is not healthy enough for normal Pro behavior.', 'griffinforms-form-builder'),
                'action_text' => $this->formatActionLabel($recommended_action !== '' ? $recommended_action : 'resolve_compatibility'),
            ];
        }

        if ($entitlement_state === 'verified_active') {
            return [
                'badge' => __('Verified Active', 'griffinforms-form-builder'),
                'title' => __('GriffinForms Pro is active and entitled', 'griffinforms-form-builder'),
                'message' => __('Core sees a compatible Pro package with a verified active entitlement. This is the healthy reference state for internal Pro contract testing.', 'griffinforms-form-builder'),
                'action_text' => __('No immediate action required.', 'griffinforms-form-builder'),
            ];
        }

        if ($entitlement_state === 'verified_inactive_or_expired') {
            return [
                'badge' => __('License Inactive', 'griffinforms-form-builder'),
                'title' => __('GriffinForms Pro license is inactive or expired', 'griffinforms-form-builder'),
                'message' => __('The Pro package is active and compatible, but entitlement is currently blocked by an inactive or expired license state.', 'griffinforms-form-builder'),
                'action_text' => $this->formatActionLabel($recommended_action),
            ];
        }

        if ($entitlement_state === 'unverified_connection_issue') {
            return [
                'badge' => __('Verification Issue', 'griffinforms-form-builder'),
                'title' => __('GriffinForms Pro could not be verified recently', 'griffinforms-form-builder'),
                'message' => __('Core is treating the current entitlement problem as a connection or verification issue, not as a confirmed expired license.', 'griffinforms-form-builder'),
                'action_text' => $this->formatActionLabel($recommended_action),
            ];
        }

        if ($entitlement_state === 'grace_period') {
            return [
                'badge' => __('Grace Period', 'griffinforms-form-builder'),
                'title' => __('GriffinForms Pro is running in grace period', 'griffinforms-form-builder'),
                'message' => __('Core is temporarily allowing Pro behavior while verification is retried. This state should be monitored until a fresh verification succeeds or grace expires.', 'griffinforms-form-builder'),
                'action_text' => $this->formatActionLabel($recommended_action),
            ];
        }

        return [
            'badge' => __('License Key Needed', 'griffinforms-form-builder'),
            'title' => __('GriffinForms Pro is ready for license activation', 'griffinforms-form-builder'),
            'message' => __('The Pro package is installed, active, and compatible, but no verified entitlement is available yet.', 'griffinforms-form-builder'),
            'action_text' => $this->formatActionLabel($recommended_action !== '' ? $recommended_action : 'enter_license_key'),
        ];
    }

    protected function formatStateLabel(string $value): string
    {
        $value = trim($value);
        if ($value === '') {
            return __('Not recorded', 'griffinforms-form-builder');
        }

        return ucwords(str_replace(['_', '-'], ' ', $value));
    }

    protected function formatActionLabel(string $value): string
    {
        $value = trim($value);
        if ($value === '') {
            return __('No action recorded.', 'griffinforms-form-builder');
        }

        $labels = [
            'install_pro' => __('Install the Pro package.', 'griffinforms-form-builder'),
            'activate_pro' => __('Activate the installed Pro package.', 'griffinforms-form-builder'),
            'resolve_compatibility' => __('Resolve the Core and Pro compatibility mismatch.', 'griffinforms-form-builder'),
            'enter_license_key' => __('Enter or reactivate a Pro license key.', 'griffinforms-form-builder'),
            'reactivate_license' => __('Reactivate or renew the Pro license.', 'griffinforms-form-builder'),
            'retry_license_verification' => __('Retry Pro license verification soon.', 'griffinforms-form-builder'),
            'monitor_grace_period' => __('Monitor the grace period and retry verification before it expires.', 'griffinforms-form-builder'),
        ];

        return $labels[$value] ?? $this->formatStateLabel($value);
    }

    protected function formatValue(string $value): string
    {
        $value = trim($value);
        return $value !== '' ? $value : __('Not recorded', 'griffinforms-form-builder');
    }

    protected function formatDateTimeValue(string $value): string
    {
        $value = trim($value);
        if ($value === '') {
            return __('Not recorded', 'griffinforms-form-builder');
        }

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

        return wp_date(
            trim(get_option('date_format') . ' ' . get_option('time_format')),
            $timestamp
        );
    }

    protected function buildLibrariesSurfaceModel(array $pro_state): array
    {
        if (empty($pro_state['is_present'])) {
            return [
                'badge' => __('Locked', 'griffinforms-form-builder'),
                'message' => __('The libraries/installability surface is discoverable in Core, but remains locked until a recognized Pro package is installed.', 'griffinforms-form-builder'),
                'mode_label' => __('Locked discoverability shell', 'griffinforms-form-builder'),
            ];
        }

        if (empty($pro_state['is_active'])) {
            return [
                'badge' => __('Locked', 'griffinforms-form-builder'),
                'message' => __('The Pro package is installed, but Core keeps the libraries surface locked until Pro is active.', 'griffinforms-form-builder'),
                'mode_label' => __('Locked discoverability shell', 'griffinforms-form-builder'),
            ];
        }

        if (($pro_state['compatibility_state'] ?? 'unknown') !== 'compatible') {
            return [
                'badge' => __('Blocked', 'griffinforms-form-builder'),
                'message' => __('Package-health warnings outrank monetization framing, so the libraries surface stays blocked until compatibility is restored.', 'griffinforms-form-builder'),
                'mode_label' => __('Blocked by package warning', 'griffinforms-form-builder'),
            ];
        }

        if (!in_array((string) ($pro_state['entitlement_state'] ?? ''), ['verified_active', 'grace_period'], true)) {
            return [
                'badge' => __('Locked', 'griffinforms-form-builder'),
                'message' => __('The libraries surface is installed and active, but it stays locked until Pro entitlement is healthy.', 'griffinforms-form-builder'),
                'mode_label' => __('Locked discoverability shell', 'griffinforms-form-builder'),
            ];
        }

        return [
            'badge' => __('Live', 'griffinforms-form-builder'),
            'message' => __('The libraries surface is now admitted and can present usable installability state instead of a locked shell.', 'griffinforms-form-builder'),
            'mode_label' => __('Admitted/live UI', 'griffinforms-form-builder'),
        ];
    }

    protected function getProBadgeHtml(string $variant = 'light'): string
    {
        $badge = new \GriffinForms\Admin\Html\Elements\ProBadge('Pro', $variant);
        ob_start();
        $badge->html();

        return (string) ob_get_clean();
    }
}
