<?php
/**
 * Component Playground
 * Interactive component testing and preview
 */
require_once __DIR__ . "/../../src/Core/Auth.php";
require_once __DIR__ . "/../../src/Core/Model.php";
require_once __DIR__ . "/../../src/Core/MultiTenancy.php";
require_once __DIR__ . "/../../src/Core/Theme.php";
require_once __DIR__ . "/../../src/Models/Meta.php";

// Auth check
if (!\Core\Auth::check()) {
    header('Location: /admin/login.php');
    exit;
}

// Database connection
$tenantId = \Core\MultiTenancy::getTenantId();
define('DB_PATH', \Core\MultiTenancy::getDatabasePath($tenantId));
try {
    $pdo = new PDO('sqlite:' . DB_PATH);
    \Core\Model::setPdo($pdo);
} catch (Exception $e) {
    die('DB Error: ' . $e->getMessage());
}

// Handle AJAX preview request
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax_preview'])) {
    header('Content-Type: text/html; charset=utf-8');

    $code = $_POST['code'] ?? '';
    $data = json_decode($_POST['data'] ?? '{}', true) ?: [];
    $componentName = $_POST['component_name'] ?? null;

    $themeUrl = \Core\Theme::getCssUrl();

    echo '<!DOCTYPE html><html><head>';
    echo '<meta charset="UTF-8">';
    echo '<link rel="stylesheet" href="' . $themeUrl . '">';
    echo '<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">';
    echo '<style>body{padding:0;margin:0;}</style>';
    echo '</head><body>';

    try {
        if ($componentName) {
            $componentPath = __DIR__ . '/../../themes/default/components/' . $componentName . '.php';
            if (file_exists($componentPath)) {
                extract($data);
                include $componentPath;
            } else {
                echo '<div class="notification is-danger">Component not found</div>';
            }
        } elseif ($code) {
            extract($data);
            eval ('?>' . $code);
        } else {
            echo '<div class="notification is-info is-light p-6 has-text-centered">
                <p class="is-size-5">Enter code or select a component to preview</p>
            </div>';
        }
    } catch (Throwable $e) {
        echo '<div class="notification is-danger"><strong>Error:</strong> ' . htmlspecialchars($e->getMessage()) . '</div>';
    }

    echo '</body></html>';
    exit;
}

// Get available components
$componentDir = __DIR__ . '/../../themes/default/components/';
$components = [];
if (is_dir($componentDir)) {
    $files = glob($componentDir . '*.php');
    foreach ($files as $file) {
        $name = basename($file, '.php');
        $components[] = [
            'name' => $name,
            'display_name' => ucwords(str_replace('_', ' ', $name))
        ];
    }
}

// Sample data for components
$sampleDataTemplates = [
    'hero' => '{"title": "Welcome", "subtitle": "A tagline", "cta_text": "Get Started", "cta_link": "/contact"}',
    'features' => '{"title": "Features", "items": [{"title": "Feature 1", "description": "Desc"}]}',
    'team' => '{"title": "Team", "member1_name": "John", "member1_role": "CEO"}',
    'contact_form' => '{"title": "Contact Us", "email_to": "info@example.com"}',
    'showcase' => '{"title": "Showcase"}'
];

$pageTitle = 'Component Playground';
$currentPage = 'playground';

ob_start();
?>

<div class="columns">
    <div class="column is-5">
        <div class="admin-card">
            <h2 class="card-header-title">
                <span class="icon mr-2"><i class="fas fa-code"></i></span>
                Code Editor
            </h2>

            <div class="field">
                <label class="label">Quick Load Component</label>
                <div class="control">
                    <div class="select is-fullwidth">
                        <select id="componentSelect">
                            <option value="">-- Custom Code --</option>
                            <?php foreach ($components as $comp): ?>
                                <option value="<?= $comp['name'] ?>"><?= $comp['display_name'] ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
            </div>

            <div class="field">
                <label class="label">PHP/HTML Code</label>
                <div class="control">
                    <textarea id="codeEditor" class="textarea" rows="15"
                        style="font-family: monospace; font-size: 13px;"
                        placeholder="Write your component code here..."></textarea>
                </div>
            </div>

            <div class="field">
                <label class="label">Sample Data (JSON)</label>
                <div class="control">
                    <textarea id="dataEditor" class="textarea" rows="5"
                        style="font-family: monospace; font-size: 12px;">{"title": "Hello World"}</textarea>
                </div>
            </div>

            <div class="buttons">
                <button type="button" class="button is-primary" id="previewBtn">
                    <span class="icon"><i class="fas fa-play"></i></span>
                    <span>Run Preview</span>
                </button>
                <button type="button" class="button is-light" id="clearBtn">
                    <span class="icon"><i class="fas fa-eraser"></i></span>
                    <span>Clear</span>
                </button>
            </div>
        </div>

        <div class="admin-card">
            <h2 class="card-header-title">
                <span class="icon mr-2"><i class="fas fa-magic"></i></span>
                Quick Templates
            </h2>
            <div class="buttons are-small">
                <button class="button template-btn" data-template="section">Section</button>
                <button class="button template-btn" data-template="hero">Hero</button>
                <button class="button template-btn" data-template="cards">Cards</button>
                <button class="button template-btn" data-template="cta">CTA</button>
            </div>
        </div>
    </div>

    <div class="column is-7">
        <div class="admin-card" style="height: 100%;">
            <div class="level mb-4">
                <div class="level-left">
                    <h2 class="card-header-title" style="border: none; padding: 0; margin: 0;">
                        <span class="icon mr-2"><i class="fas fa-eye"></i></span>
                        Live Preview
                    </h2>
                </div>
                <div class="level-right">
                    <div class="buttons are-small">
                        <button class="button viewport-btn is-info is-light" data-width="100%">
                            <i class="fas fa-desktop"></i>
                        </button>
                        <button class="button viewport-btn" data-width="768px">
                            <i class="fas fa-tablet-alt"></i>
                        </button>
                        <button class="button viewport-btn" data-width="375px">
                            <i class="fas fa-mobile-alt"></i>
                        </button>
                    </div>
                </div>
            </div>

            <div style="background: #f5f5f5; border-radius: 8px; overflow: hidden; min-height: 500px;">
                <iframe id="previewFrame" style="width: 100%; height: 500px; border: none; background: white;"></iframe>
            </div>
        </div>
    </div>
</div>

<!-- Templates stored in hidden script tags to avoid PHP parsing -->
<script type="text/template" id="tpl-section">
<section class="section">
    <div class="container">
        <h2 class="title is-2"><?= htmlspecialchars($title ?? '') ?></h2>
        <p class="subtitle"><?= htmlspecialchars($subtitle ?? '') ?></p>
        <div class="content">
            <!-- Your content here -->
        </div>
    </div>
</section>
</script>

<script type="text/template" id="tpl-hero">
<section class="hero is-primary is-medium">
    <div class="hero-body">
        <div class="container has-text-centered">
            <p class="title is-1"><?= htmlspecialchars($title ?? '') ?></p>
            <p class="subtitle is-3"><?= htmlspecialchars($subtitle ?? '') ?></p>
            <?php if (!empty($cta_text)): ?>
                <a href="<?= htmlspecialchars($cta_link ?? '#') ?>" class="button is-light is-large mt-4">
                    <?= htmlspecialchars($cta_text) ?>
                </a>
            <?php endif; ?>
        </div>
    </div>
</section>
</script>

<script type="text/template" id="tpl-cards">
<section class="section">
    <div class="container">
        <h2 class="title is-2 has-text-centered"><?= htmlspecialchars($title ?? '') ?></h2>
        <div class="columns is-multiline">
            <?php for ($i = 1; $i <= 3; $i++): ?>
                <div class="column is-4">
                    <div class="card">
                        <div class="card-content">
                            <p class="title is-4">Card <?= $i ?></p>
                            <p class="content">Card content goes here.</p>
                        </div>
                    </div>
                </div>
            <?php endfor; ?>
        </div>
    </div>
</section>
</script>

<script type="text/template" id="tpl-cta">
<section class="section has-background-primary">
    <div class="container has-text-centered">
        <h2 class="title is-2 has-text-white"><?= htmlspecialchars($title ?? '') ?></h2>
        <p class="subtitle has-text-white-ter"><?= htmlspecialchars($subtitle ?? '') ?></p>
        <a href="<?= htmlspecialchars($link ?? '#') ?>" class="button is-white is-large">
            <?= htmlspecialchars($button_text ?? 'Learn More') ?>
        </a>
    </div>
</section>
</script>

<script>
    const sampleData = <?= json_encode($sampleDataTemplates) ?>;

    const codeEditor = document.getElementById('codeEditor');
    const dataEditor = document.getElementById('dataEditor');
    const previewFrame = document.getElementById('previewFrame');
    const componentSelect = document.getElementById('componentSelect');

    function runPreview() {
        const formData = new FormData();
        formData.append('ajax_preview', '1');
        formData.append('code', codeEditor.value);
        formData.append('data', dataEditor.value);

        const selectedComponent = componentSelect.value;
        if (selectedComponent && !codeEditor.value.trim()) {
            formData.append('component_name', selectedComponent);
        }

        fetch('/admin/playground.php', {
            method: 'POST',
            body: formData
        })
            .then(response => response.text())
            .then(html => {
                previewFrame.srcdoc = html;
            })
            .catch(error => {
                previewFrame.srcdoc = '<div style="padding:20px;color:red;">Error: ' + error.message + '</div>';
            });
    }

    document.getElementById('previewBtn').addEventListener('click', runPreview);

    document.getElementById('clearBtn').addEventListener('click', () => {
        codeEditor.value = '';
        dataEditor.value = '{"title": "Hello World"}';
        componentSelect.value = '';
        previewFrame.srcdoc = '';
    });

    componentSelect.addEventListener('change', function () {
        const name = this.value;
        if (name && sampleData[name]) {
            dataEditor.value = sampleData[name];
        }
        if (name) {
            codeEditor.value = '';
            runPreview();
        }
    });

    document.querySelectorAll('.template-btn').forEach(btn => {
        btn.addEventListener('click', function () {
            const tpl = document.getElementById('tpl-' + this.dataset.template);
            if (tpl) {
                codeEditor.value = tpl.innerHTML.trim();
                runPreview();
            }
        });
    });

    document.querySelectorAll('.viewport-btn').forEach(btn => {
        btn.addEventListener('click', function () {
            document.querySelectorAll('.viewport-btn').forEach(b => b.classList.remove('is-info', 'is-light'));
            this.classList.add('is-info', 'is-light');
            previewFrame.style.width = this.dataset.width;
            previewFrame.style.margin = this.dataset.width !== '100%' ? '0 auto' : '0';
        });
    });

    codeEditor.addEventListener('keydown', function (e) {
        if (e.key === 'Tab') {
            e.preventDefault();
            const start = this.selectionStart;
            this.value = this.value.substring(0, start) + '    ' + this.value.substring(this.selectionEnd);
            this.selectionStart = this.selectionEnd = start + 4;
        }
    });

    runPreview();
</script>

<?php
$content = ob_get_clean();
include __DIR__ . '/layouts/admin_layout.php';
