<?php
$editingEmail = (($editTemplate['type'] ?? 'email') === 'email');
?>
<section class="workspace-hero">
    <div>
        <h2>Email Theme Creator</h2>
        <p>Build reusable commercial email themes with a built-in editor, HTML/CSS controls, preset layouts, live preview, and saved template library support.</p>
    </div>
    <div class="workspace-actions">
        <a class="btn secondary small" href="index.php?route=messages/campaignStudio">Campaign Studio</a>
        <a class="btn secondary small" href="index.php?route=messages/mailCenter">Mail Center</a>
    </div>
</section>

<section class="theme-creator-layout">
    <div class="card theme-creator-card">
        <div class="toolbar">
            <h2><?= !empty($editTemplate) ? 'Edit Template' : 'Create Template' ?></h2>
            <span class="badge"><?= !empty($editTemplate) ? 'Library item' : 'Built-in editor' ?></span>
        </div>
        <p class="small muted">Use the theme builder for layout blocks, keep full control with raw HTML and CSS, then save the result as a reusable email template for Campaign Studio, Mail Center, and one-to-one email workflows.</p>

        <form method="post" action="index.php?route=templates/save" enctype="multipart/form-data" id="email-theme-form" data-template-editor>
            <?= csrf_input() ?>
            <input type="hidden" name="id" value="<?= (int)($editTemplate['id'] ?? 0) ?>">
            <input type="hidden" name="theme_json" id="theme-json" value="<?= e((string)($editTemplate['theme_json'] ?? '')) ?>">
            <input type="hidden" name="theme_preset" id="theme-preset-hidden" value="<?= e((string)($editTemplate['theme_preset'] ?? 'newsletter')) ?>">

            <div class="theme-mode-toggle" role="tablist" aria-label="Template type">
                <label class="theme-mode-pill">
                    <input type="radio" name="type" value="email" <?= $editingEmail ? 'checked' : '' ?>>
                    <span>Email Theme Creator</span>
                </label>
                <label class="theme-mode-pill">
                    <input type="radio" name="type" value="sms" <?= !$editingEmail ? 'checked' : '' ?>>
                    <span>SMS/MMS Quick Template</span>
                </label>
            </div>

            <div class="form-grid three mt-12">
                <label>
                    <span class="small muted">Template name</span>
                    <input name="name" id="template-name" placeholder="Quarterly Product Launch" value="<?= e((string)($editTemplate['name'] ?? '')) ?>" required>
                </label>
                <label>
                    <span class="small muted">Email subject</span>
                    <input name="subject" id="template-subject" placeholder="Subject line for email sends" value="<?= e((string)($editTemplate['subject'] ?? '')) ?>">
                </label>
                <label data-email-only>
                    <span class="small muted">Preview text</span>
                    <input name="preview_text" id="template-preview-text" placeholder="Short inbox preview line" value="<?= e((string)($editTemplate['preview_text'] ?? '')) ?>">
                </label>
            </div>

            <div class="theme-email-shell" data-template-type-panel="email">
                <div class="theme-toolbar mt-12">
                    <div class="theme-toolbar-copy">
                        <strong>Email Theme Builder</strong>
                        <div class="small muted">Start from a preset, adjust brand styling, add sections, then fine-tune the HTML and CSS before saving.</div>
                    </div>
                    <div class="theme-toolbar-actions">
                        <label>
                            <span class="small muted">Preset</span>
                            <select id="theme-preset-select">
                                <option value="newsletter">Newsletter</option>
                                <option value="announcement">Announcement</option>
                                <option value="promotion">Promotion</option>
                                <option value="event">Event invite</option>
                                <option value="retention">Retention</option>
                                <option value="custom">Custom</option>
                            </select>
                        </label>
                        <button type="button" class="btn secondary small" id="theme-copy-html">Copy HTML</button>
                    </div>
                </div>

                <div class="theme-builder-layout mt-12">
                    <div class="theme-builder-side">
                        <div class="theme-settings-grid">
                            <label>
                                <span class="small muted">Content width</span>
                                <input type="number" id="theme-width" min="480" max="760" step="10" value="640">
                            </label>
                            <label>
                                <span class="small muted">Font family</span>
                                <select id="theme-font-family">
                                    <option value="Arial, Helvetica, sans-serif">Arial</option>
                                    <option value="'Helvetica Neue', Arial, sans-serif">Helvetica Neue</option>
                                    <option value="Georgia, 'Times New Roman', serif">Georgia</option>
                                    <option value="Tahoma, Verdana, sans-serif">Tahoma</option>
                                    <option value="'Trebuchet MS', Arial, sans-serif">Trebuchet MS</option>
                                </select>
                            </label>
                            <label>
                                <span class="small muted">Canvas background</span>
                                <input type="color" id="theme-body-bg" value="#eef2f7">
                            </label>
                            <label>
                                <span class="small muted">Card background</span>
                                <input type="color" id="theme-card-bg" value="#ffffff">
                            </label>
                            <label>
                                <span class="small muted">Text color</span>
                                <input type="color" id="theme-text-color" value="#1f2937">
                            </label>
                            <label>
                                <span class="small muted">Accent color</span>
                                <input type="color" id="theme-accent-color" value="#1f5b92">
                            </label>
                            <label>
                                <span class="small muted">Button text</span>
                                <input type="color" id="theme-button-text-color" value="#ffffff">
                            </label>
                            <label>
                                <span class="small muted">Section radius</span>
                                <input type="number" id="theme-radius" min="0" max="32" step="2" value="18">
                            </label>
                        </div>

                        <div class="theme-section-toolbar mt-12">
                            <div class="small muted"><strong>Add sections</strong> to build the layout visually.</div>
                            <div class="theme-section-actions">
                                <button type="button" class="btn secondary small js-add-theme-section" data-section="hero">+ Hero</button>
                                <button type="button" class="btn secondary small js-add-theme-section" data-section="text">+ Text</button>
                                <button type="button" class="btn secondary small js-add-theme-section" data-section="image">+ Image</button>
                                <button type="button" class="btn secondary small js-add-theme-section" data-section="columns">+ Two Column</button>
                                <button type="button" class="btn secondary small js-add-theme-section" data-section="cta">+ CTA</button>
                                <button type="button" class="btn secondary small js-add-theme-section" data-section="divider">+ Divider</button>
                                <button type="button" class="btn secondary small js-add-theme-section" data-section="footer">+ Footer</button>
                            </div>
                        </div>

                        <div id="theme-sections" class="theme-section-stack"></div>
                    </div>

                    <div class="theme-editor-side">
                        <div class="theme-code-card">
                            <div class="toolbar compact-toolbar"><strong>HTML markup</strong><span class="badge">Editable</span></div>
                            <textarea name="theme_body_html" id="theme-body" rows="16" placeholder="Theme HTML will render here. You can also write or paste your own markup."><?= e((string)($editTemplate['theme_html'] ?? (($editTemplate['type'] ?? 'email') === 'email' ? ($editTemplate['body'] ?? '') : ''))) ?></textarea>
                            <div class="small muted">The builder keeps this HTML updated. You can make manual edits here for advanced layouts.</div>
                        </div>
                        <div class="theme-code-card">
                            <div class="toolbar compact-toolbar"><strong>Theme CSS</strong><span class="badge">Built-in editor</span></div>
                            <textarea name="theme_css" id="theme-css" rows="10" placeholder="Add CSS classes for your layout, typography, spacing, or responsive tweaks."><?= e((string)($editTemplate['theme_css'] ?? '')) ?></textarea>
                            <div class="small muted">CSS is embedded with the saved template and stays available in Campaign Studio and Mail Center previews.</div>
                        </div>
                        <div class="theme-preview-card">
                            <div class="toolbar compact-toolbar"><strong>Live preview</strong><span class="badge">Email-safe preview</span></div>
                            <iframe id="theme-preview-frame" title="Email theme preview"></iframe>
                        </div>
                    </div>
                </div>
            </div>

            <div class="theme-sms-shell mt-12" data-template-type-panel="sms">
                <div class="toolbar compact-toolbar"><strong>SMS/MMS template</strong><span class="badge">Quick template</span></div>
                <textarea name="sms_body_text" id="sms-body" rows="10" placeholder="Hi {{first_name}}, thanks for reaching out. Reply STOP to unsubscribe."><?= e((string)((($editTemplate['type'] ?? '') === 'sms') ? ($editTemplate['body'] ?? '') : '')) ?></textarea>
                <div class="small muted">Use merge variables like {{first_name}}, {{company}}, and {{unsubscribe_url}}.</div>
            </div>

            <div class="mt-12">
                <label class="small muted">Optional media or attachment</label>
                <input type="file" name="media_file">
                <?php if (!empty($editTemplate['media_path'])): ?>
                    <div class="small muted mt-12">Current file: <?= e((string)$editTemplate['media_path']) ?></div>
                <?php endif; ?>
            </div>

            <div class="actions-cell mt-12">
                <button class="btn primary"><?= !empty($editTemplate) ? 'Update Template' : 'Save Template' ?></button>
                <?php if (!empty($editTemplate)): ?><a class="btn secondary" href="index.php?route=templates/index">Cancel Edit</a><?php endif; ?>
            </div>
        </form>
    </div>

    <div class="card theme-library-card">
        <div class="toolbar">
            <h2>Saved Template Library</h2>
            <span class="badge"><?= count($templates) ?> saved</span>
        </div>
        <p class="small muted">Reuse saved email themes in Campaign Studio, one-to-one email sends, Mail Center replies, and commercial launch workflows.</p>
        <div class="theme-library-list mt-12">
            <?php foreach ($templates as $template): ?>
                <?php $excerpt = trim(preg_replace('/\s+/', ' ', strip_tags((string)(($template['type'] ?? '') === 'email' ? ($template['theme_html'] ?? $template['body'] ?? '') : ($template['body'] ?? ''))))); ?>
                <article class="theme-library-item">
                    <div class="theme-library-head">
                        <div>
                            <h3><?= e((string)$template['name']) ?></h3>
                            <div class="theme-library-meta">
                                <span class="mail-chip color-slate"><?= e(strtoupper((string)$template['type'])) ?></span>
                                <?php if (!empty($template['is_theme_template'])): ?><span class="mail-chip color-blue">Theme Creator</span><?php endif; ?>
                                <?php if (!empty($template['theme_preset'])): ?><span class="mail-chip color-violet"><?= e(ucfirst((string)$template['theme_preset'])) ?></span><?php endif; ?>
                            </div>
                        </div>
                        <div class="small muted">Updated <?= e(date('M j, Y g:i a', strtotime((string)$template['updated_at']))) ?></div>
                    </div>
                    <?php if (!empty($template['subject'])): ?><div class="small"><strong>Subject:</strong> <?= e((string)$template['subject']) ?></div><?php endif; ?>
                    <p class="small muted"><?= e($excerpt !== '' ? ((strlen($excerpt) > 180) ? (substr($excerpt, 0, 177) . '…') : $excerpt) : 'Saved template ready for reuse.') ?></p>
                    <div class="actions-cell">
                        <a class="btn secondary small" href="index.php?route=templates/index&edit=<?= (int)$template['id'] ?>">Edit</a>
                        <a class="btn danger small" href="index.php?route=templates/delete&id=<?= (int)$template['id'] ?>" onclick="return confirm('Delete template?')">Delete</a>
                    </div>
                </article>
            <?php endforeach; ?>
            <?php if (empty($templates)): ?>
                <div class="muted">No templates saved yet.</div>
            <?php endif; ?>
        </div>
    </div>
</section>

<script>
window.__EMAIL_THEME_EDITOR__ = <?= json_encode($templateEditorState ?? [], JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) ?>;
</script>
