<?php
defined('ABSPATH') || die();

// Add Initial Setup to create calendar categories in Termin-Kalender Plugin
//-------------------------------------------------------------------------------------
function termin_kalender_add_block_category_setup()
{
    //global $ter_kal_admin_pages_hook_suffixes;
    $page_title = esc_html__('Categories Setup', 'termin-kalender');
    $menu_title = $page_title;
    $capability = 'termin_kalender_edit';
    $menu_slug = 'terminkalender_category_setup';
    $callback = 'termin_kalender_render_initial_setup_admin_menu_page';

    Termin_Kalender_Plugin::$ter_kal_admin_pages_hook_suffixes[] = add_submenu_page(
        'termin-kalender',
        $page_title,
        $menu_title,
        $capability,
        $menu_slug,
        $callback,
    );
}
// add_action('admin_menu', 'termin_kalender_add_block_category_setup', 14);








function termin_kalender_render_initial_setup_admin_menu_page()
{
    // ter_kal_: Check user capabilities
    if (!current_user_can('termin_kalender_edit')) {
        return;
    }

    // ter_kal_: Check if PRO license exists
    $has_pro = defined('TERMIN_KALENDER_PRO_ON');

    // ter_kal_: Get current categories to show status
    $current_categories = json_decode(get_option('termin_kalender_kategorien', '[]'), true);
    $has_categories = is_array($current_categories) && count($current_categories) > 0;

    ?>
    <div class="wrap termin-kalender-admin-container ter-kal-initial-setup-page">
        <h2 class="termin-kalender-admin-page-title">
            <?php echo esc_html__('Smart Setup', 'termin-kalender'); ?> <span class="label label-free"
                style="vertical-align: middle; font-size: 14px; position: relative; top: -4px;">FREE</span>
        </h2>

        <!-- Inject existing categories and translations for JS -->
        <script>
            window.terminKalenderExistingCategories = <?php echo json_encode($current_categories); ?>;
            window.tkStrings = {
                newCategories: '<?php echo esc_js(__('Generated Categories', 'termin-kalender')); ?>',
                existingCategories: '<?php echo esc_js(__('Existing Categories', 'termin-kalender')); ?>'
            };
        </script>

        <div class="ter-kal-smart-setup-container">
            <div class="termin-kalender-admin-box-white ter-kal-generator-card"
                style="max-width: 900px; margin: 0 auto; padding: 35px;">
                <div class="card-header" style="text-align:center;">
                            <img src="<?php echo esc_url(plugins_url('assets/freemius-banner.png', dirname(__FILE__))); ?>"
                            alt="<?php esc_attr_e('Termin Kalender Logo', 'termin-kalender'); ?>"
                            style="max-width: 100%; border-radius: 8px;">
                </div>
                <div class="card-body">
                    <div class="ter-kal-ai-form"><br>
                        <h4 class="termin-kalender-admin-h3" style="margin-bottom: 5px;">
                            <?php echo esc_html__('Tell us what you\'re organizing', 'termin-kalender'); ?>
                        </h4>
                        <p class="termin-kalender-admin-text-muted" style="margin-bottom: 15px;">
                            <?php echo esc_html__('Describe your activities, services, or group in a few sentences. The more detail you provide — e.g. "Yoga studio with 3 instructors offering morning and evening classes" or "Community sports club with multiple teams and weekly training" — the better your calendar structure will be generated. No manual setup needed.', 'termin-kalender'); ?>
                        </p>

                        <style>
                            .ter-kal-inspiration-details summary::-webkit-details-marker {
                                display: none;
                            }
                            .ter-kal-inspiration-details summary {
                                list-style: none;
                            }
                        </style>
                        <details class="ter-kal-inspiration-details" style="margin-bottom: 15px; border: 1px solid #ccd0d4; border-radius: 4px; padding: 10px; background: #fafafa;">
                            <summary style="cursor: pointer; font-weight: 600; color: #2271b1; display: flex; align-items: center; gap: 5px; outline: none;">
                                <span class="dashicons dashicons-lightbulb" style="font-size: 18px; width: 18px; height: 18px; margin-top: 1px;"></span>
                                <?php echo esc_html__('Need inspiration?', 'termin-kalender'); ?>
                            </summary>
                            <div style="margin-top: 15px;">
                                <p class="termin-kalender-admin-text-muted" style="margin-bottom: 10px; margin-top: 0;">
                                    <?php echo esc_html__('Click a template to fill the box:', 'termin-kalender'); ?>
                                </p>
                                <div class="ter-kal-examples" style="display: flex; flex-wrap: wrap; gap: 8px;">
                                    <button class="ter-kal-example-btn button button-small"
                                        data-example="Law firm handling consultations, client meetings, court dates, document reviews, and mediation sessions. Keep green-gray light colors">Law
                                        Firm EN</button>
                                    <button class="ter-kal-example-btn button button-small"
                                        data-example="Anwaltskanzlei mit Beratungsgesprächen, Mandantenterminen, Gerichtsterminen, Dokumentenprüfungen und Mediationssitzungen. Farbpalette: seriöse Grün-Grau-Töne">Anwaltskanzlei
                                        DE</button>
                                    <button class="ter-kal-example-btn button button-small"
                                        data-example="Hair salon providing haircuts, coloring, styling, bridal services, consultations, and treatments.">Hair
                                        Salon EN</button>
                                    <button class="ter-kal-example-btn button button-small"
                                        data-example="Friseursalon mit Haarschnitten, Färbungen, Styling, Brautservice, Beratungen und Behandlungen. Farbpalette: moderne Pastell- und Rosétöne">Friseursalon
                                        DE</button>
                                    <button class="ter-kal-example-btn button button-small"
                                        data-example="Small resort offering room bookings, check-in/check-out, wellness treatments, restaurant reservations, and events. Color palette: Mediterranean blue and sand tones.">Resort
                                        EN</button>
                                    <button class="ter-kal-example-btn button button-small"
                                        data-example="Kleines Resort mit Zimmerbuchungen, Check-in/Check-out, Wellnessbehandlungen, Restaurant-Reservierungen und Veranstaltungen. Farbpalette: mediterrane Blau- und Sandtöne">Resort
                                        DE</button>
                                    <button class="ter-kal-example-btn button button-small"
                                        data-example="Studio de yoga proposant des cours pour débutants, des séances avancées, des leçons particulières, des ateliers, de la méditation et des événements spéciaux. Notre site web privilégie les tons orangés.">Yoga
                                        Studio FR</button>
                                    <button class="ter-kal-example-btn button button-small"
                                        data-example="Tierarztpraxis mit Sprechstunden, Impfungen, Operationen, Notfällen, Vorsorgeuntersuchungen und Hausbesuchen. Farbpalette: beruhigende Blau- und Grüntöne">Tierarztpraxis</button>
                                    <button class="ter-kal-example-btn button button-small"
                                        data-example="Fußballverein mit Trainingseinheiten, Meisterschaftsspielen, Jugendtraining, Vorstandssitzungen und Vereinsfesten. Vereinsfarben: Blau und Gelb">Fußballverein</button>
                                    <button class="ter-kal-example-btn button button-small"
                                        data-example="Zahnarztpraxis mit Kontrolluntersuchungen, Zahnreinigungen, Füllungen, Wurzelbehandlungen, Prophylaxe und Notfallterminen. Farbpalette: hygienische Weiß- und Hellblautöne">Zahnarztpraxis</button>
                                    <button class="ter-kal-example-btn button button-small"
                                        data-example="Physiotherapie-Praxis mit Krankengymnastik, Massagen, Manuelle Therapie, Lymphdrainage, Hausbesuchen und Reha-Maßnahmen. Farbpalette: vitale Grün- und Türkistöne">Physiotherapie</button>
                                    <button class="ter-kal-example-btn button button-small"
                                        data-example="Musikschule mit Klavierunterricht, Gitarrenkursen, Gesangsunterricht, Ensembleproben, Theoriestunden und Schülerkonzerten. Farbpalette: kreative Violett- und Orangetöne">Musikschule</button>
                                    <button class="ter-kal-example-btn button button-small"
                                        data-example="KFZ-Werkstatt mit Inspektionen, Reparaturen, Reifenwechsel, HU/AU-Terminen, Ölwechsel und Karosseriearbeiten. Farbpalette: kraftvolle Rot- und Schwarztöne">KFZ-Werkstatt</button>
                                    <button class="ter-kal-example-btn button button-small"
                                        data-example="Kosmetikstudio mit Gesichtsbehandlungen, Maniküre, Pediküre, Wimpernverlängerung, Make-up und Permanent Make-up. Farbpalette: elegante Rosa- und Goldtöne">Kosmetikstudio</button>
                                    <button class="ter-kal-example-btn button button-small"
                                        data-example="Fahrschule mit Theoriestunden, Fahrstunden, Prüfungsterminen, Intensivkursen, Aufbauseminaren und Motorradtraining. Farbpalette: signalhafte Gelb- und Rottöne">Fahrschule</button>
                                    <button class="ter-kal-example-btn button button-small"
                                        data-example="Nachhilfeschule mit Einzelunterricht, Gruppenkursen, Prüfungsvorbereitung, Ferienkursen, Sprachunterricht und Online-Stunden. Farbpalette: motivierende Blau- und Grüntöne">Nachhilfeschule</button>
                                    <button class="ter-kal-example-btn button button-small"
                                        data-example="Fitnessstudio mit Krafttraining, Cardio-Kursen, Personal Training, Yoga, Spinning und Ernährungsberatung. Farbpalette: energetische Rot- und Schwarztöne">Fitnessstudio</button>
                                    <button class="ter-kal-example-btn button button-small"
                                        data-example="Restaurant mit Tischreservierungen, Privatfeiern, Catering-Terminen, Weinverkostungen, Kochkursen und Geschäftsessen. Farbpalette: appetitliche Rot- und Brauntöne">Restaurant</button>
                                    <button class="ter-kal-example-btn button button-small"
                                        data-example="Steuerberater mit Beratungsgesprächen, Jahresabschlüssen, Steuererklärungen, Betriebsprüfungen, Existenzgründungsberatung und Quartalsabrechnungen. Farbpalette: vertrauensvolle Dunkelblau- und Grautöne">Steuerberater</button>
                                    <button class="ter-kal-example-btn button button-small"
                                        data-example="Reinigungsservice mit Büroreinigung, Fensterreinigung, Teppichreinigung, Grundreinigung, Umzugsreinigung und Industriereinigung. Farbpalette: saubere Blau- und Weißtöne">Reinigungsservice</button>
                                    <button class="ter-kal-example-btn button button-small"
                                        data-example="Fotografiestudio mit Portraitaufnahmen, Hochzeitsfotografie, Bewerbungsfotos, Produktfotografie, Familienfotos und Fotoshootings. Farbpalette: künstlerische Schwarz-Weiß- und Goldtöne">Fotografiestudio</button>
                                    <button class="ter-kal-example-btn button button-small"
                                        data-example="Tennisverein mit Trainingseinheiten, Medenrunden, Clubmeisterschaften, Schnupperkursen, Jugendtraining und Vereinsturnieren. Vereinsfarben: Weiß und Grün">Tennisverein</button>
                                    <button class="ter-kal-example-btn button button-small"
                                        data-example="Freiwillige Feuerwehr mit Übungsdiensten, Einsätzen, Schulungen, Jugendarbeit, Vorstandssitzungen und Vereinsfesten. Farbpalette: klassische Rot- und Goldtöne">Feuerwehr</button>
                                    <button class="ter-kal-example-btn button button-small"
                                        data-example="Schützenverein mit Schießtraining, Wettkämpfen, Vereinsversammlungen, Schützenfesten, Anfängerkursen und Meisterschaften. Vereinsfarben: Grün und Gold">Schützenverein</button>
                                    <button class="ter-kal-example-btn button button-small"
                                        data-example="Gesangsverein mit Chorproben, Konzerten, Auftritten, Stimmbildung, Registerterminen und geselligen Abenden. Farbpalette: harmonische Blau- und Silbertöne">Gesangsverein</button>
                                    <button class="ter-kal-example-btn button button-small"
                                        data-example="Kleingartenverein mit Parzellenvergabe, Arbeitseinsätzen, Gemeinschaftsveranstaltungen, Gartenfesten, Schulungen und Vorstandssitzungen. Farbpalette: natürliche Grün- und Brauntöne">Kleingartenverein</button>
                                    <button class="ter-kal-example-btn button button-small"
                                        data-example="Heilpraktiker-Praxis mit Erstgesprächen, Akupunktur, Homöopathie, Naturheilkunde, Ernährungsberatung und Therapiesitzungen. Farbpalette: heilende Grün- und Beige-Töne">Heilpraktiker</button>
                                    <button class="ter-kal-example-btn button button-small"
                                        data-example="Psychotherapie-Praxis mit Einzeltherapie, Paartherapie, Gruppentherapie, Erstgesprächen, Krisenintervention und Supervision. Farbpalette: beruhigende Blau- und Lavendeltöne">Psychotherapie</button>
                                    <button class="ter-kal-example-btn button button-small"
                                        data-example="Massagepraxis mit klassischer Massage, Sportmassage, Hot Stone, Thai-Massage, Reflexzonenmassage und Wellnessbehandlungen. Farbpalette: entspannende Sand- und Türkistöne">Massagepraxis</button>
                                    <button class="ter-kal-example-btn button button-small"
                                        data-example="Architekturbüro mit Beratungsgesprächen, Planungsterminen, Baustellenbegehungen, Präsentationen, Genehmigungsverfahren und Abnahmen. Farbpalette: professionelle Grau- und Blautöne">Architekturbüro</button>
                                    <button class="ter-kal-example-btn button button-small"
                                        data-example="Immobilienbüro mit Besichtigungsterminen, Beratungsgesprächen, Notarterminen, Bewertungen, Übergaben und Eigentumsversammlungen. Farbpalette: vertrauensvolle Blau- und Goldtöne">Immobilienbüro</button>
                                    <button class="ter-kal-example-btn button button-small"
                                        data-example="Werbeagentur mit Kundenterminen, Brainstormings, Präsentationen, Shootings, Projekt-Deadlines und Kreativmeetings. Farbpalette: kreative Bunt-Töne mit Akzenten">Werbeagentur</button>
                                </div>
                            </div>
                        </details>

                        <textarea id="ter-kal-business-description"
                            class="termin-kalender-admin-input-full ter-kal-business-input" rows="4" maxlength="800"
                            placeholder="<?php echo esc_attr__('e.g. I run a local football club with 3 teams and a clubhouse...', 'termin-kalender'); ?>"
                            style="border-radius: 8px; border: 2px solid #ccc; font-size: 16px; padding: 15px; box-sizing: border-box;"></textarea>

                        <div class="ter-kal-char-counter">
                            <span id="ter-kal-char-count">0</span> / 800
                            <?php echo esc_html__('characters', 'termin-kalender'); ?>
                        </div>

                        <div id="ter-kal-error-message" class="notice notice-error inline" style="display: none;">
                            <p></p>
                        </div>

                        <div class="ter-kal-actions"
                            style="margin-top:20px; display:flex; justify-content:space-between; align-items:center; flex-wrap: wrap; gap: 15px;">
                            <button id="ter-kal-generate-btn" class="button button-primary button-hero" type="button"
                                style="font-size: 16px; padding: 0 30px;">
                                <?php echo esc_html__('Generate my Categories', 'termin-kalender'); ?>
                            </button>

                            <div class="ter-kal-usage-info termin-kalender-admin-notice-info"
                                style="margin-top:0; padding: 10px;">
                                <?php if ($has_pro): ?>
                                    <span class="dashicons dashicons-yes-alt" style="color: #00a32a;"></span>
                                    <strong>PRO: </strong>
                                    <?php echo esc_html__('25 setups per day', 'termin-kalender'); ?>
                                <?php else: ?>
                                    <span class="dashicons dashicons-info"></span>
                                    <strong>Free: </strong>
                                    <?php echo esc_html__('3 setups per day', 'termin-kalender'); ?>
                                    •
                                    <a href="<?php echo esc_url(admin_url('admin.php?page=termin_kalender_setup&tab=pro_info')); ?>">
                                        <?php echo esc_html__('Upgrade to PRO', 'termin-kalender'); ?>
                                    </a>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>

                    <!-- ter_kal_: Results container -->
                    <div id="ter-kal-results" class="ter-kal-results" style="display: none; margin-top:40px;">
                        <hr style="margin-bottom:20px; border-top: 2px dashed #ccc;">
                        <h3 class="termin-kalender-admin-h2">
                            <?php echo esc_html__('Review your Categories', 'termin-kalender'); ?>
                        </h3>
                        <p class="termin-kalender-admin-text-muted" style="margin-bottom:20px;">
                            <?php echo esc_html__('Uncheck any category you don\'t need anymore. Unchecked categories will be deleted when you save.', 'termin-kalender'); ?>
                        </p>

                        <div style="display:flex; flex-wrap:wrap; gap:30px;">
                            <div style="flex:1; min-width:300px;">
                                <h4 style="color:#00a32a; border-bottom:1px solid #ccc; padding-bottom:5px;">
                                    <?php echo esc_html__('Generated Categories', 'termin-kalender'); ?>
                                </h4>
                                <div id="ter-kal-categories-display-new"
                                    style="display:flex; flex-direction:column; gap:8px; margin-top:10px;"></div>
                            </div>
                            <div style="flex:1; min-width:300px;">
                                <h4 style="color:#2271b1; border-bottom:1px solid #ccc; padding-bottom:5px;">
                                    <?php echo esc_html__('Existing Categories', 'termin-kalender'); ?>
                                </h4>
                                <div id="ter-kal-categories-display-existing"
                                    style="display:flex; flex-direction:column; gap:8px; margin-top:10px;"></div>
                            </div>
                        </div>

                        <div class="termin-kalender-admin-notice-info" style="margin-top: 15px;">
                            <p style="margin: 0; color:#50575e;">
                                <i>📌 <strong><?php echo esc_html__('Category Tip:', 'termin-kalender'); ?></strong>
                                    <?php echo esc_html__('You can edit these later at any time in the main calendar view. Just click a category button at the top to open the edit window. On your live website, visitors can also click these buttons to show or hide specific categories.', 'termin-kalender'); ?>
                                </i>
                            </p>
                        </div>

                        <div class="ter-kal-result-actions" style="margin-top: 30px;">
                            <button type="button" id="ter-kal-apply-btn" class="button button-primary button-hero"
                                style="font-size: 16px;">
                                <?php echo esc_html__('Save & Go to Calendar', 'termin-kalender'); ?>
                            </button>
                            <button type="button" id="ter-kal-regenerate-btn" class="button button-secondary button-hero"
                                style="font-size: 16px;">
                                <?php echo esc_html__('Regenerate Categories', 'termin-kalender'); ?>
                            </button>
                        </div>
                        <div id="ter-kal-remaining-requests" class="ter-kal-remaining"
                            style="display: none; margin-top:15px;">
                            <span class="dashicons dashicons-backup termin-kalender-admin-icon-inline"></span>
                            <span id="ter-kal-remaining-count"></span>
                        </div>
                        <div id="ter-kal-recommendation-display" class="termin-kalender-admin-notice-info"
                            style="margin-top:20px; display: none;">Empfehlungen</div>
                    </div>

                </div>
            </div>
        </div>

        <style>
            /* ter_kal_: Initial Setup Page Styles */
            .ter-kal-initial-setup-page .card-row {
                display: grid;
                grid-template-columns: 1fr 1fr;
                gap: 20px;
                margin-top: 20px;
                max-width: 1200px;
            }

            .ter-kal-generator-card,
            .ter-kal-info-card {
                background: #fff;
                border: 1px solid #ccd0d4;
                border-radius: 4px;
                box-shadow: 0 1px 1px rgba(0, 0, 0, .04);
            }

            .ter-kal-business-input {
                width: 100%;
                padding: 12px;
                border: 1px solid #ddd;
                border-radius: 4px;
                font-size: 14px;
                font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
                resize: vertical;
                margin-top: 8px;
            }

            .ter-kal-char-counter {
                text-align: right;
                font-size: 12px;
                color: #666;
                margin-top: 4px;
            }

            .ter-kal-actions {
                margin-top: 20px;
            }

            .ter-kal-usage-info {
                margin-top: 12px;
                padding: 10px;
                background: #f0f6fc;
                border-left: 3px solid #2271b1;
                font-size: 13px;
            }

            .ter-kal-usage-info .dashicons {
                vertical-align: middle;
                margin-right: 4px;
            }

            .ter-kal-results {
                margin-top: 20px;
            }

            #ter-kal-categories-display {
                display: grid;
                grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
                gap: 10px;
                margin: 15px 0;
            }

            .ter-kal-category-preview {
                display: flex;
                align-items: center;
                gap: 10px;
                padding: 12px 16px;
                border-radius: 4px;
                font-weight: 500;
                font-size: 14px;
            }

            .ter-kal-category-preview .dashicons {
                width: 20px;
                height: 20px;
                font-size: 20px;
            }

            .ter-kal-result-actions {
                display: flex;
                gap: 10px;
                margin-top: 15px;
            }

            .ter-kal-remaining {
                margin-top: 10px;
                padding: 8px;
                background: #f0f0f0;
                border-radius: 4px;
                font-size: 13px;
                color: #666;
            }

            .ter-kal-steps {
                padding-left: 0;
                list-style: none;
            }

            .ter-kal-steps li {
                margin-bottom: 20px;
                padding-left: 40px;
                position: relative;
            }

            .ter-kal-steps .dashicons {
                position: absolute;
                left: 0;
                top: 0;
                width: 30px;
                height: 30px;
                font-size: 30px;
                color: #2271b1;
            }

            .ter-kal-steps p {
                margin: 5px 0 0 0;
                color: #666;
                font-size: 13px;
            }

            .ter-kal-tips {
                padding-left: 20px;
                font-size: 13px;
            }

            .ter-kal-tips li {
                margin-bottom: 8px;
                color: #666;
            }

            .ter-kal-examples {
                display: flex;
                flex-wrap: wrap;
                gap: 8px;
            }

            .ter-kal-example-btn {
                font-size: 12px;
            }

            #ter-kal-error-message p {
                margin: 0.5em 0;
            }

            .button-success {
                background: #00a32a !important;
                border-color: #00a32a !important;
                color: #fff !important;
            }

            /* ter_kal_: Category selection wrapper */
            .ter-kal-category-wrapper {
                display: flex;
                align-items: center;
                gap: 8px;
            }

            .ter-kal-category-checkbox {
                margin: 0;
                cursor: pointer;
            }

            .ter-kal-category-preview {
                flex: 1;
                cursor: pointer;
                transition: opacity 0.2s;
            }

            .ter-kal-category-wrapper:has(.ter-kal-category-checkbox:not(:checked)) .ter-kal-category-preview {
                opacity: 0.4;
            }

            .ter-kal-category-wrapper:has(.ter-kal-category-checkbox:not(:checked)) .ter-kal-category-preview:hover {
                opacity: 0.6;
            }

            /* AI Generation Progress Indicator */
            .ter-kal-ai-progress {
                margin-top: 10px;
                margin-bottom: 10px;
            }

            .ter-kal-progress-bar {
                width: 100%;
                height: 8px;
                background-color: #e0e0e0;
                border-radius: 4px;
                overflow: hidden;
                margin-bottom: 8px;
            }

            .ter-kal-progress-fill {
                height: 100%;
                background: linear-gradient(90deg, #2271b1, #135e96);
                width: 0%;
                transition: width 0.3s ease;
                border-radius: 4px;
            }

            .ter-kal-progress-status {
                font-size: 13px;
                color: #646970;
                font-style: italic;
            }


            @media (max-width: 1200px) {
                .ter-kal-initial-setup-page .card-row {
                    grid-template-columns: 1fr;
                }
            }
        </style>

        <script>
            (function () {
                'use strict';

                // ter_kal_: Configuration
                const SERVICE_URL = '<?php echo esc_url(rest_url('termin-kalender-ai/v1/send-to-service')); ?>';
                //const SERVICE_URL = 'https://termin-kalender.pro/wp-json/termin-kalender-ai/v1/calendar-categories';
                const APPLY_URL = '<?php echo esc_url(rest_url('termin-kalender-ai/v1/apply-categories')); ?>';
                const REST_NONCE = '<?php echo esc_js(wp_create_nonce('wp_rest')); ?>';


                // ter_kal_: localStorage persistence (NEW)
                const ter_kal_ls_prefix = 'ter_kal_initial_setup_';
                const ter_kal_ls_keys = {
                    description: ter_kal_ls_prefix + 'business_description',
                    categories_json: ter_kal_ls_prefix + 'categories_json',
                    recommendation_html: ter_kal_ls_prefix + 'recommendation_html',
                    results_visible: ter_kal_ls_prefix + 'results_visible',
                    remaining_requests: ter_kal_ls_prefix + 'remaining_requests'
                };

                // ter_kal_: Safe JSON parse helper (NEW)
                const ter_kal_safe_json_parse = (value, fallback) => {
                    try {
                        const parsed = JSON.parse(value);
                        return parsed !== null ? parsed : fallback;
                    } catch (e) {
                        return fallback;
                    }
                };

                // ter_kal_: Persist description on typing (NEW)
                // NOTE: call this after you define `textarea`
                const ter_kal_bind_description_persist = () => {
                    if (!textarea) {
                        return;
                    }

                    textarea.addEventListener('input', function () {
                        try {
                            localStorage.setItem(ter_kal_ls_keys.description, textarea.value || '');
                        } catch (e) {
                            // Ignore quota/security errors
                        }
                    });
                };

                // ter_kal_: Restore UI from localStorage (NEW)
                // NOTE: call this after you define DOM refs: textarea, resultsDiv, categoriesDisplay, recommendationDisplay, remainingDiv, remainingCount
                const ter_kal_restore_from_localstorage = () => {
                    let has_restored_anything = false;

                    // Restore description
                    try {
                        const saved_desc = localStorage.getItem(ter_kal_ls_keys.description);
                        if (saved_desc && textarea && !textarea.value) {
                            textarea.value = saved_desc;
                            has_restored_anything = true;

                            // If you have a char counter update function, call it here (kept generic)
                            // ter_kal_: use existing charCount reference if present (CHANGE)
                            if (charCount) {
                                charCount.textContent = String(saved_desc.length);
                            }
                        }
                    } catch (e) { }

                    // Restore categories (preferred: regenerate DOM via displayCategories)
                    try {
                        const saved_categories_json = localStorage.getItem(ter_kal_ls_keys.categories_json);
                        if (saved_categories_json) {
                            const saved_categories = ter_kal_safe_json_parse(saved_categories_json, []);
                            if (Array.isArray(saved_categories) && saved_categories.length) {
                                currentCategories = saved_categories; // uses your existing variable
                                // ter_kal_: do not auto-scroll on restore (CHANGE)
                                displayCategories(currentCategories, { noScroll: true });  // uses your existing function
                                has_restored_anything = true;
                            }
                        }
                    } catch (e) { }

                    // Restore recommendation HTML
                    try {
                        const saved_reco_html = localStorage.getItem(ter_kal_ls_keys.recommendation_html);
                        if (saved_reco_html && recommendationDisplay) {
                            recommendationDisplay.innerHTML = saved_reco_html;
                            recommendationDisplay.style.display = 'block';
                            has_restored_anything = true;
                        }
                    } catch (e) { }

                    // Restore remaining requests
                    try {
                        const saved_remaining = localStorage.getItem(ter_kal_ls_keys.remaining_requests);
                        if (saved_remaining !== null && remainingDiv && remainingCount) {
                            remainingCount.textContent = '<?php echo esc_js(__('Remaining today:', 'termin-kalender')); ?> ' + saved_remaining;
                            remainingDiv.style.display = 'block';
                        }
                    } catch (e) { }

                    // Ensure results are visible if we restored generated output
                    try {
                        const saved_visible = localStorage.getItem(ter_kal_ls_keys.results_visible);
                        if ((saved_visible === '1' || has_restored_anything) && resultsDiv) {
                            // displayCategories() already shows results, but keep as fallback
                            resultsDiv.style.display = 'block';
                        }
                    } catch (e) { }

                    // ter_kal_: Ensure apply button reflects restored selection state (CHANGE)
                    try {
                        updateApplyButtonText();
                    } catch (e) { }
                };




                // ter_kal_: DOM elements
                const textarea = document.getElementById('ter-kal-business-description');
                const charCount = document.getElementById('ter-kal-char-count');
                const generateBtn = document.getElementById('ter-kal-generate-btn');
                const applyBtn = document.getElementById('ter-kal-apply-btn');
                const regenerateBtn = document.getElementById('ter-kal-regenerate-btn');
                const errorDiv = document.getElementById('ter-kal-error-message');
                const resultsDiv = document.getElementById('ter-kal-results');
                const categoriesDisplayNew = document.getElementById('ter-kal-categories-display-new');
                const categoriesDisplayExisting = document.getElementById('ter-kal-categories-display-existing');
                const recommendationDisplay = document.getElementById('ter-kal-recommendation-display');
                // ter_kal_: Avoid overwriting restored recommendation later (CHANGE)
                if (recommendationDisplay && !recommendationDisplay.innerHTML) {
                    recommendationDisplay.innerHTML = '<br>Empfehlung<br>';
                }
                const remainingDiv = document.getElementById('ter-kal-remaining-requests');
                const remainingCount = document.getElementById('ter-kal-remaining-count');

                // ter_kal_: Basic safety guard (NEW) - avoid JS fatal errors if markup changes
                if (!textarea || !charCount || !generateBtn || !applyBtn || !regenerateBtn || !errorDiv || !resultsDiv || !categoriesDisplayNew || !categoriesDisplayExisting || !recommendationDisplay || !remainingDiv || !remainingCount) {
                    return;
                }

                let currentCategories = []; // ter_kal_: moved BEFORE restore so restore won't get overwritten (FIX)

                // ter_kal_: Bind localStorage persistence for textarea (NEW)
                ter_kal_bind_description_persist();






                // ter_kal_: Character counter
                textarea.addEventListener('input', function () {
                    const length = this.value.length;
                    charCount.textContent = length;

                    if (length > 800) {
                        charCount.style.color = '#d63638';
                    } else if (length > 700) {
                        charCount.style.color = '#dba617';
                    } else {
                        charCount.style.color = '#666';
                    }
                });

                // ter_kal_: Example buttons
                document.querySelectorAll('.ter-kal-example-btn').forEach(btn => {
                    btn.addEventListener('click', function () {
                        textarea.value = this.dataset.example;
                        textarea.dispatchEvent(new Event('input'));
                        textarea.focus();
                    });
                });

                // ter_kal_: Show error
                function showError(message) {
                    errorDiv.querySelector('p').textContent = message;
                    errorDiv.style.display = 'block';
                }

                // ter_kal_: Clear error
                function clearError() {
                    errorDiv.style.display = 'none';
                }

                // ter_kal_: Generate categories
                generateBtn.addEventListener('click', async function () {
                    clearError();
                    const description = textarea.value.trim();

                    if (!description) {
                        showError('<?php echo esc_js(__('Please describe your business first.', 'termin-kalender')); ?>');
                        textarea.focus();
                        return;
                    }

                    if (description.length > 800) {
                        showError('<?php echo esc_js(__('Description too long (max 800 characters).', 'termin-kalender')); ?>');
                        return;
                    }

                    //--------------------------------------------------------------

                    generateBtn.disabled = true;
                    const originalBtnText = generateBtn.textContent;

                    // Create progress container
                    const progressContainer = document.createElement('div');
                    progressContainer.className = 'ter-kal-ai-progress';
                    progressContainer.innerHTML = `
                        <div class="ter-kal-progress-bar">
                            <div class="ter-kal-progress-fill"></div>
                        </div>
                        <div class="ter-kal-progress-status"><?php echo esc_js(__('Initializing...', 'termin-kalender')); ?></div>
                    `;
                    generateBtn.parentNode.insertBefore(progressContainer, generateBtn.nextSibling);

                    const progressFill = progressContainer.querySelector('.ter-kal-progress-fill');
                    const progressStatus = progressContainer.querySelector('.ter-kal-progress-status');

                    // Helper to update progress with smooth animation
                    const updateProgress = (percent, message) => {
                        progressFill.style.transition = 'width 0.3s ease';
                        progressFill.style.width = percent + '%';
                        progressStatus.textContent = message;
                    };
                    // Simulate progress during long operations
                    let progressInterval = null;
                    const simulateProgress = (startPercent, endPercent, duration, message) => {
                        return new Promise((resolve) => {
                            let currentPercent = startPercent;
                            const step = (endPercent - startPercent) / (duration / 100);

                            progressStatus.textContent = message;

                            progressInterval = setInterval(() => {
                                currentPercent += step;
                                if (currentPercent >= endPercent) {
                                    currentPercent = endPercent;
                                    clearInterval(progressInterval);
                                    progressInterval = null;
                                    resolve();
                                }
                                progressFill.style.width = currentPercent + '%';
                            }, 100);
                        });
                    };

                    const stopSimulation = () => {
                        if (progressInterval) {
                            clearInterval(progressInterval);
                            progressInterval = null;
                        }
                    };
                    updateProgress(5, '<?php echo esc_js(__('Connecting to AI service...', 'termin-kalender')); ?>');
                    await new Promise(resolve => setTimeout(resolve, 300));
                    try {

                                /*                        // Update progress and WAIT for browser to repaint
                                                        updateProgress(60, '<?php echo esc_js(__('Sending & Receiving data...', 'termin-kalender')); ?>');*/
                        // Start simulating progress from 20% to 75% while waiting for response
                        const progressPromise = simulateProgress(
                            8,
                            88,
                            30000, // 30 seconds max (adjust based on typical response time)
                            '<?php echo esc_js(__('Sending and Receiving data...', 'termin-kalender')); ?>'
                        );
                        // Give browser time to update UI (even 0ms works because it yields control)
                        //await new Promise(resolve => setTimeout(resolve, 50))

                        const response = await fetch(SERVICE_URL, {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-WP-Nonce': REST_NONCE
                            },
                            body: JSON.stringify({
                                description: description,
                            })
                        });

                        // Stop the simulation when response arrives
                        stopSimulation();
                        updateProgress(92, '<?php echo esc_js(__('Processing response...', 'termin-kalender')); ?>');
                        await new Promise(resolve => setTimeout(resolve, 300));

                        const data = await response.json();

                        updateProgress(96, '<?php echo esc_js(__('Finalizing...', 'termin-kalender')); ?>');
                        await new Promise(resolve => setTimeout(resolve, 200));

                        if (!response.ok) {
                            showError(data.message || '<?php echo esc_js(__('Generation failed. Please try again.', 'termin-kalender')); ?>');
                            return;
                        }

                        currentCategories = data.categories || [];

                        // ter_kal_: Display recommendation text if present


                        const recText = data.recommendationHtml || data.recommendationText;

                        if (recText) {
                            // Strip attributes from allowed tags, remove all other tags
                            const clean = recText
                                .replace(/<(\/?(br|strong|em|b|i|p))\s[^>]*>/gi, '<$1>')
                                .replace(/<(?!\/?(?:br|strong|em|b|i|p)\b)[^>]+>/gi, '');
                            //console.log('recText:', recText);
                            //console.log('clean:', clean);
                            recommendationDisplay.innerHTML =
                                '<p><strong><?php echo esc_js(__('Recommendation:', 'termin-kalender')); ?> </strong>' +
                                clean + '</p>';
                            recommendationDisplay.style.display = 'block';
                        }

                        //console.log('RAW data:', data);

                        displayCategories(currentCategories);


                        // ter_kal_: Persist generated results to localStorage (NEW)
                        try {
                            localStorage.setItem(ter_kal_ls_keys.description, description || '');
                            localStorage.setItem(ter_kal_ls_keys.categories_json, JSON.stringify(currentCategories || []));
                            localStorage.setItem(ter_kal_ls_keys.recommendation_html, recommendationDisplay ? (recommendationDisplay.innerHTML || '') : '');
                            localStorage.setItem(ter_kal_ls_keys.results_visible, '1');

                            if (data.remaining_requests !== undefined && data.remaining_requests !== null) {
                                localStorage.setItem(ter_kal_ls_keys.remaining_requests, String(data.remaining_requests));
                            }
                        } catch (e) {
                            // Ignore quota/security errors
                        }

                        if (data.remaining_requests !== undefined) {
                            remainingCount.textContent = '<?php echo esc_js(__('Remaining today:', 'termin-kalender')); ?> ' + data.remaining_requests;
                            remainingDiv.style.display = 'block';
                        }

                        updateProgress(100, '<?php echo esc_js(__('Complete!', 'termin-kalender')); ?>');

                        // Remove progress after short delay
                        setTimeout(() => {
                            progressContainer.remove();
                        }, 500);

                    } catch (error) {
                        stopSimulation();
                        showError('<?php echo esc_js(__('Network error. Please check your connection.', 'termin-kalender')); ?>');
                        // Clean up on error
                        progressContainer.remove();
                        generateBtn.disabled = false;
                        generateBtn.textContent = originalBtnText;
                    } finally {
                        generateBtn.disabled = false;
                        generateBtn.textContent = '<?php echo esc_js(__('Generate Categories', 'termin-kalender')); ?>';
                    }

                    //--------------------------------------------------------------

                });

                // ter_kal_: Display generated categories (MODIFIED to allow selection and bulk management)
                // ter_kal_: Added optional options param to avoid scroll on restore (CHANGE)
                function displayCategories(categories, options) {
                    categoriesDisplayNew.innerHTML = '';
                    categoriesDisplayExisting.innerHTML = '';

                    const createCatElement = (cat, index, isExisting) => {
                        const wrapper = document.createElement('div');
                        wrapper.className = 'ter-kal-category-wrapper';

                        const checkbox = document.createElement('input');
                        checkbox.type = 'checkbox';
                        checkbox.id = (isExisting ? 'ter-kal-cat-exist-' : 'ter-kal-cat-new-') + index;
                        checkbox.className = 'ter-kal-category-checkbox ' + (isExisting ? 'ter-kal-category-existing' : 'ter-kal-category-new');
                        checkbox.dataset.index = index;
                        checkbox.checked = true; // ter_kal_: Pre-select all by default

                        const label = document.createElement('label');
                        label.htmlFor = checkbox.id;
                        label.className = 'ter-kal-category-preview';
                        label.style.backgroundColor = cat.backgroundColor || '#2271b1';
                        label.style.color = cat.textColor || '#ffffff';

                        const icon = document.createElement('span');
                        icon.className = 'dashicons ' + (cat.icon || 'dashicons-calendar');
                        icon.setAttribute('aria-hidden', 'true');

                        const text = document.createElement('span');
                        text.textContent = cat.label || 'Unbenannt';

                        label.appendChild(icon);
                        label.appendChild(text);

                        wrapper.appendChild(checkbox);
                        wrapper.appendChild(label);
                        return wrapper;
                    };

                    // Render AI categories
                    categories.forEach((cat, index) => {
                        categoriesDisplayNew.appendChild(createCatElement(cat, index, false));
                    });

                    // Render Existing Categories
                    if (window.terminKalenderExistingCategories && Array.isArray(window.terminKalenderExistingCategories)) {
                        window.terminKalenderExistingCategories.forEach((cat, index) => {
                            categoriesDisplayExisting.appendChild(createCatElement(cat, index, true));
                        });
                    }

                    resultsDiv.style.display = 'block';

                    // ter_kal_: Do not scroll on restore (CHANGE)
                    if (!options || !options.noScroll) {
                        resultsDiv.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
                    }

                    // ter_kal_: Update apply button text with selected count
                    updateApplyButtonText();
                }

                // ter_kal_: Update apply button based on selection (NEW)
                function updateApplyButtonText() {
                    const checkboxes = document.querySelectorAll('.ter-kal-category-checkbox');
                    const selectedCount = Array.from(checkboxes).filter(cb => cb.checked).length;

                    if (selectedCount === 0) {
                        applyBtn.disabled = true;
                        applyBtn.textContent = '<?php echo esc_js(__('Select categories to save', 'termin-kalender')); ?>';
                    } else {
                        applyBtn.disabled = false;
                        applyBtn.textContent = '<?php echo esc_js(__('Save {count} Categories to Calendar', 'termin-kalender')); ?>'.replace('{count}', selectedCount);
                    }
                }

                // ter_kal_: Listen for checkbox changes (ADD after displayCategories function)
                document.addEventListener('change', function (e) {
                    if (e.target.classList.contains('ter-kal-category-checkbox')) {
                        updateApplyButtonText();
                    }
                });

                // ter_kal_: Restore from localStorage on page load (FIX)
                // IMPORTANT: must be AFTER currentCategories exists and displayCategories() is available.
                ter_kal_restore_from_localstorage();

                // ter_kal_: Apply categories (MODIFIED to perform bulk overwrite 'replace')
                applyBtn.addEventListener('click', async function () {
                    // Collect selected new categories
                    const newCheckboxes = document.querySelectorAll('.ter-kal-category-new:checked');
                    const selectedNewCategories = Array.from(newCheckboxes).map(cb =>
                        currentCategories[parseInt(cb.dataset.index, 10)]
                    );

                    // Collect selected existing categories
                    const existingCheckboxes = document.querySelectorAll('.ter-kal-category-existing:checked');
                    const selectedExistingCategories = Array.from(existingCheckboxes).map(cb =>
                        window.terminKalenderExistingCategories[parseInt(cb.dataset.index, 10)]
                    );

                    // Merge them together for the save payload
                    const combinedCategories = [...selectedExistingCategories, ...selectedNewCategories];

                    if (!combinedCategories.length) return;

                    const confirmMsg = '<?php echo esc_js(__('This will REPLACE your current categories with the {count} selected ones. Unchecked demo categories will be deleted. Proceed?', 'termin-kalender')); ?>'.replace('{count}', combinedCategories.length);

                    if (!confirm(confirmMsg)) {
                        return;
                    }

                    applyBtn.disabled = true;
                    const oldText = applyBtn.textContent;
                    applyBtn.textContent = '<?php echo esc_js(__('Saving...', 'termin-kalender')); ?>';

                    try {
                        const response = await fetch(APPLY_URL, {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-WP-Nonce': REST_NONCE
                            },
                            body: JSON.stringify({
                                categories: combinedCategories,
                                mode: 'replace' // ter_kal_: Signal to backend to replace completely
                            })
                        });

                        const data = await response.json();

                        if (!response.ok) {
                            alert(data.message || '<?php echo esc_js(__('Failed to add categories.', 'termin-kalender')); ?>');
                            return;
                        }

                        applyBtn.textContent = '✓ <?php echo esc_js(__('Added!', 'termin-kalender')); ?>';
                        applyBtn.className = 'button button-large button-success';

                        // ter_kal_: Persist orphan count to localStorage so the notice
                        // survives the redirect and is shown on the admin calendar page.
                        var orphaned = (data && data.orphaned_count) ? parseInt(data.orphaned_count, 10) : 0;
                        if (orphaned > 0) {
                            try {
                                localStorage.setItem('ter_kal_pending_orphan_notice', String(orphaned));
                            } catch (e) { /* Ignore quota/security errors */ }
                        }

                        setTimeout(() => {
                            // ter_kal_: Clear ONLY generated categories after successful apply to prevent duplicates
                            try {
                                localStorage.removeItem(ter_kal_ls_keys.categories_json);
                                localStorage.removeItem(ter_kal_ls_keys.remaining_requests);
                                // Wir behalten bewusst description und recommendation_html im localstorage!
                            } catch (e) { }
                            // Redirect zurück zum Kalender für den optimalen Flow
                            window.location.href = '<?php echo esc_url(admin_url('admin.php?page=termin-kalender')); ?>';
                        }, 1500);

                    } catch (error) {
                        alert('<?php echo esc_js(__('Network error. Please try again.', 'termin-kalender')); ?>');
                        applyBtn.disabled = false;
                        applyBtn.textContent = oldText;
                    }
                });

                // ter_kal_: Regenerate (scroll to prompt to modify input, keep results visible until new generation)
                regenerateBtn.addEventListener('click', function (e) {
                    e.preventDefault();
                    textarea.focus();
                    textarea.scrollIntoView({ behavior: 'smooth', block: 'center' });
                });

                // Initialize display immediately so existing categories are always manageable
                displayCategories(currentCategories, { noScroll: true });

            })();
        </script>

    </div>
    <?php
}
