<?php

namespace GriffinForms\Admin\Html\Pages\Lists;

class Forms extends \GriffinForms\Admin\Html\Pages\Lists\Format
{   
    protected $meta;
    protected $inline_js;
    protected $order_by = 'created';
    protected $order = 'desc';
    protected $onboarding_eligibility;
    protected $conditional_logic_counts = array();
    protected $submission_edit_signal_cache = array();
    protected $migration_notice_service;
    
    protected function setType()
    {
        $this->type = 'form';
    }

    protected function setOnboardingEligibility()
    {
        $this->onboarding_eligibility = \GriffinForms\Includes\Onboarding\Eligibility::getInstance();
    }

    protected function setMigrationNoticeService()
    {
        $this->migration_notice_service = \GriffinForms\Includes\Migration\MigrationNotice::getInstance();
    }

    protected function setBulkActions()
    {
        $this->bulk_actions = array(
            'selectFolder',
            'deleteForms'
        );
    }

    protected function createFormModal()
    {
        $for = 'createForm';
        $class = 'modal-xl';
        $this->newModal($for, $class);
    }

    protected function deleteFormsModal()
    {
        $for = 'deleteForms';
        $class = '';
        $this->newModal($for, $class);
    }

    protected function selectFolderModal()
    {
        $for = 'SelectFolder';
        $class = 'modal-lg';
        $this->newModal($for, $class);
    }

    protected function pageModals()
    {
        $this->deleteFormsModal();
        $this->selectFolderModal();
        $this->publishFormModal();
        $this->previewFormModal();
        $this->createFormModal();
        $this->deleteListItemModal();
        (new \GriffinForms\Admin\Html\Modals\ColumnManager())->html();
    }

    protected function publishFormModal()
    {
        $for = 'PublishForm';
        $class = 'modal-lg';
        $this->newModal($for, $class);
    }

    protected function previewFormModal()
    {
        $for = 'PreviewForm';
        $class = 'modal-xl';
        $this->newModal($for, $class);
    }

    protected function createFormBtn()
    {
        echo '<button type="button" class="page-title-action" data-bs-toggle="modal" data-bs-target="#' . esc_attr($this->modal_ids['createForm']) . '">';
        echo esc_html($this->lang->getText('create', $this->type));
        echo '</button>';
    }

    protected function createWithAiBtn()
    {
        echo '<button type="button" class="page-title-action gf-btn-ai-sparkle gf-create-ai-modal-btn" data-bs-toggle="modal" data-bs-target="#' . esc_attr($this->modal_ids['createForm']) . '" data-gf-open-tab="griffinforms-create-form-modal-butler-assist-tab">';
        echo esc_html__('Create with AI', 'griffinforms-form-builder');
        echo '</button>';
    }

    protected function listHeading()
    {
        $notices_html = $this->migrationNoticesHtml();

        echo '<h1 class="wp-heading-inline">' . esc_html($this->lang->getText($this->meta, 'list_heading')) . '</h1>';
        //$this->addNewButton();
        $this->createFormBtn();
        $this->createWithAiBtn();
        echo '<hr class="wp-header-end">';

        if ($notices_html !== '') {
            $this->enqueueMigrationNoticeAssets();
            echo $notices_html;
        }
    }

    protected function migrationNoticesHtml(): string
    {
        $sources = $this->migration_notice_service->getDetectedSources();
        if (empty($sources)) {
            return '';
        }

        $user_id = get_current_user_id();
        $html = '<div class="gf-migration-notices" data-gf-migration-notices>';

        foreach ($sources as $source) {
            if ($this->migration_notice_service->isDismissed($source->getSlug(), $user_id)) {
                continue;
            }

            $remaining_forms = $this->migration_notice_service->getRemainingForms($source);
            if (empty($remaining_forms)) {
                continue;
            }

            $html .= $this->singleMigrationNoticeHtml($source, $remaining_forms);
        }

        $html .= '</div>';

        return $html === '<div class="gf-migration-notices" data-gf-migration-notices></div>' ? '' : $html;
    }

    /**
     * @param array<int, array<string, mixed>> $remaining_forms
     */
    protected function singleMigrationNoticeHtml($source, array $remaining_forms): string
    {
        $count = count($remaining_forms);
        $slug = $source->getSlug();
        $logo_url = $source->getLogoUrl();
        $source_label = $source->getLabel();
        $target_logo = $this->config->getRootUrl() . 'admin/images/onboarding/griffinforms-logo.svg';
        $import_url = add_query_arg(
            [
                'page' => 'griffinforms-migration',
                'source' => $slug,
            ],
            admin_url('admin.php')
        );

        $html = '<div class="gf-migration-notice" data-gf-migration-notice="' . esc_attr($slug) . '">';
        $html .= '<div class="gf-migration-notice-bridge">';
        $html .= '<span class="gf-migration-notice-logo gf-migration-notice-logo-source">';
        if ($logo_url !== '') {
            $html .= '<img src="' . esc_url($logo_url) . '" alt="' . esc_attr($source_label) . '" height="24" loading="lazy" decoding="async">';
        } else {
            $html .= '<span class="gf-migration-notice-monogram" aria-hidden="true">' . esc_html($this->migrationNoticeInitials($source_label)) . '</span>';
            $html .= '<span class="screen-reader-text">' . esc_html($source_label) . '</span>';
        }
        $html .= '</span>';
        $html .= '<span class="gf-migration-notice-arrow" aria-hidden="true">' . $this->migrationNoticeArrowSvg() . '</span>';
        $html .= '<span class="gf-migration-notice-logo gf-migration-notice-logo-target">';
        $html .= '<img src="' . esc_url($target_logo) . '" alt="' . esc_attr__('GriffinForms', 'griffinforms-form-builder') . '" height="24" loading="lazy" decoding="async">';
        $html .= '</span>';
        $html .= '</div>';

        $html .= '<div class="gf-migration-notice-copy">';
        $html .= '<p class="gf-migration-notice-title">' . esc_html(sprintf(_n('You have %d form in %s.', 'You have %d forms in %s.', $count, 'griffinforms-form-builder'), $count, $source_label)) . '</p>';
        $html .= '<p class="gf-migration-notice-text">' . esc_html__('Import them into GriffinForms in seconds.', 'griffinforms-form-builder') . '</p>';
        $html .= '</div>';

        $html .= '<div class="gf-migration-notice-actions">';
        $html .= '<a class="button button-primary" href="' . esc_url($import_url) . '">' . esc_html__('Import', 'griffinforms-form-builder') . '</a>';
        $html .= '<button type="button" class="gf-migration-notice-dismiss" data-gf-migration-dismiss="' . esc_attr($slug) . '" aria-label="' . esc_attr(sprintf(__('Dismiss %s migration notice', 'griffinforms-form-builder'), $source_label)) . '">×</button>';
        $html .= '</div>';
        $html .= '</div>';

        return $html;
    }

    protected function enqueueMigrationNoticeAssets(): void
    {
        $css_handle = 'griffinforms-migration-notice-css';
        $js_handle = 'griffinforms-migration-notice-js';

        wp_enqueue_style(
            $css_handle,
            $this->config->getRootUrl() . 'admin/css/griffinforms-migration-notice.css',
            [],
            '1.0',
            'all'
        );

        wp_enqueue_script(
            $js_handle,
            $this->config->getRootUrl() . 'admin/js/griffinforms-migration-notice.js',
            ['wp-api-fetch'],
            '1.0',
            true
        );

        wp_add_inline_script($js_handle, 'window.gfMigrationNotice = ' . wp_json_encode([
            'restBase' => rest_url('griffinforms/v1'),
            'restNonce' => wp_create_nonce('wp_rest'),
            'strings' => [
                'dismissError' => __('Migration notice dismissal failed.', 'griffinforms-form-builder'),
            ],
        ]) . ';', 'before');
    }

    protected function migrationNoticeInitials(string $label): string
    {
        $parts = preg_split('/\s+/', trim($label)) ?: [];
        $initials = '';

        foreach ($parts as $part) {
            if ($part === '') {
                continue;
            }

            $initials .= strtoupper(substr($part, 0, 1));
            if (strlen($initials) >= 2) {
                break;
            }
        }

        return $initials !== '' ? $initials : 'GF';
    }

    protected function migrationNoticeArrowSvg(): string
    {
        return '<svg viewBox="0 0 56 14" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M1 7H49" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/><path d="M43 1L49 7L43 13" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>';
    }
    
    protected function setFilterNames()
    {
        $this->filter_names = array(
            'workflow',
            'folder_id',
            'search',
            'date_from',
            'date_to',
        );
    }

    protected function setFilterLinks()
    {
        $this->filter_links = array(
            'all',
            'userRegistration',
        );
    }
    
    protected function registerColumns(): void
    {
        $r = $this->column_registry;

        $r->register('form', 'checkbox',    ['label' => '',                                                    'locked' => true, 'default_on' => true]);
        $r->register('form', 'name',        ['label' => $this->lang->getText('name', 'list_head'),             'locked' => true, 'default_on' => true, 'sortable' => true]);

        $r->register('form', 'signals',     ['label' => __('Signals', 'griffinforms-form-builder'),            'default_on' => true]);
        $r->register('form', 'publish',     ['label' => $this->lang->getText('publish', 'list_head'),          'default_on' => true]);
        $r->register('form', 'folder',      ['label' => $this->lang->getText('folder', 'list_head'),           'default_on' => true]);
        $r->register('form', 'formpages',   ['label' => $this->lang->getText('formpages', 'list_head'),        'default_on' => true]);
        $r->register('form', 'submissions', ['label' => $this->lang->getText('submissions', 'list_head'),      'default_on' => true]);
        $r->register('form', 'author',      ['label' => $this->lang->getText('author', 'list_head'),           'default_on' => true,
            'variants' => [
                'default'  => __('Username + full name', 'griffinforms-form-builder'),
                'nicename' => __('Username only', 'griffinforms-form-builder'),
                'fullname' => __('Full name only', 'griffinforms-form-builder'),
            ],
            'default_variant' => 'default',
        ]);
        $r->register('form', 'created',     ['label' => $this->lang->getText('created', 'list_head'),          'default_on' => true,  'sortable' => true]);

        $r->register('form', 'id',          ['label' => __('ID', 'griffinforms-form-builder'),                 'default_on' => false]);
        $r->register('form', 'description', ['label' => __('Description', 'griffinforms-form-builder'),        'default_on' => false]);
        $r->register('form', 'status',      ['label' => __('Status', 'griffinforms-form-builder'),             'default_on' => false]);
        $r->register('form', 'origin',      ['label' => __('Origin', 'griffinforms-form-builder'),             'default_on' => false]);
        $r->register('form', 'shortcode',   ['label' => $this->lang->getText('shortcode', 'list_head'),        'default_on' => false]);
        $r->register('form', 'lastedited',  ['label' => __('Last Edited', 'griffinforms-form-builder'),        'default_on' => false, 'sortable' => true]);
        $r->register('form', 'lasteditor',  ['label' => __('Last Editor', 'griffinforms-form-builder'),        'default_on' => false,
            'variants' => [
                'default'  => __('Username + full name', 'griffinforms-form-builder'),
                'nicename' => __('Username only', 'griffinforms-form-builder'),
            ],
            'default_variant' => 'default',
        ]);
        $r->register('form', 'compliance',  ['label' => __('Compliance', 'griffinforms-form-builder'),         'default_on' => false]);

        parent::registerColumns();
    }

    protected function setRowActions()
    {
        $this->row_actions = array(
            'ai_edit',
            'layout',
            'export',
            'preview_form',
            'trash'
        );
    }

    protected function getItemUrl($item)
    {
        return admin_url('admin.php?page=griffinforms-app&form_id=' . absint($item->id));
    }

    protected function itemFilters()
    {
        echo '<div class="alignleft actions">';
        $this->folderFilter();
        $this->dateFilter();
        echo '</div>';
    }
    
    protected function folderFilter()
    {
        $folder_id = isset($_GET['folder_id']) ? absint(wp_unslash($_GET['folder_id'])) : 0;
        $folder_filter = new \GriffinForms\Admin\Html\FormControls\Forms\FolderFilter('folder_filter', $folder_id);
        $folder_filter->html();
    }

    protected function userRegistrationFilterLink()
    {
        $count = (int) $this->sql->resultsCount([
            'item_type' => $this->type,
            'list_size' => 1,
            'order_by' => $this->order_by,
            'order' => $this->order,
            'offset' => 0,
            'filters' => [
                'workflow' => 'user_registration',
            ],
        ]);

        $link_class = '';
        $aria_current = '';
        $workflow = isset($_GET['workflow']) ? sanitize_key(wp_unslash($_GET['workflow'])) : '';
        if ($workflow === 'user_registration') {
            $link_class = 'current';
            $aria_current = ' aria-current="page"';
        }

        $url = add_query_arg(
            [
                'page' => 'griffinforms-forms',
                'workflow' => 'user_registration',
            ],
            admin_url('admin.php')
        );

        echo '<a href="' . esc_url($url) . '" class="' . esc_attr($link_class) . '"' . $aria_current . '>';
        echo esc_html__('User Registration', 'griffinforms-form-builder');
        echo ' <span class="count">(' . absint($count) . ')</span>';
        echo '</a>';
    }
    
    protected function nameCellText($list_column, $item)
    {
        $name = empty($item->name) ? '<em>' . $this->lang->getText('name_not_set') . '</em>': $item->name;
        echo wp_kses_post($name);
        
        if (isset($item->status) && $item->status === 'draft') {
            echo ' — <span class="gf-wp-badge gf-wp-badge-ai">' . esc_html__('AI Draft', 'griffinforms-form-builder') . '</span>';
        }
    }

    protected function publishHeadingText($list_column)
    {
        echo '<span>' . esc_html__('Publish', 'griffinforms-form-builder') . '</span>';
    }

    protected function publishCellText($list_column, $item)
    {
        $shortcode = \GriffinForms\Includes\Onboarding\PlacementService::getInstance()->getShortcode((int) $item->id);
        $modal_id = $this->modal_ids['PublishForm'] ?? 'griffinforms-publishform-modal';

        echo '<a href="#" class="button-link gf-form-publish-link" data-bs-toggle="modal" data-bs-target="#' . esc_attr($modal_id) . '" data-gf-form-id="' . absint($item->id) . '" data-gf-shortcode="' . esc_attr($shortcode) . '">';
        echo esc_html__('Publish', 'griffinforms-form-builder');
        echo '</a>';
    }

    protected function signalsHeadingText($list_column)
    {
        echo '<span class="screen-reader-text">' . esc_html__('Signals', 'griffinforms-form-builder') . '</span>';
    }

    protected function signalsCellText($list_column, $item)
    {
        $signals = [];

        if ($this->formHasSubmissionEditSignal($item)) {
            $signals[] = sprintf(
                '<span class="gf-forms-signal gf-forms-signal-submission-edit" title="%s" aria-label="%s"><img src="%s" alt="" width="16" height="16" loading="lazy" decoding="async" /></span>',
                esc_attr__('Submission editing is currently available', 'griffinforms-form-builder'),
                esc_attr__('Submission editing is currently available', 'griffinforms-form-builder'),
                esc_url($this->config->getRootUrl() . 'admin/images/icons/submission-editability.svg')
            );
        }

        if ($this->formHasAccountsWorkflow($item)) {
            $signals[] = sprintf(
                '<span class="gf-forms-signal gf-forms-signal-accounts" title="%s" aria-label="%s"><img src="%s" alt="" width="16" height="16" loading="lazy" decoding="async" /></span>',
                esc_attr__('Runs user registration workflow', 'griffinforms-form-builder'),
                esc_attr__('Runs user registration workflow', 'griffinforms-form-builder'),
                esc_url($this->config->getRootUrl() . 'admin/images/icons/accounts.svg')
            );
        }

        $conditional_logic_count = $this->getConditionalLogicRulesCount($item);
        if ($conditional_logic_count > 0) {
            $signals[] = sprintf(
                '<span class="gf-forms-signal gf-forms-signal-conditional-logic" title="%s" aria-label="%s"><img src="%s" alt="" width="16" height="16" loading="lazy" decoding="async" /><sup class="gf-forms-signal-count">%d</sup></span>',
                esc_attr__('Conditional logic enabled', 'griffinforms-form-builder'),
                esc_attr__('Conditional logic enabled', 'griffinforms-form-builder'),
                esc_url($this->config->getRootUrl() . 'admin/images/icons/conditional_logic.svg'),
                absint($conditional_logic_count)
            );
        }

        if (empty($signals)) {
            echo '<span class="gf-forms-signal-placeholder" aria-hidden="true">—</span>';
            return;
        }

        echo '<div class="gf-forms-signals-wrap">';
        echo wp_kses_post(implode('', $signals));
        echo '</div>';
    }

    protected function formHasSubmissionEditSignal($item): bool
    {
        if (!\GriffinForms\Includes\Upsells\UpsellRegistry::getInstance()->isFeatureAdmitted('submission_editing')) {
            return false;
        }

        $form_id = absint($item->id ?? 0);
        if ($form_id <= 0) {
            return false;
        }

        if (isset($this->submission_edit_signal_cache[$form_id])) {
            return (bool) $this->submission_edit_signal_cache[$form_id];
        }

        $form = new \GriffinForms\Items\Form();
        $form->loadItem($form_id);
        $policy = $this->maybeDecode($form->getProp('submission_edit'));
        $enabled = is_array($policy) && !empty($policy['toggle']);

        if (!$enabled) {
            $this->submission_edit_signal_cache[$form_id] = false;
            return false;
        }

        if (!$this->hasSubmissionEditAccessMode($policy)) {
            $this->submission_edit_signal_cache[$form_id] = false;
            return false;
        }

        $time = isset($policy['time']) && is_array($policy['time']) ? $policy['time'] : array();
        $mode = isset($time['mode']) ? sanitize_key((string) $time['mode']) : 'none';

        if ($mode === 'window') {
            $now = current_time('timestamp', true);
            $start_ts = absint($time['start_ts'] ?? 0);
            $end_ts = absint($time['end_ts'] ?? 0);

            if ($start_ts > 0 && $now < $start_ts) {
                $this->submission_edit_signal_cache[$form_id] = false;
                return false;
            }

            if ($end_ts > 0 && $now > $end_ts) {
                $this->submission_edit_signal_cache[$form_id] = false;
                return false;
            }
        }

        $this->submission_edit_signal_cache[$form_id] = true;
        return true;
    }

    protected function hasSubmissionEditAccessMode(array $policy): bool
    {
        return !empty($policy['original_submitters'])
            || !empty($policy['email_owners'])
            || !empty($policy['role_access'])
            || !empty($policy['user_access']);
    }

    protected function getConditionalLogicRulesCount($item): int
    {
        $form_id = absint($item->id ?? 0);
        if ($form_id <= 0) {
            return 0;
        }

        if (isset($this->conditional_logic_counts[$form_id])) {
            return (int) $this->conditional_logic_counts[$form_id];
        }

        $form = new \GriffinForms\Items\Form();
        $form->loadItem($form_id);
        $count = method_exists($form, 'getRulesCount') ? (int) $form->getRulesCount() : 0;
        $this->conditional_logic_counts[$form_id] = $count;

        return $count;
    }
    
    protected function formpagesCellText($list_column, $item)
    {
        $formpages = $this->maybeDecode($item->formpages);
        $count = is_array($formpages) ? count($formpages) : 0;
        if ($count === 0) {
            echo '<span class="text-muted">—</span>';
        } else {
            echo '<span class="badge text-bg-secondary">' . absint($count) . '</span>';
        }
    }
    
    
    protected function submissionsCellText($list_column, $item)
    {
        if (isset($item->lifetime_submission_count) && is_numeric($item->lifetime_submission_count)) {
            $count = (int) $item->lifetime_submission_count;
        } else {
            $count = $this->sql->submissionCount($item->id);
        }
        if ($count == 0) {
            $count = '—'; // Show a dash when there are no submissions
        } else {
            // URL to the submissions page with the form ID filter
            $submissions_url = admin_url('admin.php?page=griffinforms-submissions&form_id=' . absint($item->id));

            // Make the count clickable, open in new tab, and add badge styling
            $count = '<a href="' . esc_url($submissions_url) . '" class="badge text-bg-primary text-decoration-none" target="_blank" rel="noopener noreferrer">' . esc_html($count) . '</a>';
        }

        echo wp_kses_post($count);
    }
    
    protected function folderCellText($list_column, $item)
    {
        $modal_id = $this->modal_ids['SelectFolder'] ?? 'griffinforms-selectfolder-modal';
        $folder_id = absint($item->folder ?? 0);
        $folder_name = $this->sql->getFormFolderName($item->id);
        $icon_file = 'default';

        if ($folder_id > 0) {
            $folder = $this->sql->itemValues($folder_id, 'folder', array('icon'));
            $icon_file = $folder && !empty($folder->icon) ? $folder->icon : 'default';
        }

        if ($icon_file) {
            $icon_url = esc_url($this->config->getRootUrl() . 'admin/images/folder/' . $icon_file . '.png');
            echo '<img src="' . esc_url($icon_url) . '" alt="" width="18" class="me-1 align-text-bottom" />';
        }

        echo '<a href="#" class="button-link gf-form-folder-link text-decoration-none"';
        echo ' data-bs-toggle="modal" data-bs-target="#' . esc_attr($modal_id) . '"';
        echo ' data-gf-form-id="' . absint($item->id) . '"';
        echo ' data-gf-current-folder-id="' . $folder_id . '">';
        if (strtolower($folder_name) === 'root') {
            echo '<span class="text-muted">' . esc_html($folder_name) . '</span>';
        } else {
            echo esc_html($folder_name);
        }
        echo '</a>';
    }

    protected function themeCellText($list_column, $item)
    {
        $theme_name = $this->sql->getFormThemeName($item->id);
        echo esc_html($theme_name);
    }

    protected function formHasAccountsWorkflow($item): bool
    {
        $raw = $item->integration_settings ?? '';
        $decoded = $this->maybeDecode($raw);

        if (!is_array($decoded)) {
            return false;
        }

        $accounts = isset($decoded['wordpress_accounts']) && is_array($decoded['wordpress_accounts'])
            ? $decoded['wordpress_accounts']
            : [];

        $settings = isset($accounts['settings']) && is_array($accounts['settings'])
            ? $accounts['settings']
            : [];

        $rules = isset($settings['rules']) && is_array($settings['rules'])
            ? $settings['rules']
            : [];

        foreach ($rules as $rule) {
            if (!is_array($rule)) {
                continue;
            }

            if (!empty($rule['enabled'])) {
                return true;
            }
        }

        return false;
    }

    protected function rowActionLayout($item)
    {
        $url = admin_url() . 'admin.php?page=griffinforms-app&form_id=' . $item->id;
        echo '<a href="' . esc_url($url) . '">' . esc_html($this->lang->getText('layout', 'row_action')) . '</a>'; 
    }

    protected function rowActionPreviewForm($item)
    {
        $modal_id = $this->modal_ids['PreviewForm'] ?? 'griffinforms-previewform-modal';
        echo '<a href="#" class="button-link gf-form-preview-link" data-bs-toggle="modal" data-bs-target="#' . esc_attr($modal_id) . '" data-gf-form-id="' . absint($item->id) . '">';
        echo esc_html__('Preview', 'griffinforms-form-builder');
        echo '</a>';
    }

    protected function rowActionAiedit($item)
    {
        $url = admin_url() . 'admin.php?page=griffinforms-app&form_id=' . absint($item->id) . '&mode=ai_draft';
        echo '<a href="' . esc_url($url) . '">' . esc_html__('AI Edit', 'griffinforms-form-builder') . '</a>';
    }

    protected function rowActionExport($item)
    {
        echo '<a class="griffinforms-formslist-export-btn" data-gf-formid="' . absint($item->id) . '">';
        echo  esc_html($this->lang->getText('Export', 'row_action'));
        echo '</a>'; 
    }

    protected function lasteditedHeadingText($list_column)
    {
        echo '<span>' . esc_html__('Last Edited', 'griffinforms-form-builder') . '</span>';
    }

    protected function idCellText($list_column, $item)
    {
        echo '<span class="badge text-bg-secondary">' . absint($item->id) . '</span>';
    }

    protected function descriptionCellText($list_column, $item)
    {
        $desc = trim((string) ($item->description ?? ''));
        if ($desc === '') {
            echo '<span class="text-muted">—</span>';
            return;
        }
        echo esc_html(mb_strimwidth($desc, 0, 60, '…'));
    }

    protected function statusCellText($list_column, $item)
    {
        $status = sanitize_key($item->status ?? 'published');
        $badge  = $status === 'published' ? 'text-bg-success' : 'text-bg-secondary';
        echo '<span class="badge ' . esc_attr($badge) . '">' . esc_html(ucfirst($status)) . '</span>';
    }

    protected function originCellText($list_column, $item)
    {
        $origin = sanitize_key($item->origin ?? 'local');
        echo '<span class="badge text-bg-secondary">' . esc_html(ucfirst($origin)) . '</span>';
    }

    protected function shortcodeCellText($list_column, $item)
    {
        echo '<pre class="p-1 mb-0 small">[griffinforms_form id=' . absint($item->id) . ']</pre>';
    }

    protected function complianceCellText($list_column, $item)
    {
        if (empty($item->compliance_mode)) {
            echo '<span class="text-muted">—</span>';
            return;
        }
        $profile = sanitize_key($item->compliance_profile ?? 'standard');
        echo '<span class="badge text-bg-secondary">' . esc_html(strtoupper($profile)) . '</span>';
    }

    protected function authorCellTextNicename($list_column, $item)
    {
        $user = get_user_by('id', $item->author ?? 0);
        echo $user ? esc_html($user->user_nicename) : '<span class="text-muted">—</span>';
    }

    protected function authorCellTextFullname($list_column, $item)
    {
        $user = get_user_by('id', $item->author ?? 0);
        if (!$user) {
            echo '<span class="text-muted">—</span>';
            return;
        }
        $full = trim($user->user_firstname . ' ' . $user->user_lastname);
        echo esc_html($full ?: $user->user_nicename);
    }

    protected function tableBody()
    {
        if (!empty($this->list_data)) {
            parent::tableBody();
            return;
        }

        if (!$this->onboarding_eligibility->shouldShowFormsEmptyStateCta()) {
            parent::tableBody();
            return;
        }

        $feature_flags = \GriffinForms\Includes\Onboarding\FeatureFlags::getInstance();
        $onboarding_url = $feature_flags->getOnboardingPageUrl([
            'entry_source' => 'forms_empty_state',
        ]);

        echo '<tr class="no-items">';
        echo '<td class="colspanchange" colspan="' . count($this->list_columns) . '">';
        echo '<div class="gf-onboarding-empty-state">';
        echo '<h2 class="gf-onboarding-empty-state-title">' . esc_html__('Create your first form', 'griffinforms-form-builder') . '</h2>';
        echo '<p class="gf-onboarding-empty-state-copy">' . esc_html__('You do not have any forms yet. Start with a guided setup, or open the existing form creator if you already know what you want to build.', 'griffinforms-form-builder') . '</p>';
        echo '<div class="gf-onboarding-empty-state-actions">';
        echo '<a class="button button-primary" href="' . esc_url($onboarding_url) . '">' . esc_html__('Guided setup', 'griffinforms-form-builder') . '</a>';
        echo '<button type="button" class="button button-secondary" data-bs-toggle="modal" data-bs-target="#griffinforms-createform-modal">' . esc_html__('Open form creator', 'griffinforms-form-builder') . '</button>';
        echo '</div>';
        echo '</div>';
        echo '</td></tr>';
    }
}
