<?php
// components/Modal.php
namespace Components;

class Modal extends Base
{
    /**
     * Render the configuration modal markup.
     * Options:
     * - id | modalId: string element id of the modal root (default: 'config-modal')
     * - style: 'default' | 'ai' (default: 'default')
     */
    public static function render(array $opts = []): string
    {
        $modalId = isset($opts['id']) && $opts['id'] !== ''
            ? (string)$opts['id']
            : (isset($opts['modalId']) && $opts['modalId'] !== '' ? (string)$opts['modalId'] : 'config-modal');

        $style = isset($opts['style']) ? (string)$opts['style'] : 'default';

        $wrapperId       = $modalId . '-wrapper';
        $panelId         = $modalId . '-panel';
        $headerId        = $modalId . '-header';
        $titleId         = $modalId . '-title';
        $headerCloseId   = $modalId . '-header-close';
        $floatingCloseId = $modalId . '-floating-close';
        $bodyId          = $modalId . '-body';
        $iframeId        = $modalId . '-iframe';
        $footerId        = $modalId . '-footer';
        $loadingId       = $modalId . '-loading';

        $backDropCss   = 'bg-black/10';
        $dialogPanelCss = 'group/modal-panel relative w-full transform overflow-hidden rounded-lg bg-white text-left shadow-xl transition-all dark:bg-gray-800 max-w-2xl flex flex-col';


        // Escaped IDs
        $modalIdEsc        = self::h($modalId);
        $wrapperIdEsc      = self::h($wrapperId);
        $panelIdEsc        = self::h($panelId);
        $headerIdEsc       = self::h($headerId);
        $titleIdEsc        = self::h($titleId);
        $headerCloseIdEsc  = self::h($headerCloseId);
        $floatingCloseIdEsc= self::h($floatingCloseId);
        $bodyIdEsc         = self::h($bodyId);
        $iframeIdEsc       = self::h($iframeId);
        $footerIdEsc       = self::h($footerId);
        $loadingIdEsc      = self::h($loadingId);

        // Loader HTML
        $loader = self::loaderOverlay($loadingId, 'z-10');

        switch ($style) {
            case 'ai':
                $backDropCss   = '';
                $dialogPanelCss = 'flex-1 relative min-h-[80vh]';
                $loader = '';
                break;
            case 'email_preview':
                break;
            case 'default':
            default:
                break;
        }


        ob_start();
        ?>
<el-dialog>
    <dialog id="<?= $modalIdEsc; ?>" aria-labelledby="<?= $titleIdEsc; ?>" data-style="<?= self::h($style) ?>" class="fixed inset-0 size-auto max-h-none max-w-none overflow-y-auto bg-transparent backdrop:bg-transparent">
        <el-dialog-backdrop class="fixed inset-0 <?= $backDropCss; ?> transition-opacity data-closed:opacity-0 data-enter:duration-300 data-enter:ease-out data-leave:duration-200 data-leave:ease-in dark:bg-gray-900/50"></el-dialog-backdrop>
        <div id="<?= $wrapperIdEsc; ?>" tabindex="0" class="flex min-h-full items-end justify-center p-4 text-center focus:outline-none sm:items-center sm:p-0">
            <el-dialog-panel id="<?= $panelIdEsc; ?>" class="<?= $dialogPanelCss; ?>">
                <?php if ($style === 'ai'): ?>
                <div>
                    <div class="absolute -inset-3">
                        <div class="w-full h-full mx-auto opacity-20 blur-sm filter animate-pulse-opacity-and-rotate mbz-ai-gradient"></div>
                    </div>
                    <div class="group/modal-panel p-8 relative w-full transform overflow-hidden rounded-xl border border-gray-200 bg-white text-left shadow-xl transition-all dark:bg-gray-800 max-w-2xl flex flex-col">
                <?php endif; ?>

                <!-- Header (conditionally shown when a title is provided) -->
                <div id="<?= $headerIdEsc; ?>" class="hidden flex items-start justify-between border-b border-divider px-6 py-3 dark:border-white/10">
                    <h2 id="<?= $titleIdEsc; ?>" class="text-base font-semibold text-gray-900 dark:text-white"></h2>
                    <div class="ml-3 flex h-7 items-center">
                        <button id="<?= $headerCloseIdEsc; ?>" type="button" command="close" commandfor="<?= $modalIdEsc; ?>"
                                class="relative rounded-md text-gray-400 hover:text-gray-600 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-brand dark:hover:text-white dark:focus-visible:outline-brand-500">
                            <span class="absolute -inset-2.5"></span>
                            <span class="sr-only">Close modal</span>
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true" class="size-6">
                                <path d="M6 18 18 6M6 6l12 12" stroke-linecap="round" stroke-linejoin="round"/>
                            </svg>
                        </button>
                    </div>
                </div>

                <!-- Floating close button (used when no header/title) -->
                <button id="<?= $floatingCloseIdEsc; ?>" type="button" command="close" commandfor="<?= $modalIdEsc; ?>"
                        class="hidden absolute right-2 top-2 z-100 rounded-md bg-white/70 p-1 text-gray-600 hover:bg-white hover:text-gray-900 dark:bg-gray-700/70 dark:text-gray-200 dark:hover:bg-gray-700">
                    <span class="sr-only">Close modal</span>
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true" class="size-6">
                        <path d="M6 18 18 6M6 6l12 12" stroke-linecap="round" stroke-linejoin="round"/>
                    </svg>
                </button>

                <!-- Body: either HTMX target or isolated iframe -->
                <div class="relative max-h-[80vh] overflow-auto p-6">
                    <?php if ($style === 'email_preview') { ?>
                        <!-- Embedded Email Previewer component -->
                        <div id="<?= $bodyIdEsc; ?>" class="h-full">
                            <?php
                            // Render the page component with a modal-specific id prefix; URL will be injected by JS via data-url
                            if (class_exists('Components\\Ui\\EmailPreviewer')) {
                                echo \Components\Ui\EmailPreviewer::render([
                                    'url' => '',
                                    'device' => 'desktop',
                                    'id_prefix' => $modalId . '-ep'
                                ]);
                            }
                            ?>
                        </div>
                        <!-- Keep iframe present but hidden for API parity; not used in email_preview style -->
                        <iframe id="<?= $iframeIdEsc; ?>" src="about:blank" title="Modal content"
                                class="hidden h-[70vh] w-full border-0 bg-white dark:bg-gray-900"></iframe>
                    <?php } else { ?>
                        <!-- Loading overlay for iframe/htmx mode -->
                        <?= $loader ?>
                        <!-- HTMX content target -->
                        <div id="<?= $bodyIdEsc; ?>"></div>
                        <!-- Isolated URL content -->
                        <iframe id="<?= $iframeIdEsc; ?>" src="about:blank" title="Modal content"
                                class="hidden h-[70vh] w-full border-0 bg-white dark:bg-gray-900"></iframe>
                    <?php } ?>
                </div>

                <!-- Optional footer slot (empty by default) -->
                <div id="<?= $footerIdEsc; ?>" class="hidden border-t border-gray-200  py-3 dark:border-white/10"></div>
                <?php if ($style === 'ai'): ?>
                </div>
                </div>
                <?php endif; ?>
            </el-dialog-panel>
        </div>
    </dialog>
</el-dialog>
<?php
        return ob_get_clean();
    }
}
