<?php

namespace GriffinForms\Admin\Html\Pages;

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

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

    protected function setLibraryRegistry()
    {
        $this->library_registry = \GriffinForms\Includes\Libraries\LibraryRegistry::getInstance();
    }

    public function html()
    {
        $state = $this->package_state_resolver->getState();
        $pro_state = is_array($state['packages']['pro'] ?? null) ? $state['packages']['pro'] : [];
        $libraries = $this->library_registry->getAll();
        uasort($libraries, static function (array $left, array $right) {
            return strnatcasecmp((string) ($left['label'] ?? ''), (string) ($right['label'] ?? ''));
        });

        $surface = $this->buildSurfaceModel($pro_state);

        echo '<div class="wrap gf-libraries-page-wrap">';
        $this->pageHeading(__('Libraries Catalog', 'griffinforms-form-builder'), __('Internal package-aware library and installability surface.', 'griffinforms-form-builder'));

        echo '<div class="card" style="max-width:1180px;">';
        echo '<div class="card-body">';
        echo '<p class="mb-4 text-muted">' . esc_html__('This internal page is the first Core-owned libraries catalog seam. It shows how a package-aware surface transitions between locked discoverability and live installability based on normalized package state.', 'griffinforms-form-builder') . '</p>';

        echo '<div style="padding:20px 22px;border:1px solid #e2e8f0;border-radius:16px;background:linear-gradient(135deg,#fffdf8 0%,#fff7ef 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($surface['badge']) . '</span>';
        echo '</div>';
        echo '<h2 style="margin:0 0 8px 0;font-size:24px;line-height:1.2;">' . esc_html($surface['title']) . '</h2>';
        echo '<p style="margin:0 0 12px 0;color:#475569;max-width:760px;">' . esc_html($surface['message']) . '</p>';
        echo '<p style="margin:0;color:#0f172a;"><strong>' . esc_html__('Mode:', 'griffinforms-form-builder') . '</strong> ' . esc_html($surface['mode_label']) . '</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(admin_url('admin.php?page=' . $this->config::PREFIX . '-pro')) . '">' . esc_html__('Open Pro Status', 'griffinforms-form-builder') . '</a>';
        echo '<a class="button button-secondary" href="' . esc_url(admin_url('admin.php?page=' . $this->config::PREFIX . '-diagnostics')) . '">' . esc_html__('Open Diagnostics', 'griffinforms-form-builder') . '</a>';
        echo '</div>';
        echo '</div>';
        echo '</div>';

        echo '<h2 class="mb-3">' . esc_html__('Catalog', 'griffinforms-form-builder') . '</h2>';
        if (empty($libraries)) {
            echo '<div class="notice notice-info inline"><p>' . esc_html__('No package libraries are registered yet. This page still exposes the locked-to-live surface contract for future Pro and extension libraries.', 'griffinforms-form-builder') . '</p></div>';
        } else {
            echo '<table class="widefat striped mb-4">';
            echo '<thead><tr>';
            echo '<th>' . esc_html__('Library', 'griffinforms-form-builder') . '</th>';
            echo '<th>' . esc_html__('Owner Package', 'griffinforms-form-builder') . '</th>';
            echo '<th>' . esc_html__('Surface Mode', 'griffinforms-form-builder') . '</th>';
            echo '<th>' . esc_html__('Library State', 'griffinforms-form-builder') . '</th>';
            echo '<th>' . esc_html__('Action', 'griffinforms-form-builder') . '</th>';
            echo '</tr></thead><tbody>';

            foreach ($libraries as $library) {
                $row = $this->buildLibraryRowModel($library, $pro_state);
                echo '<tr>';
                echo '<td><strong>' . esc_html($row['label']) . '</strong><br><code>' . esc_html($row['id']) . '</code></td>';
                echo '<td>' . esc_html($row['package_label']) . '</td>';
                echo '<td>' . esc_html($row['surface_mode']) . '</td>';
                echo '<td>' . esc_html($row['library_state']) . '</td>';
                echo '<td>' . esc_html($row['action_text']) . '</td>';
                echo '</tr>';
            }

            echo '</tbody></table>';
        }

        echo '<h2 class="mb-3">' . esc_html__('Locked-To-Live Rule In Practice', 'griffinforms-form-builder') . '</h2>';
        echo '<table class="widefat striped"><tbody>';
        $this->tableRowHtml(__('Hidden', 'griffinforms-form-builder'), __('Core keeps the surface undiscoverable until product design chooses to expose it.', 'griffinforms-form-builder'));
        $this->tableRowHtml(__('Locked discoverability shell', 'griffinforms-form-builder'), __('Core shows the surface, but keeps it non-usable with installation, activation, or entitlement guidance.', 'griffinforms-form-builder'));
        $this->tableRowHtml(__('Admitted/live UI', 'griffinforms-form-builder'), __('Core hands off to the usable installability or package-backed UI once package state admits it.', 'griffinforms-form-builder'));
        $this->tableRowHtml(__('Preserved unavailable UI', 'griffinforms-form-builder'), __('Existing package-owned content uses preservation messaging rather than upgrade framing.', 'griffinforms-form-builder'));
        echo '</tbody></table>';

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

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

        if (empty($pro_state['is_present'])) {
            return [
                'badge' => __('Locked', 'griffinforms-form-builder'),
                'title' => __('Pro-owned library surfaces are currently locked', 'griffinforms-form-builder'),
                'message' => __('Core can expose the catalog and installability shell, but Pro-owned libraries stay in discoverability mode 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'),
                'title' => __('Pro-owned library surfaces are installed but not admitted yet', 'griffinforms-form-builder'),
                'message' => __('The Pro package is present, but Core keeps package-aware library surfaces locked until Pro is active and healthy.', 'griffinforms-form-builder'),
                'mode_label' => __('Locked discoverability shell', 'griffinforms-form-builder'),
            ];
        }

        if ($compatibility_state !== 'compatible') {
            return [
                'badge' => __('Blocked', 'griffinforms-form-builder'),
                'title' => __('Pro-owned library surfaces are blocked by package health', 'griffinforms-form-builder'),
                'message' => __('Compatibility problems outrank monetization framing. Core keeps this surface blocked until package health is restored.', 'griffinforms-form-builder'),
                'mode_label' => __('Blocked by package warning', 'griffinforms-form-builder'),
            ];
        }

        if (!in_array($entitlement_state, ['verified_active', 'grace_period'], true)) {
            return [
                'badge' => __('Locked', 'griffinforms-form-builder'),
                'title' => __('Pro-owned library surfaces are waiting for entitlement', 'griffinforms-form-builder'),
                'message' => __('The Pro package is active and compatible, but Core keeps the installability surface locked until entitlement is healthy.', 'griffinforms-form-builder'),
                'mode_label' => __('Locked discoverability shell', 'griffinforms-form-builder'),
            ];
        }

        return [
            'badge' => __('Live', 'griffinforms-form-builder'),
            'title' => __('Pro-owned library surfaces are live', 'griffinforms-form-builder'),
            'message' => __('Core now treats this package-aware surface as admitted and can show usable installability state instead of a locked shell.', 'griffinforms-form-builder'),
            'mode_label' => __('Admitted/live UI', 'griffinforms-form-builder'),
        ];
    }

    protected function buildLibraryRowModel(array $library, array $pro_state): array
    {
        $package_id = sanitize_key((string) ($library['package_id'] ?? 'core'));
        $action_intent = (string) ($library['state']['action_intent'] ?? 'unavailable');
        $surface_mode = __('Admitted / live', 'griffinforms-form-builder');
        $action_text = $this->formatActionIntent($action_intent);

        if ($package_id === 'pro') {
            if (empty($pro_state['is_present'])) {
                $surface_mode = __('Locked / install Pro', 'griffinforms-form-builder');
                $action_text = __('Install the Pro package first.', 'griffinforms-form-builder');
            } elseif (empty($pro_state['is_active'])) {
                $surface_mode = __('Locked / activate Pro', 'griffinforms-form-builder');
                $action_text = __('Activate the installed Pro package.', 'griffinforms-form-builder');
            } elseif (($pro_state['compatibility_state'] ?? 'unknown') !== 'compatible') {
                $surface_mode = __('Blocked / compatibility', 'griffinforms-form-builder');
                $action_text = __('Resolve Core and Pro compatibility first.', 'griffinforms-form-builder');
            } elseif (!in_array((string) ($pro_state['entitlement_state'] ?? ''), ['verified_active', 'grace_period'], true)) {
                $surface_mode = __('Locked / entitlement', 'griffinforms-form-builder');
                $action_text = __('Restore a healthy Pro entitlement to unlock this surface.', 'griffinforms-form-builder');
            }
        } elseif ($action_intent === 'unavailable') {
            $surface_mode = __('Locked / package unavailable', 'griffinforms-form-builder');
            $action_text = __('Required package state is not available yet.', 'griffinforms-form-builder');
        }

        return [
            'id' => (string) ($library['id'] ?? ''),
            'label' => (string) ($library['label'] ?? ''),
            'package_label' => strtoupper($package_id !== '' ? $package_id : 'core'),
            'surface_mode' => $surface_mode,
            'library_state' => $this->formatLibraryState($library),
            'action_text' => $action_text,
        ];
    }

    protected function formatLibraryState(array $library): string
    {
        $state = is_array($library['state'] ?? null) ? $library['state'] : [];
        $installed = !empty($state['installed']) ? __('Installed', 'griffinforms-form-builder') : __('Not installed', 'griffinforms-form-builder');
        $active = !empty($state['active']) ? __('active', 'griffinforms-form-builder') : __('inactive', 'griffinforms-form-builder');
        $version = trim((string) ($state['version'] ?? ''));

        $label = $installed . ' / ' . $active;
        if ($version !== '') {
            $label .= ' / ' . sprintf(__('Version %s', 'griffinforms-form-builder'), $version);
        }

        return $label;
    }

    protected function formatActionIntent(string $action_intent): string
    {
        $labels = [
            'install' => __('Install library', 'griffinforms-form-builder'),
            'activate' => __('Activate library', 'griffinforms-form-builder'),
            'ready' => __('Ready to use', 'griffinforms-form-builder'),
            'unavailable' => __('Unavailable in current package state', 'griffinforms-form-builder'),
        ];

        return $labels[$action_intent] ?? ucwords(str_replace(['_', '-'], ' ', $action_intent));
    }

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

    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();
    }
}
