<?php

namespace GriffinForms\Includes\CommandPalette\Providers;

use GriffinForms\Includes\CommandPalette\SearchProviderInterface;
use GriffinForms\Includes\CommandPalette\SearchResultItem;

class ThemeTabsProvider implements SearchProviderInterface
{
    public function getProviderId(): string { return 'theme_tabs'; }
    public function getLabel(): string      { return 'Theme Tabs'; }
    public function getPriority(): int      { return 38; }
    public function getQuickItems(int $form_id): array { return []; }

    private function tabs(): array
    {
        return [
            [
                'slug'        => 'select-theme',
                'label'       => __('Select Theme', 'griffinforms-form-builder'),
                'description' => __('Browse and apply a theme to this form', 'griffinforms-form-builder'),
                'keywords'    => ['select', 'browse', 'apply', 'choose', 'pick'],
            ],
            [
                'slug'        => 'import-theme',
                'label'       => __('Import Theme', 'griffinforms-form-builder'),
                'description' => __('Import a theme from a JSON file', 'griffinforms-form-builder'),
                'keywords'    => ['import', 'upload', 'json', 'file'],
            ],
        ];
    }

    public function query(string $query, int $form_id): array
    {
        if ($query === '') {
            return [];
        }

        $results = [];

        foreach ($this->tabs() as $tab) {
            $matched = stripos($tab['label'], $query) !== false
                || stripos($tab['description'], $query) !== false;

            if (!$matched) {
                foreach ($tab['keywords'] as $kw) {
                    if (stripos($kw, $query) !== false) {
                        $matched = true;
                        break;
                    }
                }
            }

            if (!$matched) {
                continue;
            }

            $results[] = new SearchResultItem(
                result_id:      'theme_tab_' . $tab['slug'],
                provider_id:    $this->getProviderId(),
                label:          $tab['label'],
                action_type:    'open_modal_with_context',
                action_payload: [
                    'modal_id' => 'griffinforms-builder-modal-formthemes',
                    'context'  => ['tab' => $tab['slug']],
                ],
                description:    $tab['description'],
                icon:           'theme_tab',
                score:          0
            );
        }

        return $results;
    }
}
