<?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;

use APD\PostTypes\ThemePostType;
use APD\Support\RequestData;
use APD\Theme\DesignerTheme;

defined('ABSPATH') || exit;

final class ThemePage
{
    private ?\WP_Post $editingPost = null;

    public function redirectLegacy() : never
    {
        wp_safe_redirect(admin_url('edit.php?post_type=' . ThemePostType::TYPE));
        exit;
    }

    public function registerMetaBoxes(\WP_Post $post) : void
    {
        add_meta_box(
            'apd_theme_designer',
            __('Theme appearance', 'asuka-product-designer'),
            [$this, 'renderMetaBox'],
            ThemePostType::TYPE,
            'normal',
            'high'
        );
    }

    public function renderMetaBox(\WP_Post $post) : void
    {
        $this->editingPost = $post;
        $this->render();
        $this->editingPost = null;
    }

    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'));
        }
        if (! $this->editingPost instanceof \WP_Post) {
            $this->redirectLegacy();
        }

        $service = new DesignerTheme();
        $isCptEditor = $this->editingPost instanceof \WP_Post;
        $library = $service->library();
        $defaultThemeId = $service->defaultThemeId();
        $query = RequestData::query();
        $requestedThemeId = $isCptEditor
            ? (string) $this->editingPost->ID
            : sanitize_key((string) ($query['theme_id'] ?? ''));
        $themeId = $isCptEditor || isset($library[$requestedThemeId]) ? $requestedThemeId : $defaultThemeId;
        $draft = $service->draft($themeId);
        $published = $service->published($themeId);
        $presets = DesignerTheme::presets();
        $sections = DesignerTheme::sections();
        $tokens = DesignerTheme::tokens();
        $settings = (new AdminSettings())->all();
        $isDirty = $this->themeSignature($draft) !== $this->themeSignature($published);
        $sectionGroups = [];
        foreach ($tokens as $token => $definition) {
            $section = (string) $definition['section'];
            $group = (string) $definition['group'];
            $sectionGroups[$section][$group][$token] = $definition;
        }
        ?>
        <div class="<?php echo $isCptEditor ? 'apd-theme-cpt-editor ' : 'wrap '; ?>apd-admin-shell apd-admin-theme-<?php echo esc_attr((string) $settings['admin_theme']); ?> apd-theme-studio" data-apd-theme-studio <?php echo $isCptEditor ? 'data-apd-theme-cpt-editor' : ''; ?>>
            <?php if (! $isCptEditor) : ?>
            <section class="apd-theme-library" aria-labelledby="apd-theme-library-title">
                <header class="apd-theme-library__header">
                    <div>
                        <span class="apd-dashboard-eyebrow"><?php esc_html_e('Reusable visual systems', 'asuka-product-designer'); ?></span>
                        <h1 id="apd-theme-library-title"><?php esc_html_e('Theme library', 'asuka-product-designer'); ?></h1>
                        <p><?php esc_html_e('Create branded themes once, then assign them globally or to individual products and templates.', 'asuka-product-designer'); ?></p>
                    </div>
                    <a class="button button-secondary" href="<?php echo esc_url(admin_url('admin.php?page=apd-settings#apd-default-designer-theme')); ?>">
                        <span class="dashicons dashicons-admin-settings" aria-hidden="true"></span>
                        <?php esc_html_e('Choose store default', 'asuka-product-designer'); ?>
                    </a>
                </header>

                <div class="apd-theme-library__grid">
                    <?php foreach ($library as $libraryThemeId => $libraryTheme) : ?>
                        <?php
                        $libraryThemeColors = (array) ($libraryTheme['colors'] ?? []);
                        $libraryThemeUsage = $service->usageCount((string) $libraryThemeId);
                        $libraryThemeDraft = $service->draft((string) $libraryThemeId);
                        $hasDraftChanges = $this->themeSignature($libraryThemeDraft) !== $this->themeSignature($libraryTheme);
                        ?>
                        <a class="apd-theme-library-card <?php echo $libraryThemeId === $themeId ? 'is-active' : ''; ?>" href="<?php echo esc_url(add_query_arg(['page' => 'apd-theme', 'theme_id' => $libraryThemeId], admin_url('admin.php'))); ?>" style="--theme-card-bg: <?php echo esc_attr((string) ($libraryThemeColors['layout.appBg'] ?? '#f5f7fb')); ?>; --theme-card-panel: <?php echo esc_attr((string) ($libraryThemeColors['layout.panelBg'] ?? '#ffffff')); ?>; --theme-card-text: <?php echo esc_attr((string) ($libraryThemeColors['text.primary'] ?? '#0f172a')); ?>; --theme-card-accent: <?php echo esc_attr((string) ($libraryThemeColors['accent.primary'] ?? '#2563eb')); ?>;">
                            <span class="apd-theme-library-card__preview"><i></i><i></i><i></i></span>
                            <span class="apd-theme-library-card__body">
                                <span class="apd-theme-library-card__name">
                                    <strong><?php echo esc_html((string) ($libraryTheme['name'] ?? $libraryThemeId)); ?></strong>
                                    <?php if ($libraryThemeId === $defaultThemeId) : ?><em><?php esc_html_e('Default', 'asuka-product-designer'); ?></em><?php endif; ?>
                                </span>
                                <small><?php echo esc_html(sprintf(/* translators: Placeholder values are populated from the current administration record. */ _n('%d assignment', '%d assignments', $libraryThemeUsage, 'asuka-product-designer'), $libraryThemeUsage)); ?><?php echo $hasDraftChanges ? ' · ' . esc_html__('Draft changes', 'asuka-product-designer') : ''; ?></small>
                            </span>
                            <span class="dashicons dashicons-arrow-right-alt2" aria-hidden="true"></span>
                        </a>
                    <?php endforeach; ?>

                    <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" class="apd-theme-library-create">
                        <?php wp_nonce_field('apd_save_designer_theme'); ?>
                        <input type="hidden" name="action" value="apd_save_designer_theme">
                        <input type="hidden" name="apd_theme_intent" value="create">
                        <span class="dashicons dashicons-plus-alt2" aria-hidden="true"></span>
                        <div><strong><?php esc_html_e('Create a theme', 'asuka-product-designer'); ?></strong><small><?php esc_html_e('Start clean from any curated foundation.', 'asuka-product-designer'); ?></small></div>
                        <label><span class="screen-reader-text"><?php esc_html_e('Theme name', 'asuka-product-designer'); ?></span><input type="text" name="apd_theme_name" maxlength="80" required placeholder="<?php echo esc_attr__('Theme name', 'asuka-product-designer'); ?>"></label>
                        <label><span class="screen-reader-text"><?php esc_html_e('Foundation', 'asuka-product-designer'); ?></span><select name="apd_theme_preset"><?php foreach ($presets as $presetId => $preset) : ?><option value="<?php echo esc_attr((string) $presetId); ?>"><?php echo esc_html((string) $preset['label']); ?></option><?php endforeach; ?></select></label>
                        <button type="submit" class="button button-primary"><?php esc_html_e('Create theme', 'asuka-product-designer'); ?></button>
                    </form>
                </div>
            </section>
            <?php endif; ?>

            <?php if (! $isCptEditor) : ?>
                <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" data-apd-theme-form>
                <?php wp_nonce_field('apd_save_designer_theme'); ?>
                <input type="hidden" name="action" value="apd_save_designer_theme">
            <?php else : ?>
                <?php wp_nonce_field('apd_save_designer_theme_' . $themeId, 'apd_theme_nonce'); ?>
            <?php endif; ?>
                <input type="hidden" name="apd_theme_id" value="<?php echo esc_attr($themeId); ?>">
                <input type="hidden" name="apd_theme_payload" value="" data-apd-theme-payload>

                <script type="application/json" data-apd-theme-draft><?php echo wp_json_encode($draft, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_UNESCAPED_SLASHES); ?></script>
                <script type="application/json" data-apd-theme-published><?php echo wp_json_encode($published, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_UNESCAPED_SLASHES); ?></script>
                <script type="application/json" data-apd-theme-presets><?php echo wp_json_encode($presets, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_UNESCAPED_SLASHES); ?></script>

                <header class="apd-theme-studio__header">
                    <div class="apd-theme-studio__heading">
                        <span class="apd-dashboard-eyebrow"><?php esc_html_e('Visual system', 'asuka-product-designer'); ?></span>
                        <div class="apd-theme-studio__title-row">
                            <h2><?php echo esc_html($isCptEditor ? __('Theme configuration', 'asuka-product-designer') : (string) $draft['name']); ?></h2>
                            <?php if ($themeId === $defaultThemeId) : ?><span class="apd-theme-default-badge"><?php esc_html_e('Store default', 'asuka-product-designer'); ?></span><?php endif; ?>
                            <span class="apd-theme-status <?php echo $isDirty ? 'is-draft' : 'is-published'; ?>" data-apd-theme-status>
                                <span aria-hidden="true"></span>
                                <?php echo esc_html($isDirty ? __('Unpublished changes', 'asuka-product-designer') : __('Published', 'asuka-product-designer')); ?>
                            </span>
                        </div>
                        <p><?php esc_html_e('Choose a foundation, refine its tokens, then use the standard WordPress Publish or Update action to save this theme.', 'asuka-product-designer'); ?></p>
                    </div>
                    <div class="apd-theme-studio__header-actions">
                        <?php if (! $isCptEditor) : ?>
                        <button type="submit" class="button button-secondary" name="apd_theme_intent" value="duplicate">
                            <span class="dashicons dashicons-admin-page" aria-hidden="true"></span>
                            <?php esc_html_e('Duplicate', 'asuka-product-designer'); ?>
                        </button>
                        <button type="submit" class="button button-secondary apd-theme-delete-button" name="apd_theme_intent" value="delete" <?php disabled(count($library) <= 1 || $themeId === $defaultThemeId || $service->usageCount($themeId) > 0); ?> data-apd-confirm="<?php echo esc_attr__('Delete this theme? This cannot be undone.', 'asuka-product-designer'); ?>" title="<?php echo esc_attr($themeId === $defaultThemeId ? __('Choose another store default before deleting this theme.', 'asuka-product-designer') : ($service->usageCount($themeId) > 0 ? __('Remove this theme from every product and template before deleting it.', 'asuka-product-designer') : __('Delete theme', 'asuka-product-designer'))); ?>">
                            <span class="dashicons dashicons-trash" aria-hidden="true"></span>
                            <?php esc_html_e('Delete', 'asuka-product-designer'); ?>
                        </button>
                        <?php endif; ?>
                        <div class="apd-theme-history-actions" aria-label="<?php echo esc_attr__('Theme history', 'asuka-product-designer'); ?>">
                            <button type="button" class="button button-secondary button-icon" data-apd-theme-undo disabled title="<?php echo esc_attr__('Undo theme change', 'asuka-product-designer'); ?>">
                                <span class="dashicons dashicons-undo" aria-hidden="true"></span><span class="screen-reader-text"><?php esc_html_e('Undo', 'asuka-product-designer'); ?></span>
                            </button>
                            <button type="button" class="button button-secondary button-icon" data-apd-theme-redo disabled title="<?php echo esc_attr__('Redo theme change', 'asuka-product-designer'); ?>">
                                <span class="dashicons dashicons-redo" aria-hidden="true"></span><span class="screen-reader-text"><?php esc_html_e('Redo', 'asuka-product-designer'); ?></span>
                            </button>
                        </div>
                        <?php if (! $isCptEditor) : ?>
                        <button type="submit" class="button button-secondary" name="apd_theme_intent" value="draft">
                            <?php esc_html_e('Save draft', 'asuka-product-designer'); ?>
                        </button>
                        <button type="submit" class="button button-primary" name="apd_theme_intent" value="publish">
                            <span class="dashicons dashicons-cloud-upload" aria-hidden="true"></span>
                            <?php esc_html_e('Publish theme', 'asuka-product-designer'); ?>
                        </button>
                        <?php endif; ?>
                    </div>
                </header>

                <section class="apd-theme-identity" aria-labelledby="apd-theme-foundation-title">
                    <div class="apd-theme-identity__copy">
                        <span class="apd-theme-step">01</span>
                        <div>
                            <h2 id="apd-theme-foundation-title"><?php esc_html_e('Choose a visual foundation', 'asuka-product-designer'); ?></h2>
                            <p><?php esc_html_e('Start from a curated family, then tune every token without losing a coherent baseline.', 'asuka-product-designer'); ?></p>
                        </div>
                    </div>
                    <?php if (! $isCptEditor) : ?><label class="apd-theme-name-field">
                        <span><?php esc_html_e('Theme name', 'asuka-product-designer'); ?></span>
                        <input type="text" value="<?php echo esc_attr((string) $draft['name']); ?>" maxlength="80" data-apd-theme-name>
                    </label><?php endif; ?>
                </section>

                <div class="apd-theme-presets" role="radiogroup" aria-label="<?php echo esc_attr__('Theme presets', 'asuka-product-designer'); ?>">
                    <?php foreach ($presets as $presetId => $preset) : ?>
                        <?php $presetColors = (array) $preset['colors']; ?>
                        <label class="apd-theme-preset <?php echo $draft['preset'] === $presetId ? 'is-active' : ''; ?>" data-apd-theme-preset-card="<?php echo esc_attr($presetId); ?>">
                            <input type="radio" name="apd_theme_preset_preview" value="<?php echo esc_attr($presetId); ?>" <?php checked($draft['preset'], $presetId); ?> data-apd-theme-preset>
                            <span class="apd-theme-preset__preview" style="--preset-bg: <?php echo esc_attr((string) $presetColors['layout.appBg']); ?>; --preset-panel: <?php echo esc_attr((string) $presetColors['layout.panelBg']); ?>; --preset-text: <?php echo esc_attr((string) $presetColors['text.primary']); ?>; --preset-accent: <?php echo esc_attr((string) $presetColors['accent.primary']); ?>;">
                                <span></span><span></span><span></span><span></span>
                            </span>
                            <span class="apd-theme-preset__content">
                                <strong><?php echo esc_html((string) $preset['label']); ?></strong>
                                <small><?php echo esc_html((string) $preset['description']); ?></small>
                            </span>
                            <span class="apd-theme-preset__check dashicons dashicons-yes-alt" aria-hidden="true"></span>
                        </label>
                    <?php endforeach; ?>
                </div>

                <div class="apd-theme-editor">
                    <aside class="apd-theme-editor__nav">
                        <div class="apd-theme-search">
                            <span class="dashicons dashicons-search" aria-hidden="true"></span>
                            <input type="search" placeholder="<?php echo esc_attr__('Search colors and tokens', 'asuka-product-designer'); ?>" data-apd-theme-search>
                            <button type="button" data-apd-theme-search-clear hidden title="<?php echo esc_attr__('Clear search', 'asuka-product-designer'); ?>">
                                <span class="dashicons dashicons-no-alt" aria-hidden="true"></span>
                            </button>
                        </div>
                        <nav aria-label="<?php echo esc_attr__('Theme sections', 'asuka-product-designer'); ?>">
                            <?php $firstSection = true; ?>
                            <?php foreach ($sections as $sectionId => $section) : ?>
                                <?php $sectionCount = count(array_filter($tokens, static fn(array $token) : bool => $token['section'] === $sectionId)); ?>
                                <button type="button" class="apd-theme-section-link <?php echo $firstSection ? 'is-active' : ''; ?>" data-apd-theme-section-link="<?php echo esc_attr($sectionId); ?>">
                                    <span class="dashicons dashicons-<?php echo esc_attr((string) $section['icon']); ?>" aria-hidden="true"></span>
                                    <span><strong><?php echo esc_html((string) $section['label']); ?></strong><small><?php echo esc_html((string) $section['description']); ?></small></span>
                                    <em><?php echo esc_html((string) $sectionCount); ?></em>
                                </button>
                                <?php $firstSection = false; ?>
                            <?php endforeach; ?>
                        </nav>
                        <div class="apd-theme-editor__nav-tools">
                            <button type="button" class="button button-secondary" data-apd-theme-restore-published>
                                <span class="dashicons dashicons-backup" aria-hidden="true"></span>
                                <?php esc_html_e('Restore published', 'asuka-product-designer'); ?>
                            </button>
                            <button type="button" class="button button-link" data-apd-theme-reset-all><?php esc_html_e('Reset preset', 'asuka-product-designer'); ?></button>
                        </div>
                    </aside>

                    <main class="apd-theme-editor__tokens">
                        <div class="apd-theme-editor__toolbar">
                            <div>
                                <span class="apd-theme-step">02</span>
                                <div><h2><?php esc_html_e('Refine the system', 'asuka-product-designer'); ?></h2><p><?php esc_html_e('Every value maps directly to a supported AsukaDesigner runtime token.', 'asuka-product-designer'); ?></p></div>
                            </div>
                            <button type="button" class="button button-secondary" data-apd-theme-generate-palette>
                                <span class="dashicons dashicons-admin-customizer" aria-hidden="true"></span>
                                <?php esc_html_e('Build from primary', 'asuka-product-designer'); ?>
                            </button>
                        </div>

                        <?php $firstSection = true; ?>
                        <?php foreach ($sections as $sectionId => $section) : ?>
                            <section class="apd-theme-token-section" data-apd-theme-section="<?php echo esc_attr($sectionId); ?>" <?php echo $firstSection ? '' : 'hidden'; ?>>
                                <header>
                                    <div><h3><?php echo esc_html((string) $section['label']); ?></h3><p><?php echo esc_html((string) $section['description']); ?></p></div>
                                    <button type="button" class="button button-link" data-apd-theme-reset-section="<?php echo esc_attr($sectionId); ?>"><?php esc_html_e('Reset section', 'asuka-product-designer'); ?></button>
                                </header>
                                <?php foreach ((array) ($sectionGroups[$sectionId] ?? []) as $groupLabel => $groupTokens) : ?>
                                    <div class="apd-theme-token-group" data-apd-theme-token-group>
                                        <div class="apd-theme-token-group__title">
                                            <strong><?php echo esc_html((string) $groupLabel); ?></strong>
                                            <span><?php echo esc_html(sprintf(/* translators: Placeholder values are populated from the current administration record. */ _n('%d token', '%d tokens', count($groupTokens), 'asuka-product-designer'), count($groupTokens))); ?></span>
                                        </div>
                                        <div class="apd-theme-token-list">
                                            <?php foreach ($groupTokens as $token => $definition) : ?>
                                                <?php $value = (string) ($draft['colors'][$token] ?? ''); ?>
                                                <div class="apd-theme-token" data-apd-theme-token-row data-apd-theme-token="<?php echo esc_attr($token); ?>" data-apd-theme-search-text="<?php echo esc_attr(strtolower($token . ' ' . $definition['label'] . ' ' . $definition['description'] . ' ' . $groupLabel)); ?>">
                                                    <div class="apd-theme-token__copy">
                                                        <strong><?php echo esc_html((string) $definition['label']); ?></strong>
                                                        <small><?php echo esc_html((string) $definition['description']); ?></small>
                                                        <code><?php echo esc_html($token); ?></code>
                                                    </div>
                                                    <div class="apd-theme-token__control">
                                                        <label class="apd-theme-color-swatch" style="--token-color: <?php echo esc_attr($value); ?>;" title="<?php echo esc_attr__('Choose color', 'asuka-product-designer'); ?>">
                                                            <input type="color" value="<?php echo esc_attr($this->colorInputValue($value)); ?>" data-apd-theme-picker="<?php echo esc_attr($token); ?>">
                                                            <span></span>
                                                        </label>
                                                        <input type="text" value="<?php echo esc_attr($value); ?>" spellcheck="false" autocomplete="off" data-apd-theme-color="<?php echo esc_attr($token); ?>" aria-label="<?php echo esc_attr(sprintf(/* translators: Placeholder values are populated from the current administration record. */ __('Color for %s', 'asuka-product-designer'), $definition['label'])); ?>">
                                                        <button type="button" class="button button-secondary button-icon" data-apd-theme-reset-token="<?php echo esc_attr($token); ?>" title="<?php echo esc_attr__('Reset token', 'asuka-product-designer'); ?>">
                                                            <span class="dashicons dashicons-image-rotate" aria-hidden="true"></span><span class="screen-reader-text"><?php esc_html_e('Reset token', 'asuka-product-designer'); ?></span>
                                                        </button>
                                                    </div>
                                                </div>
                                            <?php endforeach; ?>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </section>
                            <?php $firstSection = false; ?>
                        <?php endforeach; ?>

                        <div class="apd-theme-search-empty" data-apd-theme-search-empty hidden>
                            <span class="dashicons dashicons-search" aria-hidden="true"></span>
                            <strong><?php esc_html_e('No theme token matches this search', 'asuka-product-designer'); ?></strong>
                            <button type="button" class="button button-link" data-apd-theme-search-empty-clear><?php esc_html_e('Clear search', 'asuka-product-designer'); ?></button>
                        </div>
                    </main>

                    <aside class="apd-theme-preview-column">
                        <div class="apd-theme-preview-panel">
                            <header>
                                <div><span class="apd-theme-step">03</span><div><h2><?php esc_html_e('Live preview', 'asuka-product-designer'); ?></h2><p data-apd-theme-preview-label><?php esc_html_e('Editing draft', 'asuka-product-designer'); ?></p></div></div>
                                <div class="apd-theme-preview-modes" role="group" aria-label="<?php echo esc_attr__('Preview size', 'asuka-product-designer'); ?>">
                                    <button type="button" class="is-active" data-apd-theme-preview-mode="desktop" title="<?php echo esc_attr__('Desktop preview', 'asuka-product-designer'); ?>"><span class="dashicons dashicons-desktop" aria-hidden="true"></span></button>
                                    <button type="button" data-apd-theme-preview-mode="mobile" title="<?php echo esc_attr__('Mobile preview', 'asuka-product-designer'); ?>"><span class="dashicons dashicons-smartphone" aria-hidden="true"></span></button>
                                </div>
                            </header>

                            <div class="apd-theme-preview" data-apd-theme-preview>
                                <div class="apd-theme-preview__shell">
                                    <div class="apd-theme-preview__topbar">
                                        <span class="apd-theme-preview__brand"><i></i><i></i></span>
                                        <div><span></span><span></span><span></span></div>
                                    </div>
                                    <div class="apd-theme-preview__body">
                                        <nav class="apd-theme-preview__sidebar">
                                            <button class="is-active" type="button"><span class="dashicons dashicons-screenoptions" aria-hidden="true"></span><small><?php esc_html_e('Views', 'asuka-product-designer'); ?></small></button>
                                            <button type="button"><span class="dashicons dashicons-format-image" aria-hidden="true"></span><small><?php esc_html_e('Images', 'asuka-product-designer'); ?></small></button>
                                            <button type="button"><span class="dashicons dashicons-editor-textcolor" aria-hidden="true"></span><small><?php esc_html_e('Text', 'asuka-product-designer'); ?></small></button>
                                        </nav>
                                        <div class="apd-theme-preview__workarea">
                                            <div class="apd-theme-preview__toolbar">
                                                <span><?php esc_html_e('Zoom: 100%', 'asuka-product-designer'); ?></span>
                                                <div><button type="button"><span class="dashicons dashicons-undo" aria-hidden="true"></span></button><button type="button"><span class="dashicons dashicons-redo" aria-hidden="true"></span></button></div>
                                            </div>
                                            <div class="apd-theme-preview__stage">
                                                <div class="apd-theme-preview__product"><span></span><span></span><strong>ASUKA</strong></div>
                                            </div>
                                            <div class="apd-theme-preview__thumbnails">
                                                <small><?php esc_html_e('Views', 'asuka-product-designer'); ?></small>
                                                <button type="button" class="is-active"><span>1</span></button><button type="button"><span>2</span></button>
                                            </div>
                                        </div>
                                        <aside class="apd-theme-preview__panel">
                                            <header><strong><?php esc_html_e('Edit design', 'asuka-product-designer'); ?></strong><small><?php esc_html_e('Selected layer', 'asuka-product-designer'); ?></small></header>
                                            <label><span><?php esc_html_e('Name', 'asuka-product-designer'); ?></span><input type="text" placeholder="<?php echo esc_attr__('Your artwork', 'asuka-product-designer'); ?>"></label>
                                            <div class="apd-theme-preview__states"><i class="is-success"></i><i class="is-warning"></i><i class="is-danger"></i></div>
                                            <button type="button" class="is-primary"><?php esc_html_e('Apply changes', 'asuka-product-designer'); ?></button>
                                            <button type="button" class="is-secondary"><?php esc_html_e('Duplicate layer', 'asuka-product-designer'); ?></button>
                                            <button type="button" class="is-ghost"><?php esc_html_e('More options', 'asuka-product-designer'); ?></button>
                                        </aside>
                                    </div>
                                </div>
                            </div>

                            <div class="apd-theme-contrast" aria-label="<?php echo esc_attr__('Contrast checks', 'asuka-product-designer'); ?>">
                                <div data-apd-theme-contrast="content"><span></span><strong>--</strong><small><?php esc_html_e('Content', 'asuka-product-designer'); ?></small></div>
                                <div data-apd-theme-contrast="primary"><span></span><strong>--</strong><small><?php esc_html_e('Primary action', 'asuka-product-designer'); ?></small></div>
                                <div data-apd-theme-contrast="input"><span></span><strong>--</strong><small><?php esc_html_e('Input', 'asuka-product-designer'); ?></small></div>
                            </div>
                            <button type="button" class="button button-secondary apd-theme-compare" data-apd-theme-compare>
                                <span class="dashicons dashicons-visibility" aria-hidden="true"></span>
                                <?php esc_html_e('Compare published theme', 'asuka-product-designer'); ?>
                            </button>
                        </div>
                    </aside>
                </div>

                <section class="apd-theme-portability">
                    <div class="apd-theme-portability__intro">
                        <span class="apd-theme-step">04</span>
                        <div><h2><?php esc_html_e('Move the visual system safely', 'asuka-product-designer'); ?></h2><p><?php esc_html_e('Export a portable JSON theme, duplicate it across stores, or inspect the exact runtime payload before publishing.', 'asuka-product-designer'); ?></p></div>
                    </div>
                    <div class="apd-theme-portability__actions">
                        <button type="button" class="button button-secondary" data-apd-theme-copy><span class="dashicons dashicons-clipboard" aria-hidden="true"></span><?php esc_html_e('Copy JSON', 'asuka-product-designer'); ?></button>
                        <button type="button" class="button button-secondary" data-apd-theme-export><span class="dashicons dashicons-download" aria-hidden="true"></span><?php esc_html_e('Export file', 'asuka-product-designer'); ?></button>
                        <label class="button button-secondary apd-theme-import-button"><span class="dashicons dashicons-upload" aria-hidden="true"></span><?php esc_html_e('Import file', 'asuka-product-designer'); ?><input type="file" accept="application/json,.json" data-apd-theme-import></label>
                    </div>
                    <details class="apd-theme-json-details">
                        <summary><?php esc_html_e('Advanced JSON editor', 'asuka-product-designer'); ?></summary>
                        <div><textarea rows="12" spellcheck="false" data-apd-theme-json></textarea><button type="button" class="button button-secondary" data-apd-theme-apply-json><?php esc_html_e('Apply JSON to draft', 'asuka-product-designer'); ?></button></div>
                    </details>
                </section>

                <?php if (! $isCptEditor) : ?><footer class="apd-theme-savebar">
                    <div>
                        <span class="apd-theme-status <?php echo $isDirty ? 'is-draft' : 'is-published'; ?>" data-apd-theme-status><span aria-hidden="true"></span><?php echo esc_html($isDirty ? __('Unpublished changes', 'asuka-product-designer') : __('Published', 'asuka-product-designer')); ?></span>
                        <small data-apd-theme-change-summary><?php echo esc_html($this->publishedSummary($published)); ?></small>
                    </div>
                    <div><button type="submit" class="button button-secondary" name="apd_theme_intent" value="draft"><?php esc_html_e('Save draft', 'asuka-product-designer'); ?></button><button type="submit" class="button button-primary" name="apd_theme_intent" value="publish"><?php esc_html_e('Publish theme', 'asuka-product-designer'); ?></button></div>
                </footer><?php endif; ?>
            <?php if (! $isCptEditor) : ?></form><?php endif; ?>
        </div>
        <?php
    }

    public function savePost(int $postId, \WP_Post $post, bool $update) : void
    {
        if (
            $post->post_type !== ThemePostType::TYPE
            || wp_is_post_autosave($postId)
            || wp_is_post_revision($postId)
            || ! current_user_can('manage_asuka_designer')
        ) {
            return;
        }

        $request = RequestData::post();
        $nonce = sanitize_text_field((string) ($request['apd_theme_nonce'] ?? ''));
        if ($nonce === '' || ! wp_verify_nonce($nonce, 'apd_save_designer_theme_' . $postId)) {
            return;
        }

        $payload = json_decode((string) ($request['apd_theme_payload'] ?? ''), true);
        if (! is_array($payload)) {
            return;
        }

        (new DesignerTheme())->savePostPayload($postId, $payload);
    }

    public function columns(array $columns) : array
    {
        return [
            'cb' => $columns['cb'] ?? '<input type="checkbox">',
            'title' => __('Theme', 'asuka-product-designer'),
            'apd_theme_preview' => __('Preview', 'asuka-product-designer'),
            'apd_theme_preset' => __('Foundation', 'asuka-product-designer'),
            'apd_theme_default' => __('Store default', 'asuka-product-designer'),
            'apd_theme_usage' => __('Assignments', 'asuka-product-designer'),
            'date' => $columns['date'] ?? __('Date', 'asuka-product-designer'),
        ];
    }

    public function renderColumn(string $column, int $postId) : void
    {
        $service = new DesignerTheme();
        $theme = $service->draft((string) $postId);
        if ($column === 'apd_theme_preview') {
            $colors = (array) ($theme['colors'] ?? []);
            printf(
                '<span class="apd-theme-list-preview" style="--theme-bg:%1$s;--theme-panel:%2$s;--theme-accent:%3$s" aria-hidden="true"><i></i><i></i><i></i></span>',
                esc_attr((string) ($colors['layout.appBg'] ?? '#f5f7fb')),
                esc_attr((string) ($colors['layout.panelBg'] ?? '#ffffff')),
                esc_attr((string) ($colors['accent.primary'] ?? '#2563eb'))
            );
            return;
        }
        if ($column === 'apd_theme_preset') {
            $preset = (string) ($theme['preset'] ?? 'light');
            $presets = DesignerTheme::presets();
            echo esc_html((string) ($presets[$preset]['label'] ?? $preset));
            return;
        }
        if ($column === 'apd_theme_default') {
            echo $service->defaultThemeId() === (string) $postId
                ? '<span class="apd-theme-list-default">' . esc_html__('Default', 'asuka-product-designer') . '</span>'
                : '<span aria-hidden="true">&mdash;</span>';
            return;
        }
        if ($column === 'apd_theme_usage') {
            $count = $service->usageCount((string) $postId);
            echo esc_html(sprintf(/* translators: Placeholder values are populated from the current administration record. */ _n('%d item', '%d items', $count, 'asuka-product-designer'), $count));
        }
    }

    public function rowActions(array $actions, \WP_Post $post) : array
    {
        if ($post->post_type !== ThemePostType::TYPE) {
            return $actions;
        }

        unset($actions['view'], $actions['inline hide-if-no-js']);
        $service = new DesignerTheme();
        $isPublished = $post->post_status === 'publish';
        if (
            $service->defaultThemeId() === (string) $post->ID
            || $service->usageCount((string) $post->ID) > 0
            || ($isPublished && count($service->library()) <= 1)
        ) {
            unset($actions['trash'], $actions['delete']);
        }
        return $actions;
    }

    public function guardTrash(int $postId) : void
    {
        if (get_post_type($postId) !== ThemePostType::TYPE) {
            return;
        }
        $service = new DesignerTheme();
        if ($service->defaultThemeId() === (string) $postId) {
            wp_die(esc_html__('Choose another default theme in Settings before moving this theme to Trash.', 'asuka-product-designer'));
        }
        if ($service->usageCount((string) $postId) > 0) {
            wp_die(esc_html__('Reassign every product and template before moving this theme to Trash.', 'asuka-product-designer'));
        }
        if (get_post_status($postId) === 'publish' && count($service->library()) <= 1) {
            wp_die(esc_html__('The final published theme cannot be moved to Trash.', 'asuka-product-designer'));
        }
    }

    private function themeSignature(array $theme) : string
    {
        return (string) wp_json_encode([
            'name' => (string) ($theme['name'] ?? ''),
            'preset' => (string) ($theme['preset'] ?? ''),
            'colors' => (array) ($theme['colors'] ?? []),
        ]);
    }

    private function publishedSummary(array $published) : string
    {
        $updatedAt = trim((string) ($published['updatedAt'] ?? ''));
        if ($updatedAt === '') {
            return __('Using the built-in Asuka Light theme.', 'asuka-product-designer');
        }
        $timestamp = strtotime($updatedAt . ' UTC');
        return $timestamp
            ? sprintf(/* translators: Placeholder values are populated from the current administration record. */ __('Last published %s.', 'asuka-product-designer'), wp_date(get_option('date_format') . ' ' . get_option('time_format'), $timestamp))
            : __('A custom theme is published.', 'asuka-product-designer');
    }

    private function colorInputValue(string $value) : string
    {
        if (preg_match('/^#([0-9a-f]{6})$/i', trim($value), $match)) {
            return '#' . strtolower($match[1]);
        }
        if (preg_match('/^#([0-9a-f]{3})$/i', trim($value), $match)) {
            return '#' . strtolower($match[1][0] . $match[1][0] . $match[1][1] . $match[1][1] . $match[1][2] . $match[1][2]);
        }
        if (preg_match('/^rgba?\(\s*([0-9.]+)[, ]+([0-9.]+)[, ]+([0-9.]+)/i', trim($value), $match)) {
            return sprintf('#%02x%02x%02x', min(255, (int) round((float) $match[1])), min(255, (int) round((float) $match[2])), min(255, (int) round((float) $match[3])));
        }
        return '#2563eb';
    }
}
