<?php
/**
 * TinyMCE Editor Component
 *
 * Purpose: Initialize TinyMCE using the same config as generate.php step 3.
 *
 * Usage:
 *   <script src="https://cdn.jsdelivr.net/npm/tinymce@6.8.2/tinymce.min.js"></script>
 *   <?php
 *     $tinymceComponent = __DIR__ . '/components/editors/tinymce-init.php';
 *     if (file_exists($tinymceComponent)) {
 *         require_once $tinymceComponent;
 *         if (function_exists('renderTinyMCEInit')) {
 *             renderTinyMCEInit();
 *         }
 *     }
 *   ?>
 */

function renderTinyMCEInit(): void {
    ?>
    <script>
        function getEditorThemeConfig() {
            const root = document.documentElement;
            const theme = (root.getAttribute('data-theme') || 'dark').toLowerCase();
            const isLight = theme === 'light';

            if (isLight) {
                return {
                    isLight,
                    colors: {
                        background: '#ffffff',
                        text: '#111827',
                        link: '#0f766e'
                    }
                };
            }

            return {
                isLight: false,
                colors: {
                    background: '#2A2A2A',
                    text: '#f5f5f4',
                    link: '#d4d4d8'
                }
            };
        }

        function initializeRichEditors() {
            if (!window.tinymce) return;

            tinymce.remove();

            const { isLight, colors } = getEditorThemeConfig();

            tinymce.init({
                selector: '.rich',
                height: 360,
                min_height: 320,
                plugins: 'lists table image link code autoresize',
                toolbar: 'undo redo | bold italic underline | bullist numlist | alignleft aligncenter alignright | link image | code',
                menubar: false,
                statusbar: false,
                toolbar_mode: 'sliding',
                branding: false,
                promotion: false,
                skin: isLight ? 'oxide' : 'oxide-dark',
                content_css: isLight ? 'default' : 'dark',
                automatic_uploads: false,
                images_file_types: 'jpg,png,jpeg,gif,webp',
                images_upload_handler: function (blobInfo, success, failure) {
                    const reader = new FileReader();
                    reader.readAsDataURL(blobInfo.blob());
                    reader.onload = function () {
                        success(reader.result);
                    };
                    reader.onerror = function () {
                        failure('Image upload failed');
                    };
                },
                content_style: `
                    body {
                        font-family: system-ui, -apple-system, BlinkMacSystemFont, 'SF Pro Text', sans-serif;
                        font-size: 14px;
                        line-height: 1.6;
                        color: ${colors.text};
                        background-color: ${colors.background};
                    }
                    a { color: ${colors.link}; }
                    p { margin: 0 0 0.5rem 0; }
                `
            });
        }

        document.addEventListener('DOMContentLoaded', () => {
            initializeRichEditors();

            const themeObserver = new MutationObserver((mutations) => {
                for (const mutation of mutations) {
                    if (mutation.attributeName === 'data-theme') {
                        initializeRichEditors();
                        break;
                    }
                }
            });

            themeObserver.observe(document.documentElement, { attributes: true });
        });
    </script>
    <?php
}

function getTinyMCEVariableTokens(): array
{
    return [
        ['label' => 'Client name', 'token' => '{{client_name}}'],
        ['label' => 'Company', 'token' => '{{company_name}}'],
        ['label' => 'Project', 'token' => '{{project_name}}'],
        ['label' => 'Proposal date', 'token' => '{{proposal_date}}'],
        ['label' => 'Client email', 'token' => '{{client_email}}'],
        ['label' => 'Client phone', 'token' => '{{client_phone}}'],
        ['label' => 'Client address', 'token' => '{{client_address}}'],
    ];
}

function renderTinyMCEVariableInserts(?array $variableTokens = null, string $title = 'Quick inserts'): void
{
    $tokens = $variableTokens ?? getTinyMCEVariableTokens();

    if (!$tokens) {
        return;
    }
    ?>
    <div class="module-card__inserts">
        <p><?= h($title) ?></p>
        <div class="chip-group">
            <?php foreach ($tokens as $token): ?>
                <button type="button" class="variable-chip" onclick="insertVariable('<?= h($token['token']) ?>')">
                    <?= h($token['label']) ?>
                </button>
            <?php endforeach; ?>
        </div>
    </div>
    <?php
}
