<?php
$editingEmail = (($editTemplate['type'] ?? 'email') === 'email');
?>
<section class="workspace-hero">
    <div>
        <h2>Email Theme Creator</h2>
        <p>Build a real drag-and-drop email designer with reusable blocks, a live preview, direct HTML/CSS access, and a saved template library for campaigns and one-to-one email sends.</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 theme-v2-layout">
    <div class="card theme-v2-editor-card">
        <div class="toolbar">
            <h2><?= !empty($editTemplate) ? 'Edit Template' : 'Create Template' ?></h2>
            <span class="badge"><?= !empty($editTemplate) ? 'Library item' : 'Drag-and-drop builder' ?></span>
        </div>
        <p class="small muted">Drag blocks into the canvas, click any block to edit its content on the right, then fine-tune the HTML and CSS before saving. This builder keeps saved templates reusable in Campaign Studio, Mail Center, and individual email workflows.</p>

        <form method="post" action="index.php?route=templates/save" enctype="multipart/form-data" id="email-theme-form-v2" data-template-creator-v2>
            <?= 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-v2-toolbar mt-12">
                    <div class="theme-v2-toolbar-copy">
                        <strong>True Template Creator</strong>
                        <div class="small muted">Drag new blocks from the left rail, drop them anywhere in the canvas, and use the inspector to edit each section like a real email builder.</div>
                    </div>
                    <div class="theme-v2-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>
                        <span class="badge color-blue" id="theme-builder-status">Builder synced</span>
                        <button type="button" class="btn secondary small" id="theme-copy-html">Copy HTML</button>
                        <button type="button" class="btn secondary small" id="theme-rebuild-html">Rebuild from Canvas</button>
                    </div>
                </div>

                <div class="theme-v2-shell mt-12">
                    <aside class="theme-v2-palette-card">
                        <div class="theme-v2-panel-head">
                            <div>
                                <strong>Blocks</strong>
                                <div class="small muted">Click to add or drag into the canvas.</div>
                            </div>
                            <span class="badge">Drag &amp; drop</span>
                        </div>
                        <div class="theme-v2-palette-grid">
                            <button type="button" class="theme-v2-palette-item" data-theme-palette-item data-section="hero" draggable="true">
                                <strong>Hero</strong>
                                <span>Headline, intro, CTA</span>
                            </button>
                            <button type="button" class="theme-v2-palette-item" data-theme-palette-item data-section="text" draggable="true">
                                <strong>Text</strong>
                                <span>Copy block</span>
                            </button>
                            <button type="button" class="theme-v2-palette-item" data-theme-palette-item data-section="image" draggable="true">
                                <strong>Image</strong>
                                <span>Banner or visual</span>
                            </button>
                            <button type="button" class="theme-v2-palette-item" data-theme-palette-item data-section="columns" draggable="true">
                                <strong>Two Column</strong>
                                <span>Side-by-side content</span>
                            </button>
                            <button type="button" class="theme-v2-palette-item" data-theme-palette-item data-section="cta" draggable="true">
                                <strong>CTA</strong>
                                <span>Focused action panel</span>
                            </button>
                            <button type="button" class="theme-v2-palette-item" data-theme-palette-item data-section="divider" draggable="true">
                                <strong>Divider</strong>
                                <span>Spacing rule</span>
                            </button>
                            <button type="button" class="theme-v2-palette-item" data-theme-palette-item data-section="footer" draggable="true">
                                <strong>Footer</strong>
                                <span>Support and unsubscribe</span>
                            </button>
                        </div>
                        <div class="theme-v2-panel-note small muted">Tip: reorder blocks by dragging cards up and down the canvas or use the arrow controls on each block.</div>
                    </aside>

                    <section class="theme-v2-canvas-column">
                        <div class="theme-v2-panel-head">
                            <div>
                                <strong>Template canvas</strong>
                                <div class="small muted">Drop blocks between the blue lines to place them exactly where you want.</div>
                            </div>
                            <button type="button" class="btn danger small" id="theme-clear-canvas">Clear Canvas</button>
                        </div>
                        <div id="theme-canvas" class="theme-v2-canvas"></div>

                        <div class="theme-v2-code-grid">
                            <div class="theme-v2-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="14" placeholder="Canvas-generated HTML will appear here. You can also paste in your own custom email markup."><?= e((string)($editTemplate['theme_html'] ?? (($editTemplate['type'] ?? 'email') === 'email' ? ($editTemplate['body'] ?? '') : ''))) ?></textarea>
                                <div class="small muted">Typing here switches the preview into custom HTML mode until you click <strong>Rebuild from Canvas</strong>.</div>
                            </div>
                            <div class="theme-v2-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="14" placeholder="Add CSS classes for typography, spacing, or responsive tweaks."><?= e((string)($editTemplate['theme_css'] ?? '')) ?></textarea>
                                <div class="small muted">CSS is saved with the template and stays available in Campaign Studio and Mail Center previews.</div>
                            </div>
                        </div>
                    </section>

                    <aside class="theme-v2-inspector-column">
                        <div class="theme-v2-panel">
                            <div class="theme-v2-panel-head">
                                <div>
                                    <strong>Theme settings</strong>
                                    <div class="small muted">Adjust brand colors, width, typography, and radius.</div>
                                </div>
                            </div>
                            <div class="theme-v2-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>

                        <div class="theme-v2-panel">
                            <div class="theme-v2-panel-head">
                                <div>
                                    <strong>Block inspector</strong>
                                    <div class="small muted">Click a block in the canvas to edit its fields here.</div>
                                </div>
                            </div>
                            <div id="theme-section-inspector"></div>
                        </div>

                        <div class="theme-v2-panel 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>
                    </aside>
                </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_CREATOR_V2__ = <?= json_encode($templateEditorState ?? [], JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) ?>;
</script>
<script src="assets/js/template_creator_v2.js?v=16.6"></script>
