<?php
/**
 * Certificate & Marksheet Mapping — Drag & Drop Editor
 *
 * Features:
 *   - A4 PORTRAIT fixed size (210mm × 297mm = 595pt × 842pt)
 *   - Visual drag-and-drop canvas with the JPG background
 *   - Drag field labels to position them on the image
 *   - X/Y coordinates auto-update as you drag
 *   - Side panel to edit font/size/color/alignment per field
 *   - Enable/disable fields with checkboxes
 *   - Grid overlay for alignment (toggleable)
 *   - Zoom controls
 *   - Touch support for tablets
 */
$bp = defined('BASE_PATH') ? BASE_PATH : '/gmind';
$course = $course ?? [];
$template = $template ?? [];
$type = $type ?? 'certificate';
$fieldKeys = $fieldKeys ?? [];
$fieldsByKey = $fieldsByKey ?? [];
$csrfToken = $csrfToken ?? '';

$bgUrl = '';
if (!empty($template['background_image'])) {
    $bgUrl = $bp . '/' . ltrim($template['background_image'], '/');
}

// A4 PORTRAIT: 210mm × 297mm = 595pt × 842pt (fixed)
$A4_W = 595;
$A4_H = 842;

// Display scale: canvas displayed at 500px wide on screen (portrait is taller)
$displayW = 500;
$displayH = (int)($displayW * ($A4_H / $A4_W)); // ~707px
$scale = $displayW / $A4_W; // ~0.840
?>
<style>
/* ─── Drag & Drop Mapping Editor ─── */
.dd-container { display: grid; grid-template-columns: 1fr 320px; gap: 16px; }
@media (max-width: 1100px) { .dd-container { grid-template-columns: 1fr; } }

.dd-canvas-wrap {
    background: #f0f0f0; padding: 20px; border-radius: 12px;
    display: flex; flex-direction: column; align-items: center;
}
.dd-toolbar {
    width: <?= $displayW ?>px; max-width: 100%; display: flex;
    justify-content: space-between; align-items: center;
    margin-bottom: 12px; flex-wrap: wrap; gap: 8px;
}
.dd-toolbar-left { display: flex; gap: 8px; align-items: center; }
.dd-toolbar-right { display: flex; gap: 8px; align-items: center; }
.dd-btn {
    padding: 6px 12px; border: 1px solid #ccc; border-radius: 6px;
    background: #fff; cursor: pointer; font-size: 0.78rem; font-weight: 600;
    color: #333; transition: all 0.15s;
}
.dd-btn:hover { background: #f0f0f0; }
.dd-btn.active { background: #6c3fe8; color: #fff; border-color: #6c3fe8; }
.dd-a4-badge {
    background: #eaf0fb; color: #1a4fa0; padding: 4px 10px;
    border-radius: 4px; font-size: 0.72rem; font-weight: 700;
}

.dd-canvas {
    width: <?= $displayW ?>px; height: <?= $displayH ?>px;
    position: relative; border: 2px solid #333; border-radius: 4px;
    overflow: hidden; background: #fff;
    box-shadow: 0 4px 20px rgba(0,0,0,0.1);
    user-select: none; -webkit-user-select: none;
}
.dd-canvas-bg {
    position: absolute; top: 0; left: 0;
    width: 100%; height: 100%;
    object-fit: fill; pointer-events: none;
}
.dd-canvas-placeholder {
    position: absolute; top: 50%; left: 50%;
    transform: translate(-50%, -50%);
    color: #ccc; font-size: 0.9rem; text-align: center;
    pointer-events: none;
}
.dd-grid-overlay {
    position: absolute; top: 0; left: 0;
    width: 100%; height: 100%; pointer-events: none;
    background-image:
        linear-gradient(to right, rgba(108,63,232,0.08) 1px, transparent 1px),
        linear-gradient(to bottom, rgba(108,63,232,0.08) 1px, transparent 1px);
    background-size: <?= round($displayW / 20) ?>px <?= round($displayH / 14) ?>px;
    display: none;
}
.dd-grid-overlay.show { display: block; }

.dd-field {
    position: absolute; padding: 3px 8px; border-radius: 4px;
    font-size: 0.76rem; cursor: move; white-space: nowrap;
    border: 2px dashed transparent; transition: border-color 0.15s;
    user-select: none; -webkit-user-select: none;
    touch-action: none; /* enables touch dragging */
}
.dd-field:hover { border-color: rgba(108,63,232,0.5); }
.dd-field.selected {
    border-color: #6c3fe8; border-style: solid;
    box-shadow: 0 2px 8px rgba(108,63,232,0.3);
    z-index: 10;
}
.dd-field.dragging { opacity: 0.7; cursor: grabbing; }
.dd-field-label {
    font-size: 0.62rem; color: #999; display: block;
    margin-bottom: 1px; font-weight: 600; text-transform: uppercase;
}
.dd-field-text {
    font-weight: 600; pointer-events: none;
}
.dd-field-handle {
    position: absolute; top: -6px; right: -6px;
    width: 14px; height: 14px; background: #6c3fe8;
    border-radius: 50%; cursor: pointer; border: 2px solid #fff;
    display: none;
}
.dd-field.selected .dd-field-handle { display: block; }

/* ─── Side Panel ─── */
.dd-side-panel {
    background: #fff; border-radius: 12px; padding: 18px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.06);
    max-height: 600px; overflow-y: auto;
}
.dd-side-title {
    font-size: 0.92rem; font-weight: 700; color: #2c1e4a;
    margin: 0 0 12px; padding-bottom: 8px;
    border-bottom: 2px solid #f0f0f0;
}
.dd-field-list { list-style: none; padding: 0; margin: 0; }
.dd-field-list-item {
    display: flex; align-items: center; gap: 8px;
    padding: 8px 10px; border-radius: 6px;
    cursor: pointer; transition: background 0.15s;
    border: 1px solid transparent; margin-bottom: 4px;
}
.dd-field-list-item:hover { background: #f8f5fc; }
.dd-field-list-item.selected {
    background: #f0eafa; border-color: #6c3fe8;
}
.dd-field-list-item input[type=checkbox] {
    accent-color: #6c3fe8; cursor: pointer; width: 16px; height: 16px;
}
.dd-field-list-item .fi-label {
    flex: 1; font-size: 0.8rem; font-weight: 600; color: #333;
}
.dd-field-list-item .fi-type {
    font-size: 0.62rem; color: #999; text-transform: uppercase;
}
.dd-field-list-item.disabled .fi-label { color: #999; text-decoration: line-through; }

/* ─── Properties Panel (shown when a field is selected) ─── */
.dd-props {
    margin-top: 14px; padding-top: 14px;
    border-top: 2px solid #f0f0f0; display: none;
}
.dd-props.show { display: block; }
.dd-props h4 {
    margin: 0 0 10px; font-size: 0.84rem; color: #6c3fe8;
    text-transform: uppercase; letter-spacing: 0.5px;
}
.dd-prop-row {
    display: grid; grid-template-columns: 1fr 1fr; gap: 8px; margin-bottom: 8px;
}
.dd-prop-row.full { grid-template-columns: 1fr; }
.dd-prop-label {
    font-size: 0.72rem; font-weight: 600; color: #666;
    margin-bottom: 3px; display: block;
}
.dd-prop-input {
    width: 100%; padding: 5px 8px; border: 1px solid #ddd;
    border-radius: 4px; font-size: 0.78rem;
}
.dd-prop-select {
    width: 100%; padding: 5px 8px; border: 1px solid #ddd;
    border-radius: 4px; font-size: 0.78rem; background: #fff;
}
.dd-prop-color {
    width: 100%; height: 30px; border: 1px solid #ddd;
    border-radius: 4px; cursor: pointer;
}

/* ─── Save Bar ─── */
.dd-save-bar {
    margin-top: 16px; padding: 14px; background: #f8f5fc;
    border-radius: 8px; display: flex; justify-content: space-between;
    align-items: center; gap: 10px; flex-wrap: wrap;
}
.dd-upload-btn {
    padding: 8px 16px; background: #6c3fe8; color: #fff;
    border: none; border-radius: 6px; font-size: 0.82rem;
    font-weight: 600; cursor: pointer;
}
.dd-save-btn {
    padding: 10px 28px; background: linear-gradient(135deg, #6c3fe8, #4a2db8);
    color: #fff; border: none; border-radius: 8px;
    font-size: 0.9rem; font-weight: 700; cursor: pointer;
    box-shadow: 0 4px 12px rgba(108,63,232,0.3);
}
</style>

<div class="admin-section">
    <div style="margin-bottom:14px;">
        <a href="<?= $bp ?>/super-admin/cert-marksheet-mapping" style="color:#6c3fe8;text-decoration:none;font-size:0.85rem;">← Back to Mappings</a>
    </div>

    <div style="background:linear-gradient(135deg,#2c1e4a,#4a2db8);color:#fff;border-radius:12px;padding:18px;margin-bottom:18px;">
        <h1 style="margin:0;font-size:1.15rem;">
            <?= $type === 'certificate' ? '📜' : '📋' ?> <?= ucfirst($type) ?> Mapping — Drag & Drop Editor
        </h1>
        <p style="margin:6px 0 0;opacity:0.9;font-size:0.84rem;">
            Course: <strong><?= htmlspecialchars($course['name'], ENT_QUOTES, 'UTF-8') ?></strong> ·
            Size: <strong>A4 Portrait (210mm × 297mm)</strong> — fixed
        </p>
    </div>

    <!-- Instructions -->
    <div style="background:#eaf0fb;border-left:4px solid #1a4fa0;padding:12px 16px;border-radius:8px;margin-bottom:16px;font-size:0.82rem;color:#1a4fa0;line-height:1.6;">
        <strong>📌 How to use:</strong>
        <ol style="margin:4px 0 0 18px;padding:0;">
            <li>Upload a JPG/PNG background image (A4 portrait recommended: 210mm × 297mm).</li>
            <li>Enable fields from the right panel by ticking their checkboxes.</li>
            <li><strong>Drag</strong> enabled fields onto the canvas to position them.</li>
            <li>Click a field on the canvas to select it → edit font/size/color in the properties panel.</li>
            <li>Use the grid toggle for alignment help.</li>
            <li>Click <strong>"Save Mapping"</strong> when done.</li>
        </ol>
    </div>

    <form method="POST" action="<?= $bp ?>/super-admin/cert-marksheet-mapping/save" enctype="multipart/form-data" id="mappingForm">
        <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrfToken, ENT_QUOTES, 'UTF-8') ?>">
        <input type="hidden" name="course_id" value="<?= (int)$course['id'] ?>">
        <input type="hidden" name="type" value="<?= htmlspecialchars($type, ENT_QUOTES, 'UTF-8') ?>">
        <input type="hidden" name="template_id" value="<?= (int)$template['id'] ?>">
        <input type="hidden" name="template_width" value="<?= $A4_W ?>">
        <input type="hidden" name="template_height" value="<?= $A4_H ?>">

        <div class="dd-container">
            <!-- LEFT: Canvas -->
            <div class="dd-canvas-wrap">
                <!-- Toolbar -->
                <div class="dd-toolbar">
                    <div class="dd-toolbar-left">
                        <span class="dd-a4-badge">📐 A4 Portrait · 595×842pt</span>
                        <button type="button" class="dd-btn" id="gridToggle" onclick="toggleGrid()">📊 Grid</button>
                        <button type="button" class="dd-btn" onclick="zoomCanvas(-0.1)">−</button>
                        <span id="zoomLevel" style="font-size:0.74rem;color:#666;min-width:40px;text-align:center;">100%</span>
                        <button type="button" class="dd-btn" onclick="zoomCanvas(0.1)">+</button>
                    </div>
                    <div class="dd-toolbar-right">
                        <label class="dd-upload-btn" style="cursor:pointer;">
                            📁 Upload Background
                            <input type="file" name="background_image" accept="image/jpeg,image/png" style="display:none;" onchange="previewBg(this)">
                        </label>
                    </div>
                </div>

                <!-- Canvas -->
                <div class="dd-canvas" id="ddCanvas" style="width:<?= $displayW ?>px;height:<?= $displayH ?>px;">
                    <?php if ($bgUrl): ?>
                    <img class="dd-canvas-bg" src="<?= htmlspecialchars($bgUrl, ENT_QUOTES, 'UTF-8') ?>" alt="Background" id="bgImg">
                    <?php else: ?>
                    <div class="dd-canvas-placeholder">
                        📁 No background uploaded<br>
                        <span style="font-size:0.74rem;">Click "Upload Background" above</span>
                    </div>
                    <?php endif; ?>
                    <div class="dd-grid-overlay" id="gridOverlay"></div>
                    <!-- Draggable fields will be inserted here by JS -->
                </div>

                <p style="margin:10px 0 0;font-size:0.74rem;color:#999;">
                    💡 Drag fields to position them. Coordinates are in points (pt). A4 portrait = 595×842pt.
                </p>
            </div>

            <!-- RIGHT: Side Panel -->
            <div class="dd-side-panel">
                <h3 class="dd-side-title">📍 Fields (<?= count($fieldKeys) ?>)</h3>
                <ul class="dd-field-list" id="fieldList">
                    <?php $i = 0; foreach ($fieldKeys as $fkey => $fdef):
                        $existing = $fieldsByKey[$fkey] ?? [];
                        // Enable ALL fields by default
                        $enabled = true;
                    ?>
                    <li class="dd-field-list-item" data-field="<?= htmlspecialchars($fkey, ENT_QUOTES, 'UTF-8') ?>" onclick="selectField('<?= htmlspecialchars($fkey, ENT_QUOTES, 'UTF-8') ?>')">
                        <input type="checkbox" checked onchange="toggleField('<?= htmlspecialchars($fkey, ENT_QUOTES, 'UTF-8') ?>', this.checked)" onclick="event.stopPropagation()">
                        <span class="fi-label"><?= htmlspecialchars($fdef['label'], ENT_QUOTES, 'UTF-8') ?></span>
                        <span class="fi-type"><?= $fdef['type'] ?></span>
                    </li>
                    <?php $i++; endforeach; ?>
                </ul>

                <!-- Properties Panel (shows when a field is selected) -->
                <div class="dd-props" id="propsPanel">
                    <h4 id="propsTitle">Field Properties</h4>
                    <div class="dd-prop-row">
                        <div>
                            <label class="dd-prop-label">X Position (pt)</label>
                            <input type="number" class="dd-prop-input" id="propX" oninput="updateFieldPos('x', this.value)">
                        </div>
                        <div>
                            <label class="dd-prop-label">Y Position (pt)</label>
                            <input type="number" class="dd-prop-input" id="propY" oninput="updateFieldPos('y', this.value)">
                        </div>
                    </div>
                    <div class="dd-prop-row">
                        <div>
                            <label class="dd-prop-label">Width (pt)</label>
                            <input type="number" class="dd-prop-input" id="propWidth" oninput="updateFieldProp('width', this.value)">
                        </div>
                        <div>
                            <label class="dd-prop-label">Font Size</label>
                            <input type="number" class="dd-prop-input" id="propFontSize" oninput="updateFieldProp('font_size', this.value)">
                        </div>
                    </div>
                    <div class="dd-prop-row">
                        <div>
                            <label class="dd-prop-label">Font Family</label>
                            <select class="dd-prop-select" id="propFontFamily" onchange="updateFieldProp('font_family', this.value)">
                                <option value="Arial">Arial</option>
                                <option value="Helvetica">Helvetica</option>
                                <option value="Times">Times</option>
                                <option value="Courier">Courier</option>
                            </select>
                        </div>
                        <div>
                            <label class="dd-prop-label">Style</label>
                            <select class="dd-prop-select" id="propFontStyle" onchange="updateFieldProp('font_style', this.value)">
                                <option value="regular">Regular</option>
                                <option value="bold">Bold</option>
                                <option value="italic">Italic</option>
                                <option value="bold-italic">Bold Italic</option>
                            </select>
                        </div>
                    </div>
                    <div class="dd-prop-row">
                        <div>
                            <label class="dd-prop-label">Color</label>
                            <input type="color" class="dd-prop-color" id="propFontColor" onchange="updateFieldProp('font_color', this.value)">
                        </div>
                        <div>
                            <label class="dd-prop-label">Alignment</label>
                            <select class="dd-prop-select" id="propAlign" onchange="updateFieldProp('align', this.value)">
                                <option value="left">Left</option>
                                <option value="center">Center</option>
                                <option value="right">Right</option>
                            </select>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Save Bar -->
        <div class="dd-save-bar">
            <div style="font-size:0.82rem;color:#666;">
                💡 Fields are auto-positioned as you drag. Click "Save Mapping" to store positions permanently.
            </div>
            <button type="submit" class="dd-save-btn">💾 Save Mapping</button>
        </div>

        <!-- Hidden field data inputs (populated by JS before submit) -->
        <div id="hiddenFieldsContainer"></div>
    </form>
</div>

<script>
(function() {
    'use strict';

    // Configuration
    var A4_W = <?= $A4_W ?>;  // 595pt (portrait)
    var A4_H = <?= $A4_H ?>;  // 842pt (portrait)
    var displayW = <?= $displayW ?>;
    var displayH = <?= $displayH ?>;
    var scale = displayW / A4_W;  // ~0.831
    var zoom = 1.0;

    // Field definitions from PHP
    var fieldDefs = <?= json_encode($fieldKeys) ?>;
    var existingFields = <?= json_encode($fieldsByKey) ?>;

    // State
    var selectedField = null;
    var fieldStates = {};  // {field_key: {enabled, x, y, width, font_size, font_family, font_style, font_color, align}}

    // Initialize field states — ALL 15 fields enabled by default
    var idx = 0;
    Object.keys(fieldDefs).forEach(function(fkey) {
        var existing = existingFields[fkey] || {};
        var def = fieldDefs[fkey];
        // Enable ALL fields by default (was only first 5)
        var isEnabled = !!(existing.field_key) || true;  // always true
        // For photo/qr_code, use larger default positions
        var defaultX = 20, defaultY = idx * 40 + 20;
        if (fkey === 'photo') { defaultX = 400; defaultY = 50; }
        if (fkey === 'qr_code') { defaultX = 400; defaultY = 500; }
        if (fkey === 'from_date') { defaultX = 100; defaultY = 500; }
        if (fkey === 'to_date') { defaultX = 300; defaultY = 500; }
        if (fkey === 'subject_marks') { defaultX = 50; defaultY = 600; }

        fieldStates[fkey] = {
            enabled: isEnabled,
            x: parseInt(existing.x_pos) || defaultX,
            y: parseInt(existing.y_pos) || defaultY,
            width: parseInt(existing.width) || 0,
            font_size: parseInt(existing.font_size) || def.default_size,
            font_family: existing.font_family || def.default_font,
            font_style: existing.font_style || 'regular',
            font_color: existing.font_color || '#000000',
            align: existing.align || 'left',
        };
        idx++;
    });

    // ─── Render fields on canvas ───────────────────────────────
    function renderFields() {
        var canvas = document.getElementById('ddCanvas');
        // Remove existing field elements
        canvas.querySelectorAll('.dd-field').forEach(function(el) { el.remove(); });

        Object.keys(fieldStates).forEach(function(fkey) {
            var state = fieldStates[fkey];
            if (!state.enabled) return;

            var def = fieldDefs[fkey];
            var el = document.createElement('div');
            el.className = 'dd-field';
            el.dataset.fieldKey = fkey;
            el.style.left = (state.x * scale * zoom) + 'px';
            el.style.top = (state.y * scale * zoom) + 'px';
            if (state.width > 0) el.style.width = (state.width * scale * zoom) + 'px';

            // Apply font properties — but NOT for image/qrcode/table types (they have their own sizing)
            var fontWeight = (state.font_style === 'bold' || state.font_style === 'bold-italic') ? 'bold' : 'normal';
            var fontStyle = (state.font_style === 'italic' || state.font_style === 'bold-italic') ? 'italic' : 'normal';

            // Special styling for QR code, photo, and table — use FIXED display sizes
            if (def.type === 'qrcode') {
                el.style.background = '#f0eafa';
                el.style.border = '2px dashed #6c3fe8';
                el.style.borderRadius = '4px';
                var qrDisplaySize = Math.max(40, state.font_size * scale * zoom * 0.5);
                el.style.minWidth = qrDisplaySize + 'px';
                el.style.minHeight = qrDisplaySize + 'px';
                el.style.width = qrDisplaySize + 'px';
                el.style.height = qrDisplaySize + 'px';
                el.style.display = 'flex';
                el.style.alignItems = 'center';
                el.style.justifyContent = 'center';
                el.style.flexDirection = 'column';
                el.style.padding = '4px';
                el.innerHTML = '<span class="dd-field-label">' + fkey + '</span><span class="dd-field-text" style="font-size:9px;">📷 QR</span><div class="dd-field-handle"></div>';
            } else if (def.type === 'image') {
                el.style.background = '#eaf0fb';
                el.style.border = '2px dashed #1a4fa0';
                el.style.borderRadius = '4px';
                var imgW = Math.max(40, state.font_size * scale * zoom * 0.4);
                var imgH = Math.max(50, imgW * 1.3);
                el.style.minWidth = imgW + 'px';
                el.style.minHeight = imgH + 'px';
                el.style.width = imgW + 'px';
                el.style.height = imgH + 'px';
                el.style.display = 'flex';
                el.style.alignItems = 'center';
                el.style.justifyContent = 'center';
                el.style.flexDirection = 'column';
                el.style.padding = '4px';
                el.style.fontSize = '9px';
                el.innerHTML = '<span class="dd-field-label">' + fkey + '</span><span class="dd-field-text" style="font-size:9px;">👤 PHOTO</span><div class="dd-field-handle"></div>';
            } else if (def.type === 'table') {
                el.style.background = '#eafaf1';
                el.style.border = '2px dashed #27ae60';
                el.style.borderRadius = '4px';
                el.style.minWidth = '200px';
                el.style.minHeight = '100px';
                el.style.padding = '8px';
                el.style.fontSize = '9px';
                el.style.color = '#27ae60';
                el.style.fontWeight = 'bold';
                el.innerHTML = '<span class="dd-field-label">' + fkey + '</span><span class="dd-field-text" style="font-size:9px;">📋 Subject Marks Table<br>(Subject | Max | Obtained)<br>Only on Marksheet</span><div class="dd-field-handle"></div>';
            } else {
                // Normal text field
                el.style.fontFamily = state.font_family;
                el.style.fontSize = Math.max(8, state.font_size * scale * zoom) + 'px';
                el.style.color = state.font_color;
                el.style.fontWeight = fontWeight;
                el.style.fontStyle = fontStyle;
                el.style.textAlign = state.align;
                el.style.padding = '3px 8px';
                el.innerHTML = '<span class="dd-field-label">' + fkey + '</span><span class="dd-field-text">' + def.label + '</span><div class="dd-field-handle"></div>';
            }

            // Click to select
            el.addEventListener('click', function(e) {
                e.stopPropagation();
                selectField(fkey);
            });

            // Drag handling
            makeDraggable(el, fkey);

            canvas.appendChild(el);
        });
    }

    // ─── Make element draggable (mouse + touch) ────────────────
    function makeDraggable(el, fkey) {
        var isDragging = false;
        var startX, startY, startLeft, startTop;

        function onStart(clientX, clientY) {
            isDragging = true;
            el.classList.add('dragging');
            selectField(fkey);
            startX = clientX;
            startY = clientY;
            startLeft = parseInt(el.style.left) || 0;
            startTop = parseInt(el.style.top) || 0;
            e.preventDefault && e.preventDefault();
        }

        function onMove(clientX, clientY) {
            if (!isDragging) return;
            var dx = clientX - startX;
            var dy = clientY - startY;
            var newLeft = Math.max(0, Math.min(displayW * zoom - 20, startLeft + dx));
            var newTop = Math.max(0, Math.min(displayH * zoom - 20, startTop + dy));
            el.style.left = newLeft + 'px';
            el.style.top = newTop + 'px';
            // Update state (convert display px to points)
            fieldStates[fkey].x = Math.round(newLeft / (scale * zoom));
            fieldStates[fkey].y = Math.round(newTop / (scale * zoom));
            // Update properties panel
            if (selectedField === fkey) {
                document.getElementById('propX').value = fieldStates[fkey].x;
                document.getElementById('propY').value = fieldStates[fkey].y;
            }
        }

        function onEnd() {
            if (!isDragging) return;
            isDragging = false;
            el.classList.remove('dragging');
        }

        // Mouse events
        el.addEventListener('mousedown', function(e) {
            onStart(e.clientX, e.clientY);
        });
        document.addEventListener('mousemove', function(e) {
            if (isDragging) onMove(e.clientX, e.clientY);
        });
        document.addEventListener('mouseup', onEnd);

        // Touch events
        el.addEventListener('touchstart', function(e) {
            if (e.touches.length === 1) onStart(e.touches[0].clientX, e.touches[0].clientY);
        }, {passive: false});
        document.addEventListener('touchmove', function(e) {
            if (isDragging && e.touches.length === 1) {
                onMove(e.touches[0].clientX, e.touches[0].clientY);
                e.preventDefault();
            }
        }, {passive: false});
        document.addEventListener('touchend', onEnd);
    }

    // ─── Select a field ────────────────────────────────────────
    window.selectField = function(fkey) {
        selectedField = fkey;
        // Update canvas
        document.querySelectorAll('.dd-field').forEach(function(el) {
            el.classList.toggle('selected', el.dataset.fieldKey === fkey);
        });
        // Update side panel
        document.querySelectorAll('.dd-field-list-item').forEach(function(li) {
            li.classList.toggle('selected', li.dataset.field === fkey);
        });
        // Show properties panel
        var state = fieldStates[fkey];
        var def = fieldDefs[fkey];
        document.getElementById('propsPanel').classList.add('show');
        document.getElementById('propsTitle').textContent = 'Field: ' + fkey + ' (' + def.label + ')';
        document.getElementById('propX').value = state.x;
        document.getElementById('propY').value = state.y;
        document.getElementById('propWidth').value = state.width;
        document.getElementById('propFontSize').value = state.font_size;
        document.getElementById('propFontFamily').value = state.font_family;
        document.getElementById('propFontStyle').value = state.font_style;
        document.getElementById('propFontColor').value = state.font_color;
        document.getElementById('propAlign').value = state.align;
    };

    // ─── Toggle field enabled/disabled ────────────────────────
    window.toggleField = function(fkey, enabled) {
        fieldStates[fkey].enabled = enabled;
        // Update side panel styling
        var li = document.querySelector('.dd-field-list-item[data-field="' + fkey + '"]');
        if (li) li.classList.toggle('disabled', !enabled);
        // Re-render canvas
        renderFields();
    };

    // ─── Update field position from properties panel ──────────
    window.updateFieldPos = function(axis, value) {
        if (!selectedField) return;
        var val = parseInt(value) || 0;
        fieldStates[selectedField][axis] = val;
        // Update canvas element position
        var el = document.querySelector('.dd-field[data-field-key="' + selectedField + '"]');
        if (el) {
            if (axis === 'x') el.style.left = (val * scale * zoom) + 'px';
            if (axis === 'y') el.style.top = (val * scale * zoom) + 'px';
        }
    };

    // ─── Update field property from properties panel ──────────
    window.updateFieldProp = function(prop, value) {
        if (!selectedField) return;
        fieldStates[selectedField][prop] = value;
        // Re-render to apply visual changes
        renderFields();
        // Re-select the field
        selectField(selectedField);
    };

    // ─── Grid toggle ───────────────────────────────────────────
    window.toggleGrid = function() {
        var overlay = document.getElementById('gridOverlay');
        var btn = document.getElementById('gridToggle');
        overlay.classList.toggle('show');
        btn.classList.toggle('active');
    };

    // ─── Zoom ──────────────────────────────────────────────────
    window.zoomCanvas = function(delta) {
        zoom = Math.max(0.5, Math.min(2.0, zoom + delta));
        var newW = Math.round(displayW * zoom);
        var newH = Math.round(displayH * zoom);
        var canvas = document.getElementById('ddCanvas');
        canvas.style.width = newW + 'px';
        canvas.style.height = newH + 'px';
        document.getElementById('zoomLevel').textContent = Math.round(zoom * 100) + '%';
        renderFields();
    };

    // ─── Preview background on upload ──────────────────────────
    window.previewBg = function(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();
            reader.onload = function(e) {
                var canvas = document.getElementById('ddCanvas');
                var oldImg = document.getElementById('bgImg');
                var placeholder = canvas.querySelector('.dd-canvas-placeholder');
                if (placeholder) placeholder.remove();
                if (oldImg) {
                    oldImg.src = e.target.result;
                } else {
                    var img = document.createElement('img');
                    img.className = 'dd-canvas-bg';
                    img.id = 'bgImg';
                    img.src = e.target.result;
                    canvas.insertBefore(img, canvas.firstChild);
                }
            };
            reader.readAsDataURL(input.files[0]);
        }
    };

    // ─── Deselect on canvas click ──────────────────────────────
    document.getElementById('ddCanvas').addEventListener('click', function(e) {
        if (e.target === this || e.target.classList.contains('dd-canvas-bg') || e.target.classList.contains('dd-canvas-placeholder')) {
            document.querySelectorAll('.dd-field').forEach(function(el) { el.classList.remove('selected'); });
            document.querySelectorAll('.dd-field-list-item').forEach(function(li) { li.classList.remove('selected'); });
            document.getElementById('propsPanel').classList.remove('show');
            selectedField = null;
        }
    });

    // ─── Populate hidden fields on form submit ─────────────────
    document.getElementById('mappingForm').addEventListener('submit', function() {
        var container = document.getElementById('hiddenFieldsContainer');
        container.innerHTML = '';
        var i = 0;
        Object.keys(fieldStates).forEach(function(fkey) {
            var state = fieldStates[fkey];
            container.innerHTML +=
                '<input type="hidden" name="field_key[' + i + ']" value="' + fkey + '">' +
                '<input type="hidden" name="is_enabled[' + i + ']" value="' + (state.enabled ? 1 : 0) + '">' +
                '<input type="hidden" name="x_pos[' + i + ']" value="' + state.x + '">' +
                '<input type="hidden" name="y_pos[' + i + ']" value="' + state.y + '">' +
                '<input type="hidden" name="field_width[' + i + ']" value="' + state.width + '">' +
                '<input type="hidden" name="font_size[' + i + ']" value="' + state.font_size + '">' +
                '<input type="hidden" name="font_family[' + i + ']" value="' + state.font_family + '">' +
                '<input type="hidden" name="font_style[' + i + ']" value="' + state.font_style + '">' +
                '<input type="hidden" name="font_color[' + i + ']" value="' + state.font_color + '">' +
                '<input type="hidden" name="align[' + i + ']" value="' + state.align + '">';
            i++;
        });
    });

    // ─── Initialize ────────────────────────────────────────────
    renderFields();
})();
</script>
