<?php

use Components\Base;
use Components\Button;
use Components\Dropdown;
use Components\Router;


function mb_normalize_status(string $status): string {
    $status = strtolower(trim($status));
    return ($status === 'simulate') ? 'simulate' : 'production';
}

// Helper: get current status from legacy configuration, then constant, then default
function mb_get_status(): string {
    $keys = ['MAILBEEZ_MAILHIVE_MODE'];

    if (function_exists('mh_cfg')) {
        foreach ($keys as $key) {
            $s = (string) mh_cfg($key, '');
            if ($s !== '') {
                return mb_normalize_status(strtolower($s));
            }
        }
    }

    foreach ($keys as $key) {
        if (defined($key)) {
            return mb_normalize_status(strtolower((string) constant($key)));
        }
    }

    return 'production';
}

// Handle HTMX POST to update status in legacy configuration
if (mh_server('REQUEST_METHOD', 'GET') === 'POST' && mh_post('status') !== null) {
    $new = mb_normalize_status(strtolower(trim((string) mh_post('status', '', 'string'))));

    try {
        if (function_exists('mh_update_config_value')) {
            mh_update_config_value([
                    'configuration_key'   => 'MAILBEEZ_MAILHIVE_MODE',
                    'configuration_value' => $new,
            ]);

            if (function_exists('mh_cfg_override_set')) {
                // Ensure immediate consistency for current request if cache is used
                mh_cfg_override_set('MAILBEEZ_MAILHIVE_MODE', $new);
            }
        }
    } catch (\Throwable $e) {
        // ignore; we still render component with current effective status
    }
}

$status = mb_get_status();
$statusStyles = [
        'production' => [
                'label' => (string) mh_lng('MAILBEEZ_MODE_STATUS_PRODUCTION_LABEL', 'Production'),
                'description' => (string) mh_lng('MAILBEEZ_MODE_STATUS_PRODUCTION_DESCRIPTION', 'Live sending enabled.'),
                'bgMain' => 'bg-green-600/80 dark:bg-green-500/70   hover:bg-green-600/80 dark:hover:bg-green-400',
                'iconChip' => 'bg-green-200/20 dark:bg-green-300/35',
                'outline' => 'focus-visible:outline-green-400 dark:focus-visible:outline-green-400',
                'optionFocus' => 'focus:bg-green-600/70 focus:text-white dark:focus:bg-green-500',
                'optionCheck' => 'text-green-500 dark:text-green-400',
                'optionDescriptionFocus' => 'group-focus/option:text-green-100 dark:group-focus/option:text-green-100',
        ],
        'simulate' => [
                'label' => (string) mh_lng('MAILBEEZ_MODE_STATUS_SIMULATION_LABEL', 'Simulation'),
                'description' => (string) mh_lng('MAILBEEZ_MODE_STATUS_SIMULATION_DESCRIPTION', 'No live sending. Safe test mode.'),
                'bgMain' => 'bg-orange-600/80 dark:bg-orange-500/70 hover:bg-orange-500/80 dark:hover:bg-orange-400',
                'iconChip' => 'bg-orange-200/20 dark:bg-orange-300/40',
                'outline' => 'focus-visible:outline-orange-400 dark:focus-visible:outline-orange-400',
                'optionFocus' => 'focus:bg-orange-500/70 focus:text-white dark:focus:bg-orange-500',
                'optionCheck' => 'text-orange-400 dark:text-orange-400',
                'optionDescriptionFocus' => 'group-focus/option:text-orange-100 dark:group-focus/option:text-orange-100',
        ],
];
$statusIcons = [
        'production' => Base::SVG_OUTLINE_PLAY,
        'simulate' => Base::SVG_OUTLINE_PAUSE,
];
$currentStyle = $statusStyles[$status] ?? $statusStyles['production'];
$modeUrl = Router::url('mode', ['partial' => 1]);
$confirmProductionUrl = Router::url('mode', ['partial' => 1, 'confirm_production' => 1]);
$confirmProductionTitle = (string) mh_lng('MAILBEEZ_MODE_CONFIRM_PRODUCTION_TITLE', 'Enable Production mode?');
$statusJs = htmlspecialchars((string) json_encode($status, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), ENT_QUOTES, 'UTF-8');
$statusStylesJs = htmlspecialchars((string) json_encode($statusStyles, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), ENT_QUOTES, 'UTF-8');
$modeUrlJs = htmlspecialchars((string) json_encode($modeUrl, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), ENT_QUOTES, 'UTF-8');
$confirmProductionUrlJs = htmlspecialchars((string) json_encode($confirmProductionUrl, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), ENT_QUOTES, 'UTF-8');

if ((int) mh_get('confirm_production', 0, 'int') === 1) {
    ob_start();
    ?>
    <div class="space-y-4">
        <div class="text-sm text-gray-800">
            <?= mh_lng('MAILBEEZ_MODE_CONFIRM_PRODUCTION_TEXT', 'Emails will be sent to real recipients. Use this only when you are ready for live sending.') ?>
        </div>

        <template x-teleport="#confirm-modal-footer">
            <div class="grid grid-cols-1 sm:grid-cols-2 gap-3 w-full">
                <?= Button::render(mh_lng('UI_CANCEL', 'Cancel'), [
                        'variant' => 'outline',
                        'fullWidth' => true,
                        'attrs' => [
                                'command' => 'close',
                                'commandfor' => 'confirm-modal',
                        ],
                ]) ?>

                <?= Button::render(mh_lng('MAILBEEZ_MODE_CONFIRM_PRODUCTION_ACTION', 'Enable Production'), [
                        'variant' => 'primary',
                        'fullWidth' => true,
                        'modal_close' => 'confirm-modal',
                        'attrs' => [
                                'hx-post' => $modeUrl,
                                'hx-vals' => json_encode(['status' => 'production'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE),
                                'hx-target' => '#mode-component',
                                'hx-swap' => 'outerHTML',
                                'data-no-global-loader' => '1',
                                'data-no-local-loader' => '1',
                                'hx-on::before-request' => 'window.dispatchEvent(new CustomEvent("mb-mode-status-request-start"))',
                                'hx-on::response-error' => 'window.dispatchEvent(new CustomEvent("mb-mode-status-request-finish"))',
                                'hx-on::send-error' => 'window.dispatchEvent(new CustomEvent("mb-mode-status-request-finish"))',
                                'hx-on::timeout' => 'window.dispatchEvent(new CustomEvent("mb-mode-status-request-finish"))',
                        ],
                ]) ?>
            </div>
        </template>
    </div>
    <?php
    echo ob_get_clean();
    return;
}

if ((int) mh_get('restart_simulation', 0, 'int') === 1) {
    ob_start();
    ?>
    <div class="flex flex-col justify-center">
        <div class="text-sm text-gray-800 text-center">
            <?= mh_lng('MAILBEEZ_MODE_CONFIRM_RESTART_TEXT', 'All simulation results will be cleared, allowing you to start the simulation from the beginning.') ?>
        </div>

        <template x-teleport="#confirm-modal-footer">
            <div x-data="{ resetting: false }" class="w-full">
                <div x-show="!resetting" class="grid grid-cols-1 sm:grid-cols-2 gap-3 w-full">
                    <?= Button::render(mh_lng('UI_CANCEL', 'Cancel'), [
                            'variant' => 'outline',
                            'fullWidth' => true,
                            'attrs' => [
                                    'command' => 'close',
                                    'commandfor' => 'confirm-modal',
                            ],
                    ]) ?>

                    <?= Button::render(mh_lng('MAILBEEZ_MODE_CONFIRM_RESTART_ACTION', 'Reset Simulation Now'), [
                            'variant' => 'primary',
                            'fullWidth' => true,
                            'attrs' => [
                                    'hx-post' => $modeUrl,
                                    'hx-vals' => json_encode(['action' => 'restart_simulation_action'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE),
                                    'hx-target' => '#confirm-modal-body',
                                    'hx-swap' => 'innerHTML',
                                    'data-no-global-loader' => '1',
                                    'data-no-local-loader' => '1',
                                    '@click' => 'resetting = true',
                            ],
                    ]) ?>
                </div>
                <div x-show="resetting" x-cloak class="inline-block ">
                    <div class="h-9 w-full bg-orange-600/80 dark:bg-orange-500/70 rounded-full overflow-hidden relative flex items-center">
                        <div class="absolute top-0 bottom-0 left-0 bg-white/25 transition-all duration-[10000ms] ease-out" style="width: 0%" :style="{ width: resetting ? '100%' : '0%' }"></div>
                        <div class="relative flex items-center gap-2 pl-1 w-full">
                             <span class="inline-flex size-7 shrink-0 items-center justify-center rounded-full bg-orange-200/20 dark:bg-orange-300/40">
                                <span class="inline-flex size-5 items-center justify-center animate-spin text-white">
                                    <?= Base::SVG_REFRESH; ?>
                                </span>
                            </span>
                            <span class="text-sm font-medium text-white truncate pr-4">
                                <?= mh_lng('MAILBEEZ_MODE_RESETTING_PROGRESS', 'Starting fresh: Cleaning up simulation data...') ?>
                            </span>
                        </div>
                    </div>
                </div>
            </div>
        </template>
    </div>
    <?php
    echo ob_get_clean();
    return;
}

if (mh_server('REQUEST_METHOD', 'POST') && mh_post('action') === 'restart_simulation_action') {
    if (function_exists('mh_simulation_restart')) {
        mh_simulation_restart();
    }
    ob_start();
    ?>
    <div class="p-6 text-center min-h-[180px] flex flex-col justify-center items-center">
        <div class="size-16 rounded-full bg-green-100 text-green-600 flex items-center justify-center mx-auto mb-6">
            <svg class="size-8" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
            </svg>
        </div>
        <div class="text-lg font-semibold text-gray-900">
            <?= mh_lng('MAILBEEZ_SIMULATION_RESTARTED_MSG', 'Simulation Restarted') ?>
        </div>
        <script>
            setTimeout(() => {
                const dlg = document.getElementById('confirm-modal');
                if (dlg && typeof dlg.close === 'function') {
                    dlg.close();
                }
            }, 1500);
        </script>
    </div>
    <?php
    echo ob_get_clean();
    return;
}
?>



<div id="mode-component" class="flex items-center"
     x-data='{
       status: <?= $statusJs ?>,
       styles: <?= $statusStylesJs ?>,
       modeUrl: <?= $modeUrlJs ?>,
       confirmProductionUrl: <?= $confirmProductionUrlJs ?>,
       loading: false,
       get state() {
         return this.styles[this.status] || this.styles.production;
       },
       postStatus(next) {
         if (!window.htmx) {
           return;
         }
         window.dispatchEvent(new CustomEvent("mb-mode-status-request-start"));
         var request = window.htmx.ajax("POST", this.modeUrl, {
           target: "#mode-component",
           swap: "outerHTML",
           values: { status: next },
           headers: {
             "X-No-Global-Loader": "1",
             "X-No-Local-Loader": "1"
           }
         });
         if (request && typeof request.catch === "function") {
           request.catch(function () {
             window.dispatchEvent(new CustomEvent("mb-mode-status-request-finish"));
           });
         }
       },
       openProductionConfirm() {
         var trigger = this.$refs.productionConfirmTrigger;
         if (trigger && window.MBModal && typeof window.MBModal.applyFromTrigger === "function") {
           window.MBModal.applyFromTrigger(trigger);
           if (window.htmx) {
             window.htmx.ajax("GET", this.confirmProductionUrl, {
               target: "#confirm-modal-body",
               swap: "innerHTML",
               headers: {
                 "X-No-Global-Loader": "1",
                 "X-No-Local-Loader": "1"
               }
             });
           }
           return;
         }
         if (trigger) {
           trigger.click();
         }
       },
       onLabelToggle() {
         var next = this.status === "production" ? "simulate" : "production";
         if (next === "simulate") {
           this.postStatus("simulate");
           return;
         }
         this.openProductionConfirm();
       }
     }'
     @mb-mode-status-request-start.window="loading = true"
     @mb-mode-status-request-finish.window="loading = false">

    <?php if ($status === 'simulate'): ?>
        <button type="button"
                class="mr-2 inline-flex size-9 items-center justify-center rounded-full bg-orange-600/80 dark:bg-orange-500/70 hover:bg-orange-500/80 dark:hover:bg-orange-400 text-white transition-colors cursor-pointer outline-hidden"
                command="show-modal"
                commandfor="confirm-modal"
                data-no-global-loader="1"
                data-no-local-loader="1"
                data-title="<?= htmlspecialchars(mh_lng('MAILBEEZ_MODE_CONFIRM_RESTART_TITLE', 'Reset Simulation'), ENT_QUOTES, 'UTF-8'); ?>"
                hx-get="<?= Router::url('mode', ['partial' => 1, 'restart_simulation' => 1]); ?>"
                hx-target="#confirm-modal-body"
                hx-swap="innerHTML"
                title="<?= htmlspecialchars(mh_lng('MAILBEEZ_MODE_CONFIRM_RESTART_TITLE', 'Reset Simulation'), ENT_QUOTES, 'UTF-8'); ?>">
            <span class="inline-flex size-7 items-center justify-center rounded-full bg-orange-200/20 dark:bg-orange-300/40">
                <span class="inline-flex size-5 items-center justify-center">
                    <?= Base::SVG_REFRESH; ?>
                </span>
            </span>
        </button>
    <?php endif; ?>

    <button id="mode-production-confirm-trigger"
            x-ref="productionConfirmTrigger"
            type="button"
            class="hidden"
            command="show-modal"
            commandfor="confirm-modal"
            data-type="warning"
            data-no-global-loader="1"
            data-no-local-loader="1"
            data-title="<?= htmlspecialchars($confirmProductionTitle, ENT_QUOTES, 'UTF-8'); ?>"
            hx-get="<?= htmlspecialchars($confirmProductionUrl, ENT_QUOTES, 'UTF-8'); ?>"
            hx-target="#confirm-modal-body"
            hx-swap="innerHTML"></button>

    <?php
    $dropdownItems = [];
    foreach ($statusStyles as $value => $style) {
        ob_start();
        ?>
        <div class="flex flex-col">
            <div class="flex justify-between items-center">
                <div class="inline-flex items-center gap-2">
                <span class="inline-flex size-6 items-center justify-center rounded-full <?= htmlspecialchars($style['bgMain'], ENT_QUOTES, 'UTF-8'); ?>" aria-hidden="true">
                  <span class="inline-flex size-6 items-center justify-center rounded-full <?= htmlspecialchars($style['iconChip'], ENT_QUOTES, 'UTF-8'); ?>">
                    <span class="inline-flex size-4 items-center justify-center text-white"><?= $statusIcons[$value] ?? ''; ?></span>
                  </span>
                </span>
                    <p class="font-normal [[aria-selected=true]_&]:font-semibold"><?= htmlspecialchars($style['label'], ENT_QUOTES, 'UTF-8'); ?></p>
                </div>
                <span class="hidden! [[aria-selected=true]_&]:inline-flex! group-focus/item:text-white <?= htmlspecialchars($style['optionCheck'], ENT_QUOTES, 'UTF-8'); ?>">
                <svg viewBox="0 0 20 20" fill="currentColor" aria-hidden="true" class="size-5">
                  <path d="M16.704 4.153a.75.75 0 0 1 .143 1.052l-8 10.5a.75.75 0 0 1-1.127.075l-4.5-4.5a.75.75 0 0 1 1.06-1.06l3.894 3.893 7.48-9.817a.75.75 0 0 1 1.05-.143Z" clip-rule="evenodd" fill-rule="evenodd" />
                </svg>
              </span>
            </div>
            <p class="mt-2 text-gray-500 text-xs dark:text-gray-400 group-focus/item:text-white/80"><?= htmlspecialchars($style['description'], ENT_QUOTES, 'UTF-8'); ?></p>
        </div>
        <?php
        $itemHtml = ob_get_clean();

        $dropdownItems[] = [
                'content' => '<button type="button" role="menuitem" ' .
                        Base::attrs([
                                'class' => 'group/item flex flex-col w-full text-left p-4 text-sm text-gray-900 select-none focus:outline-hidden dark:text-white ' . $style['optionFocus'],
                                '@click' => "status === '$value' ? null : ('$value' === 'production' ? openProductionConfirm() : postStatus('simulate'))",
                                'aria-selected' => ($status === $value ? 'true' : 'false'),
                                'onmousedown' => 'event.stopPropagation();',
                                'onclick' => 'event.stopPropagation();',
                        ]) . '>' . $itemHtml . '</button>'
        ];
    }

    ob_start();
    ?>
    <div class="flex h-9 divide-x divide-white/20 rounded-full outline-hidden">
        <div id="status-label"
             class="inline-flex cursor-pointer items-center gap-x-1.5 rounded-l-full px-2 text-white/80 <?= htmlspecialchars($currentStyle['bgMain'], ENT_QUOTES, 'UTF-8'); ?>"
             :class="state.bgMain"
             @mousedown.prevent.stop
             @click.prevent.stop="onLabelToggle()">
      <span class="-ml-1 inline-flex size-7 shrink-0 items-center justify-center rounded-full"
            :class="state.iconChip">
        <span x-cloak x-show="!loading && status === 'production'" aria-hidden="true" class="inline-flex size-5 items-center justify-center">
          <?= Base::SVG_OUTLINE_PLAY; ?>
        </span>
        <span x-cloak x-show="!loading && status === 'simulate'" aria-hidden="true" class="inline-flex size-5 items-center justify-center">
          <?= Base::SVG_OUTLINE_PAUSE; ?>
        </span>
        <svg x-cloak x-show="loading" viewBox="0 0 24 24" fill="none" aria-hidden="true" class="size-4 animate-spin text-white">
          <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="3" class="opacity-25"></circle>
          <path d="M22 12a10 10 0 0 0-10-10" stroke="currentColor" stroke-width="3" stroke-linecap="round" class="opacity-90"></path>
        </svg>
      </span>
            <div class="text-left text-sm font-semibold pl-1 tracking-tight"
                 style="width: 9ch;"
                 x-text="state.label"><?= htmlspecialchars($currentStyle['label'], ENT_QUOTES, 'UTF-8'); ?></div>
        </div>
        <button
                type="button"
                aria-label="Toggle system mode"
                class="inline-flex items-center [&>svg]:size-5! rounded-l-none text-white/70 rounded-r-full pl-1.5 pr-2 <?= htmlspecialchars($currentStyle['bgMain'] . ' ' . $currentStyle['outline'], ENT_QUOTES, 'UTF-8'); ?>"
                :class="state.bgMain + ' ' + state.outline"
        >
            <?= Base::SVG_CHEVRON_DOWN; ?>
        </button>
    </div>
    <?php
    $triggerHtml = ob_get_clean();

    echo Dropdown::render([
            'trigger_tag' => 'div',
            'trigger_html' => $triggerHtml,
            'items' => $dropdownItems,
            'anchor' => 'bottom end',
            'wrapper_class' => 'flex items-center',
            'menu_attrs' => ['class' => 'w-72 divide-y divide-gray-200 dark:divide-white/10 overflow-hidden'],
    ]);
    ?>
</div>
