<?php

namespace GriffinForms\Admin\App\Html\Modals;

use GriffinForms\Traits\Singleton;

final class Preview extends \GriffinForms\Admin\App\Html\Modals\Format
{
    use Singleton;

    protected $has_footer = false;
    protected $modal_dialog_classes = ['modal-xl', 'modal-dialog-scrollable'];

    protected function getModalTitle()
    {
        return __('Preview', 'griffinforms-form-builder');
    }

    protected function renderModalBodyHtml()
    {
        $form_id   = isset($_GET['form_id']) ? absint($_GET['form_id']) : 0;
        $icons_url = $this->config->getRootUrl() . 'admin/images/icons/';

        // Toolbar strip — flex-shrink:0 keeps it visible in fullscreen
        echo '<div class="d-flex align-items-center justify-content-between mb-3 gf-preview-toolbar" style="flex-shrink:0;">';

        // Left: Expand/Contract
        echo '<div>';
        $buttons = \GriffinForms\Admin\Html\Elements\Buttons::getInstance();
        $buttons->bsBtn([
            'id'    => 'griffinforms-builder-preview-toggle-size',
            'class' => 'gf-btn-secondary',
            'label' => __('Expand', 'griffinforms-form-builder'),
            'aria'  => ['aria-pressed' => 'false'],
        ]);
        echo '</div>';

        // Centre: Viewport switcher
        echo '<div class="d-flex align-items-center gap-1" id="griffinforms-builder-preview-viewport-switcher">';

        $viewports = [
            'desktop' => ['label' => __('Desktop', 'griffinforms-form-builder'), 'icon' => 'viewport-desktop.svg', 'width' => '100%'],
            'tablet'  => ['label' => __('Tablet',  'griffinforms-form-builder'), 'icon' => 'viewport-tablet.svg',  'width' => '768px'],
            'mobile'  => ['label' => __('Mobile',  'griffinforms-form-builder'), 'icon' => 'viewport-mobile.svg',  'width' => '430px'],
        ];

        foreach ($viewports as $key => $vp) {
            $active = $key === 'desktop' ? ' gf-preview-viewport-btn--active' : '';
            echo '<button type="button"'
                . ' class="components-button has-icon p-1 gf-preview-viewport-btn' . esc_attr($active) . '"'
                . ' data-gf-viewport="' . esc_attr($key) . '"'
                . ' data-gf-viewport-width="' . esc_attr($vp['width']) . '"'
                . ' aria-label="' . esc_attr($vp['label']) . '"'
                . ' title="' . esc_attr($vp['label']) . '">';
            echo '<img src="' . esc_url($icons_url . $vp['icon']) . '" alt="' . esc_attr($vp['label']) . '" height="18">';
            echo '</button>';
        }

        echo '</div>';
        echo '<div style="width:80px;"></div>'; // balance the flex row
        echo '</div>'; // end toolbar

        // Hidden state fields
        echo '<input type="hidden" id="griffinforms-builder-preview-form-id" value="' . esc_attr($form_id) . '">';
        echo '<input type="hidden" id="griffinforms-builder-preview-size" value="xl">';

        // Static context notice
        echo '<div class="gf-notice gf-notice-info mb-3">';
        echo '<div>' . esc_html__('Live preview using your active WordPress theme. Conditional logic and submission workflows are fully active.', 'griffinforms-form-builder') . '</div>';
        echo '</div>';

        // Growing content area (status + iframe) — targeted by JS $previewWrap in fullscreen
        echo '<div id="griffinforms-builder-preview-content" style="flex:1 1 auto;min-height:0;display:flex;flex-direction:column;">';

        // Status notice
        echo '<div id="griffinforms-builder-preview-status" class="gf-notice gf-notice-info mb-3" role="alert">';
        echo '<div>' . esc_html__('Loading preview...', 'griffinforms-form-builder') . '</div>';
        echo '</div>';

        // Iframe wrapper
        echo '<div id="griffinforms-builder-preview-outer" class="d-flex justify-content-center bg-light rounded-3 overflow-hidden" style="min-height:70vh;">';
        echo '<div id="griffinforms-builder-preview-inner" class="bg-white overflow-hidden" style="width:100%;min-height:70vh;">';
        echo '<iframe id="griffinforms-builder-preview-iframe"'
            . ' title="' . esc_attr__('Form preview', 'griffinforms-form-builder') . '"'
            . ' style="width:100%;height:70vh;border:0;display:block;background:#fff;" loading="lazy">';
        echo '</iframe>';
        echo '</div>';
        echo '</div>';

        echo '</div>'; // end #griffinforms-builder-preview-content
    }

    public function getModalJs()
    {
        $modal_id = $this->modal_id;
        $nonce    = wp_create_nonce('griffinforms_get_form_preview_url');
        $form_id  = isset($_GET['form_id']) ? absint($_GET['form_id']) : 0;

        echo "
        (function($) {
            const previewNonce  = '" . esc_js($nonce) . "';
            const formId        = " . $form_id . ";
            const \$modal       = $('#{$modal_id}');
            const \$status      = $('#griffinforms-builder-preview-status');
            const \$iframe      = $('#griffinforms-builder-preview-iframe');
            const \$size        = $('#griffinforms-builder-preview-size');
            const \$toggle      = $('#griffinforms-builder-preview-toggle-size');
            const \$dialog      = \$modal.find('.modal-dialog');
            const \$modalBody   = \$modal.find('.modal-body');
            const \$previewWrap = $('#griffinforms-builder-preview-content');
            const \$outer       = $('#griffinforms-builder-preview-outer');
            const \$inner       = $('#griffinforms-builder-preview-inner');

            function setStatus(type, message) {
                \$status
                    .removeClass('gf-notice-info gf-notice-success gf-notice-warning gf-notice-danger')
                    .addClass('gf-notice-' + type)
                    .html('<div>' + message + '</div>')
                    .show();
            }

            function setModalSize(mode) {
                const fullscreen = mode === 'fullscreen';
                \$dialog.removeClass('modal-xl modal-fullscreen').addClass(fullscreen ? 'modal-fullscreen' : 'modal-xl');
                \$size.val(fullscreen ? 'fullscreen' : 'xl');
                \$toggle.find('.gf-btn-label').text(fullscreen ? '" . esc_js(__('Contract', 'griffinforms-form-builder')) . "' : '" . esc_js(__('Expand', 'griffinforms-form-builder')) . "');
                \$toggle.attr('aria-pressed', fullscreen ? 'true' : 'false');
                if (fullscreen) {
                    \$dialog.removeClass('modal-dialog-scrollable');
                    \$modalBody.css({display:'flex','flex-direction':'column',overflow:'hidden',padding:'8px',height:'100%'});
                    \$previewWrap.css({flex:'1 1 auto','min-height':'0',display:'flex','flex-direction':'column'});
                    \$outer.css({flex:'1 1 auto','min-height':'0',height:'100%','border-radius':'0'});
                    \$inner.css({height:'100%'});
                    \$iframe.css({height:'100%'});
                } else {
                    \$dialog.addClass('modal-dialog-scrollable');
                    \$modalBody.css({display:'',overflow:'',padding:'',height:''});
                    \$previewWrap.css({flex:'','min-height':'',display:'',height:''});
                    \$outer.css({flex:'','min-height':'70vh',height:'','border-radius':''});
                    \$inner.css({height:'',width:\$inner.attr('data-gf-viewport-width') || '100%'});
                    \$iframe.css({height:'70vh'});
                }
            }

            function scrollIframeToForm() {
                try {
                    const iframeDoc = \$iframe[0].contentDocument || \$iframe[0].contentWindow.document;
                    const container = iframeDoc.querySelector('.griffinforms-form-container');
                    const toolbarH = \$modal.find('.gf-preview-toolbar').outerHeight(true) || 0;
                    if (container) {
                        const offsetTop = container.getBoundingClientRect().top + iframeDoc.documentElement.scrollTop - toolbarH;
                        iframeDoc.documentElement.scrollTop = Math.max(0, offsetTop);
                    } else {
                        iframeDoc.documentElement.scrollTop = 0;
                    }
                } catch(e) {}
            }

            function refreshIframeViewport() {
                try {
                    const iframeWin = \$iframe[0] && \$iframe[0].contentWindow ? \$iframe[0].contentWindow : null;
                    if (iframeWin && typeof iframeWin.dispatchEvent === 'function') {
                        iframeWin.dispatchEvent(new Event('resize'));
                    }
                } catch (e) {}

                setTimeout(function() {
                    scrollIframeToForm();
                }, 275);
            }

            function applyViewport(width, viewport) {
                const isDesktop = viewport === 'desktop' || width === '100%';

                if (isDesktop) {
                    \$inner.attr('data-gf-viewport-width', '100%').css({
                        width: '100%',
                        maxWidth: '100%',
                        flex: '1 1 100%',
                        transition: 'width 0.25s ease, max-width 0.25s ease'
                    });
                } else {
                    \$inner.attr('data-gf-viewport-width', width).css({
                        width: width,
                        maxWidth: width,
                        flex: '0 0 auto',
                        transition: 'width 0.25s ease, max-width 0.25s ease'
                    });
                }

                refreshIframeViewport();
            }

            \$modal.on('click', '.gf-preview-viewport-btn', function() {
                const \$btn = \$(this);
                const viewport = \$btn.data('gfViewport') || 'desktop';
                const width = \$btn.data('gfViewportWidth') || '100%';
                \$modal.find('.gf-preview-viewport-btn').removeClass('gf-preview-viewport-btn--active');
                \$btn.addClass('gf-preview-viewport-btn--active');
                applyViewport(width, viewport);
            });

            function resetPreviewState() {
                \$iframe.attr('src', 'about:blank');
                setModalSize('xl');
                \$modal.find('.gf-preview-viewport-btn').removeClass('gf-preview-viewport-btn--active');
                \$modal.find('[data-gf-viewport=\"desktop\"]').addClass('gf-preview-viewport-btn--active');
                \$inner.attr('data-gf-viewport-width', '100%').css({width:'100%'});
                setStatus('info', '" . esc_js(__('Loading preview...', 'griffinforms-form-builder')) . "');
                \$modal.find('.griffinforms-modal-spinner').addClass('d-none');
            }

            \$iframe.on('load', function() {
                \$modal.find('.griffinforms-modal-spinner').addClass('d-none');
                scrollIframeToForm();
            });

            \$modal.on('show.bs.modal', function() {
                resetPreviewState();
                if (!formId) {
                    setStatus('danger', '" . esc_js(__('No form selected.', 'griffinforms-form-builder')) . "');
                    return;
                }
                \$modal.find('.griffinforms-modal-spinner').removeClass('d-none');
                $.post(ajaxurl, {
                    action: 'griffinforms_get_form_preview_url',
                    form_id: formId,
                    nonce: previewNonce
                }, function(response) {
                    if (response && response.success && response.data && response.data.preview_url) {
                        \$iframe.attr('src', response.data.preview_url);
                        \$status.hide();
                        return;
                    }
                    \$modal.find('.griffinforms-modal-spinner').addClass('d-none');
                    const msg = (response && response.data && response.data.message)
                        ? response.data.message
                        : '" . esc_js(__('Preview could not be loaded.', 'griffinforms-form-builder')) . "';
                    setStatus('danger', msg);
                }).fail(function() {
                    \$modal.find('.griffinforms-modal-spinner').addClass('d-none');
                    setStatus('danger', '" . esc_js(__('Network request failed. Try again later.', 'griffinforms-form-builder')) . "');
                });
            });

            \$modal.on('hidden.bs.modal', resetPreviewState);

            \$toggle.on('click', function() {
                setModalSize(\$size.val() === 'fullscreen' ? 'xl' : 'fullscreen');
                refreshIframeViewport();
            });
        })(jQuery);
        ";
    }

    private function __construct()
    {
        $this->setAll();
    }
}
