<?php
/**
 * Artifact Template Builder & Library Manager
 * Location: public_html/team/artifact-template-builder.php
 */

require_once __DIR__ . '/../connections/connect.php';
require_once __DIR__ . '/../includes/functions.php';

require_login();

$user_id = $_SESSION['user_id'];
$account_id = $_SESSION['account_id'];
$user_role = $_SESSION['role'] ?? 'TEAM_MEMBER';

$project_id = $_GET['project_id'] ?? '';
$action_success = '';
$action_error = '';

// ==========================================
// 1. QUERY COMPANY NAME & PRIMARY OWNER
// ==========================================
$company_name = $_SESSION['company_name'] ?? 'Company Name';
$primary_owner_name = ($_SESSION['first_name'] ?? '') . ' ' . ($_SESSION['last_name'] ?? '');

try {
    $stmt_acc = $pdo->prepare("
        SELECT a.company_name, u.first_name, u.last_name 
        FROM accounts a 
        LEFT JOIN users u ON a.id = u.account_id AND u.role = 'PRIMARY_ADMIN' 
        WHERE a.id = ? 
        ORDER BY u.created_at ASC 
        LIMIT 1
    ");
    $stmt_acc->execute([$account_id]);
    $account_info = $stmt_acc->fetch();
    if ($account_info) {
        if (!empty($account_info['company_name'])) {
            $company_name = $account_info['company_name'];
        }
        if (!empty($account_info['first_name'])) {
            $primary_owner_name = trim($account_info['first_name'] . ' ' . $account_info['last_name']);
        }
    }
} catch (Exception $e) {
    // Session fallback
}

// Project Context Check (if navigated from project_details.php)
$project_context = null;
if (!empty($project_id)) {
    try {
        $stmt_prj = $pdo->prepare("SELECT id, project_code, project_name, address FROM projects WHERE id = ? AND account_id = ?");
        $stmt_prj->execute([$project_id, $account_id]);
        $project_context = $stmt_prj->fetch();
    } catch (Exception $e) {
        $project_context = null;
    }
}

// ==========================================
// 2. HANDLE POST ACTIONS
// ==========================================
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    // Action A: Create New Custom Template with Fields
    if ($action === 'create_template') {
        $title = trim($_POST['title'] ?? '');
        $description = trim($_POST['description'] ?? '');
        $category = trim($_POST['category'] ?? 'General');
        $type = $_POST['type'] ?? 'QC_CHECKLIST';
        
        $field_labels = $_POST['field_label'] ?? [];
        $field_types = $_POST['field_type'] ?? [];
        $field_options = $_POST['field_options'] ?? [];
        $field_required = $_POST['field_required'] ?? [];
        $field_help = $_POST['field_help'] ?? [];

        if (empty($title)) {
            $action_error = "Template title is required.";
        } else {
            try {
                $template_id = 'tmpl_' . bin2hex(random_bytes(6));

                $pdo->beginTransaction();

                $stmt_ins = $pdo->prepare("
                    INSERT INTO artifact_templates (id, account_id, type, title, description, category, is_standard_template) 
                    VALUES (?, ?, ?, ?, ?, ?, 0)
                ");
                $stmt_ins->execute([$template_id, $account_id, $type, $title, $description, $category]);

                // Insert Questions / Fields
                if (is_array($field_labels) && count($field_labels) > 0) {
                    $stmt_fld = $pdo->prepare("
                        INSERT INTO artifact_template_fields (id, template_id, field_label, field_type, options_json, is_required, help_text, sort_order) 
                        VALUES (?, ?, ?, ?, ?, ?, ?, ?)
                    ");

                    foreach ($field_labels as $idx => $label) {
                        $trimmed_label = trim($label);
                        if (empty($trimmed_label)) continue;

                        $f_id = 'fld_' . bin2hex(random_bytes(6));
                        $f_type = $field_types[$idx] ?? 'SINGLE_CHOICE';
                        $f_req = !empty($field_required[$idx]) ? 1 : 0;
                        $f_help_text = trim($field_help[$idx] ?? '');
                        
                        $f_opts = null;
                        if (in_array($f_type, ['SINGLE_CHOICE', 'MULTI_CHOICE', 'DROPDOWN']) && !empty($field_options[$idx])) {
                            $opts_raw = explode(',', $field_options[$idx]);
                            $opts_arr = array_values(array_filter(array_map('trim', $opts_raw)));
                            if (!empty($opts_arr)) {
                                $f_opts = json_encode($opts_arr);
                            }
                        }

                        $stmt_fld->execute([$f_id, $template_id, $trimmed_label, $f_type, $f_opts, $f_req, $f_help_text, $idx + 1]);
                    }
                }

                // Audit log
                $stmt_log = $pdo->prepare("INSERT INTO audit_logs (id, account_id, user_id, action, details) VALUES (?, ?, ?, 'TEMPLATE_CREATED', ?)");
                $stmt_log->execute(['log_' . bin2hex(random_bytes(6)), $account_id, $user_id, "Created custom template: $title (ID: $template_id)"]);

                $pdo->commit();

                // If user checked "Attach to project now"
                if (!empty($_POST['attach_to_project_now']) && !empty($project_id)) {
                    $art_id = 'art_' . bin2hex(random_bytes(6));
                    $stmt_art = $pdo->prepare("
                        INSERT INTO project_artifacts (id, project_id, template_id, title, type, status) 
                        VALUES (?, ?, ?, ?, ?, 'DRAFT')
                    ");
                    $stmt_art->execute([$art_id, $project_id, $template_id, $title, $type]);
                    header("Location: project_details.php?id=" . urlencode($project_id) . "&attached=1");
                    exit;
                }

                $action_success = "Template <strong>" . htmlspecialchars($title) . "</strong> created successfully!";
            } catch (Exception $e) {
                if ($pdo->inTransaction()) {
                    $pdo->rollBack();
                }
                $action_error = "Error creating template: " . $e->getMessage();
            }
        }
    }

    // Action B: Clone Template (from Standard or existing)
    elseif ($action === 'clone_template') {
        $source_id = trim($_POST['source_template_id'] ?? '');

        if (empty($source_id)) {
            $action_error = "Invalid template selection.";
        } else {
            try {
                $stmt_src = $pdo->prepare("SELECT * FROM artifact_templates WHERE id = ? AND (account_id = ? OR account_id IS NULL OR is_standard_template = 1)");
                $stmt_src->execute([$source_id, $account_id]);
                $src = $stmt_src->fetch();

                if (!$src) {
                    $action_error = "Source template not found.";
                } else {
                    $new_tmpl_id = 'tmpl_' . bin2hex(random_bytes(6));
                    $new_title = $src['title'] . ' (Custom Copy)';

                    $pdo->beginTransaction();

                    $stmt_ins = $pdo->prepare("
                        INSERT INTO artifact_templates (id, account_id, type, title, description, category, is_standard_template) 
                        VALUES (?, ?, ?, ?, ?, ?, 0)
                    ");
                    $stmt_ins->execute([$new_tmpl_id, $account_id, $src['type'], $new_title, $src['description'], $src['category']]);

                    // Clone fields
                    $stmt_flds = $pdo->prepare("SELECT * FROM artifact_template_fields WHERE template_id = ? ORDER BY sort_order ASC");
                    $stmt_flds->execute([$source_id]);
                    $src_fields = $stmt_flds->fetchAll();

                    $stmt_fld_ins = $pdo->prepare("
                        INSERT INTO artifact_template_fields (id, template_id, field_label, field_type, options_json, is_required, help_text, sort_order) 
                        VALUES (?, ?, ?, ?, ?, ?, ?, ?)
                    ");

                    foreach ($src_fields as $f) {
                        $new_f_id = 'fld_' . bin2hex(random_bytes(6));
                        $stmt_fld_ins->execute([
                            $new_f_id,
                            $new_tmpl_id,
                            $f['field_label'],
                            $f['field_type'],
                            $f['options_json'],
                            $f['is_required'],
                            $f['help_text'],
                            $f['sort_order']
                        ]);
                    }

                    $pdo->commit();
                    $action_success = "Cloned <strong>" . htmlspecialchars($new_title) . "</strong> into your company templates! You can now customize its fields.";
                }
            } catch (Exception $e) {
                if ($pdo->inTransaction()) {
                    $pdo->rollBack();
                }
                $action_error = "Error cloning template: " . $e->getMessage();
            }
        }
    }

    // Action C: Delete Custom Template
    elseif ($action === 'delete_template') {
        $del_id = trim($_POST['template_id'] ?? '');
        try {
            $stmt_del = $pdo->prepare("DELETE FROM artifact_templates WHERE id = ? AND account_id = ?");
            $stmt_del->execute([$del_id, $account_id]);
            if ($stmt_del->rowCount() > 0) {
                $action_success = "Custom template removed.";
            } else {
                $action_error = "Template not found or cannot be deleted (system standard templates are protected).";
            }
        } catch (Exception $e) {
            $action_error = "Error deleting template: " . $e->getMessage();
        }
    }

    // Action D: Attach Existing Template to Project
    elseif ($action === 'attach_to_project') {
        $attach_tmpl_id = trim($_POST['template_id'] ?? '');
        $tgt_project_id = trim($_POST['project_id'] ?? $project_id);

        if (!empty($attach_tmpl_id) && !empty($tgt_project_id)) {
            try {
                $stmt_tmpl = $pdo->prepare("SELECT * FROM artifact_templates WHERE id = ? AND (account_id = ? OR account_id IS NULL OR is_standard_template = 1)");
                $stmt_tmpl->execute([$attach_tmpl_id, $account_id]);
                $tmpl_data = $stmt_tmpl->fetch();

                if ($tmpl_data) {
                    $art_id = 'art_' . bin2hex(random_bytes(6));
                    $stmt_art = $pdo->prepare("
                        INSERT INTO project_artifacts (id, project_id, template_id, title, type, status) 
                        VALUES (?, ?, ?, ?, ?, 'DRAFT')
                    ");
                    $stmt_art->execute([$art_id, $tgt_project_id, $attach_tmpl_id, $tmpl_data['title'], $tmpl_data['type']]);

                    header("Location: project_details.php?id=" . urlencode($tgt_project_id) . "&attached=1");
                    exit;
                }
            } catch (Exception $e) {
                $action_error = "Error attaching template to project: " . $e->getMessage();
            }
        }
    }
}

// ==========================================
// 3. FETCH TEMPLATES & ASSOCIATED FIELDS
// ==========================================
try {
    $stmt_all_tmpl = $pdo->prepare("
        SELECT t.*, 
               COUNT(f.id) AS field_count,
               (CASE WHEN t.account_id IS NULL OR t.is_standard_template = 1 THEN 1 ELSE 0 END) AS is_standard
        FROM artifact_templates t
        LEFT JOIN artifact_template_fields f ON t.id = f.template_id
        WHERE t.account_id = ? OR t.account_id IS NULL OR t.is_standard_template = 1
        GROUP BY t.id
        ORDER BY is_standard DESC, t.created_at DESC
    ");
    $stmt_all_tmpl->execute([$account_id]);
    $templates = $stmt_all_tmpl->fetchAll();

    // Fetch all fields mapped by template_id for live preview modals
    $stmt_fields = $pdo->prepare("
        SELECT f.* 
        FROM artifact_template_fields f
        INNER JOIN artifact_templates t ON f.template_id = t.id
        WHERE t.account_id = ? OR t.account_id IS NULL OR t.is_standard_template = 1
        ORDER BY f.template_id, f.sort_order ASC
    ");
    $stmt_fields->execute([$account_id]);
    $all_fields_raw = $stmt_fields->fetchAll();

    $template_fields_map = [];
    foreach ($all_fields_raw as $f) {
        $template_fields_map[$f['template_id']][] = $f;
    }
} catch (Exception $e) {
    $templates = [];
    $template_fields_map = [];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Artifact Template Builder & Library - <?php echo htmlspecialchars($company_name); ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <style>
        body { font-family: 'Plus Jakarta Sans', sans-serif; }
    </style>
    <script>
        function toggleMobileNav() {
            var menu = document.getElementById('mobile-nav-menu');
            var openIcon = document.getElementById('mobile-menu-open-icon');
            var closeIcon = document.getElementById('mobile-menu-close-icon');
            if (!menu) return;
            var isHidden = menu.classList.contains('hidden') || menu.style.display === 'none';
            if (isHidden) {
                menu.classList.remove('hidden');
                menu.style.display = 'block';
                if (openIcon) openIcon.classList.add('hidden');
                if (closeIcon) closeIcon.classList.remove('hidden');
            } else {
                menu.classList.add('hidden');
                menu.style.display = 'none';
                if (openIcon) openIcon.classList.remove('hidden');
                if (closeIcon) closeIcon.classList.add('hidden');
            }
        }
    </script>
</head>
<body class="bg-slate-200 min-h-screen text-slate-800">

    <?php require_once("../includes/layout-header.php") ;?>

    <!-- Main Container -->
    <main class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8 space-y-6 flex-1 w-full">

        <!-- Project Context Banner (if navigated from project details) -->
        <?php if ($project_context): ?>
            <div class="p-4 rounded-2xl bg-indigo-50/90 border border-indigo-200/80 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3 shadow-xs">
                <div class="flex items-center gap-3">
                    <div class="w-9 h-9 rounded-xl bg-indigo-600 text-white flex items-center justify-center shrink-0 shadow-xs">
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4"></path></svg>
                    </div>
                    <div>
                        <div class="text-[11px] font-bold uppercase tracking-wider text-indigo-600">Working in Context of Project</div>
                        <div class="text-sm font-bold text-slate-900">
                            <span class="font-mono text-indigo-700 bg-white px-2 py-0.5 rounded-md border border-indigo-200 text-xs mr-1.5"><?php echo htmlspecialchars($project_context['project_code']); ?></span>
                            <?php echo htmlspecialchars($project_context['project_name']); ?>
                        </div>
                    </div>
                </div>
                <a href="project_details.php?id=<?php echo urlencode($project_context['id']); ?>" class="px-3.5 py-2 rounded-xl bg-white hover:bg-slate-50 text-indigo-700 border border-indigo-200 text-xs font-bold transition-all shadow-xs inline-flex items-center gap-1.5">
                    <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18"></path></svg>
                    <span>Return to Project Details</span>
                </a>
            </div>
        <?php endif; ?>

        <!-- Flash Messages -->
        <?php if ($action_success): ?>
            <div class="p-4 rounded-xl bg-emerald-50 border border-emerald-200 text-emerald-800 text-xs flex items-center justify-between shadow-xs">
                <div><?php echo $action_success; ?></div>
                <button onclick="this.parentElement.remove()" class="text-emerald-600 font-bold ml-4">✕</button>
            </div>
        <?php endif; ?>

        <?php if ($action_error): ?>
            <div class="p-4 rounded-xl bg-rose-50 border border-rose-200 text-rose-800 text-xs flex items-center justify-between shadow-xs">
                <div><?php echo $action_error; ?></div>
                <button onclick="this.parentElement.remove()" class="text-rose-600 font-bold ml-4">✕</button>
            </div>
        <?php endif; ?>

        <!-- Top Header & Primary Action -->
        <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
            <div>
                <h1 class="text-2xl sm:text-3xl font-extrabold text-slate-900 tracking-tight">Artifact Template Builder</h1>
                <p class="text-xs text-slate-500 mt-1">Design customized checklists, stage reviews, questionnaires, and subcontractor sign-off forms.</p>
            </div>

            <button onclick="openCreateModal()" class="px-4 py-2.5 rounded-xl bg-indigo-600 hover:bg-indigo-700 text-white font-semibold text-xs transition-all shadow-sm flex items-center gap-2">
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path></svg>
                <span>Create New Template</span>
            </button>
        </div>

        <!-- Filter & Search Bar -->
        <div class="bg-white rounded-2xl border border-slate-200 p-4 shadow-xs flex flex-col md:flex-row items-center justify-between gap-4">
            <div class="flex items-center gap-2 w-full md:w-auto">
                <button onclick="filterTemplates('ALL')" id="tab-btn-ALL" class="filter-tab-btn px-3 py-1.5 rounded-xl bg-indigo-50 text-indigo-700 font-bold text-xs border border-indigo-200">
                    All (<?php echo count($templates); ?>)
                </button>
                <button onclick="filterTemplates('STANDARD')" id="tab-btn-STANDARD" class="filter-tab-btn px-3 py-1.5 rounded-xl bg-slate-100 hover:bg-slate-200 text-slate-700 font-semibold text-xs border border-slate-200">
                    System Standard
                </button>
                <button onclick="filterTemplates('CUSTOM')" id="tab-btn-CUSTOM" class="filter-tab-btn px-3 py-1.5 rounded-xl bg-slate-100 hover:bg-slate-200 text-slate-700 font-semibold text-xs border border-slate-200">
                    Company Custom
                </button>
            </div>

            <div class="w-full md:w-72">
                <input type="text" id="template-search-input" onkeyup="searchTemplates()" placeholder="Search templates, categories, questions..." class="w-full px-3 py-2 border border-slate-200 rounded-xl text-xs focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500 outline-none">
            </div>
        </div>

        <!-- Template Cards Grid -->
        <div id="templates-grid" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            <?php foreach ($templates as $tmpl): 
                $is_std = !empty($tmpl['is_standard']);
                $f_count = $tmpl['field_count'] ?? 0;
                $tmpl_fields = $template_fields_map[$tmpl['id']] ?? [];
            ?>
                <div class="template-card bg-white rounded-2xl border border-slate-200 p-5 shadow-xs hover:border-indigo-300 transition-all flex flex-col justify-between space-y-4" 
                     data-standard="<?php echo $is_std ? '1' : '0'; ?>"
                     data-search="<?php echo htmlspecialchars(strtolower($tmpl['title'] . ' ' . $tmpl['category'] . ' ' . $tmpl['type'] . ' ' . $tmpl['description'])); ?>">
                    
                    <div class="space-y-3">
                        <div class="flex items-center justify-between gap-2">
                            <span class="text-[11px] font-bold px-2.5 py-0.5 rounded-full bg-slate-100 text-slate-700 border border-slate-200">
                                <?php echo htmlspecialchars($tmpl['category']); ?>
                            </span>

                            <span class="text-[10px] font-bold px-2 py-0.5 rounded-md border <?php echo $is_std ? 'bg-indigo-50 text-indigo-700 border-indigo-200' : 'bg-emerald-50 text-emerald-700 border-emerald-200'; ?>">
                                <?php echo $is_std ? 'STANDARD' : 'COMPANY CUSTOM'; ?>
                            </span>
                        </div>

                        <div>
                            <h3 class="text-base font-bold text-slate-900 leading-snug"><?php echo htmlspecialchars($tmpl['title']); ?></h3>
                            <div class="text-[11px] font-semibold text-slate-400 uppercase tracking-wider mt-0.5">
                                <?php echo str_replace('_', ' ', htmlspecialchars($tmpl['type'])); ?>
                            </div>
                        </div>

                        <?php if (!empty($tmpl['description'])): ?>
                            <p class="text-xs text-slate-500 line-clamp-2 leading-relaxed">
                                <?php echo htmlspecialchars($tmpl['description']); ?>
                            </p>
                        <?php endif; ?>

                        <div class="flex items-center gap-2 text-xs font-semibold text-indigo-600 bg-slate-50 px-3 py-2 rounded-xl border border-slate-100">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path></svg>
                            <span><?php echo $f_count; ?> Configured Questions & Fields</span>
                        </div>
                    </div>

                    <!-- Actions Footer -->
                    <div class="pt-3 border-t border-slate-100 flex items-center justify-between gap-2 flex-wrap">
                        <button type="button" onclick="openPreviewModal('<?php echo htmlspecialchars($tmpl['id'], ENT_QUOTES, 'UTF-8'); ?>')" class="px-2.5 py-1.5 rounded-lg border border-slate-200 hover:bg-slate-50 text-slate-600 text-xs font-semibold transition-colors inline-flex items-center gap-1">
                            <svg class="w-3.5 h-3.5 text-slate-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path></svg>
                            <span>Preview (<?php echo $f_count; ?>)</span>
                        </button>

                        <div class="flex items-center gap-1.5">
                            <?php if ($project_context): ?>
                                <form action="artifact-template-builder.php?project_id=<?php echo urlencode($project_id); ?>" method="POST">
                                    <input type="hidden" name="action" value="attach_to_project">
                                    <input type="hidden" name="template_id" value="<?php echo htmlspecialchars($tmpl['id']); ?>">
                                    <button type="submit" class="px-2.5 py-1.5 rounded-lg bg-indigo-600 hover:bg-indigo-700 text-white text-xs font-bold transition-all shadow-2xs inline-flex items-center gap-1">
                                        <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path></svg>
                                        <span>Use in Project</span>
                                    </button>
                                </form>
                            <?php endif; ?>

                            <!-- Clone Template Form -->
                            <form action="artifact-template-builder.php<?php echo !empty($project_id) ? '?project_id=' . urlencode($project_id) : ''; ?>" method="POST" onsubmit="return confirm('Clone this template into your company library?');">
                                <input type="hidden" name="action" value="clone_template">
                                <input type="hidden" name="source_template_id" value="<?php echo htmlspecialchars($tmpl['id']); ?>">
                                <button type="submit" class="px-2.5 py-1.5 rounded-lg bg-slate-100 hover:bg-slate-200 text-slate-700 text-xs font-semibold transition-colors inline-flex items-center gap-1" title="Create Custom Copy">
                                    <svg class="w-3.5 h-3.5 text-indigo-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7v8a2 2 0 002 2h6M8 7V5a2 2 0 012-2h4.586a1 1 0 01.707.293l4.414 4.414a1 1 0 01.293.707V15a2 2 0 01-2 2h-2M8 7H6a2 2 0 00-2 2v10a2 2 0 002 2h8a2 2 0 002-2v-2"></path></svg>
                                    <span>Clone</span>
                                </button>
                            </form>

                            <?php if (!$is_std): ?>
                                <form action="artifact-template-builder.php<?php echo !empty($project_id) ? '?project_id=' . urlencode($project_id) : ''; ?>" method="POST" onsubmit="return confirm('Are you sure you want to delete this custom template?');">
                                    <input type="hidden" name="action" value="delete_template">
                                    <input type="hidden" name="template_id" value="<?php echo htmlspecialchars($tmpl['id']); ?>">
                                    <button type="submit" class="p-1.5 rounded-lg text-rose-500 hover:bg-rose-50 hover:text-rose-700 transition-colors" title="Delete Template">
                                        <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path></svg>
                                    </button>
                                </form>
                            <?php endif; ?>
                        </div>
                    </div>

                </div>
            <?php endforeach; ?>
        </div>

    </main>

    <!-- ==================== CREATE / CUSTOMIZE TEMPLATE MODAL ==================== -->
    <div id="template-builder-modal" class="fixed inset-0 z-50 bg-slate-900/60 backdrop-blur-xs flex items-center justify-center p-4 hidden overflow-y-auto">
        <div class="bg-slate-900 rounded-2xl max-w-3xl w-full p-6 sm:p-8 shadow-2xl border border-slate-200 my-8 space-y-6 max-h-[90vh] overflow-y-auto">
            <div class="flex items-center justify-between border-b border-slate-100 pb-4">
                <div>
                    <h2 class="text-xl font-bold text-slate-50">Custom Template & Field Designer</h2>
                    <p class="text-xs text-slate-300">Define template details, compliance steps, questions, and site photo requirements.</p>
                </div>
                <button onclick="closeCreateModal()" class="text-slate-400 hover:text-slate-300 font-bold text-base p-1">✕</button>
            </div>

            <form action="artifact-template-builder.php<?php echo !empty($project_id) ? '?project_id=' . urlencode($project_id) : ''; ?>" method="POST" class="space-y-6" id="builder-form">
                <input type="hidden" name="action" value="create_template">

                <!-- Template Metadata -->
                <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div class="sm:col-span-2">
                        <label class="block text-xs font-bold text-slate-300 mb-1">Template Title *</label>
                        <input type="text" name="title" id="builder-title-input" required placeholder="e.g. Pre-Pour Concrete & Rebar Inspection" class="w-full px-3.5 py-2.5 border border-slate-200 rounded-xl text-sm focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500 outline-none">
                    </div>

                    <div>
                        <label class="block text-xs font-bold text-slate-300 mb-1">Category *</label>
                        <select name="category" id="builder-category-select" required class="w-full px-3 py-2 border border-slate-200 rounded-xl text-sm focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500 outline-none">
                            <option value="Structural">Structural & Foundation</option>
                            <option value="Framing">Framing & Timber</option>
                            <option value="Waterproofing">Waterproofing & Roofing</option>
                            <option value="Plumbing">Plumbing & Drainage</option>
                            <option value="Electrical">Electrical Rough-In</option>
                            <option value="Finishing">Finishing & Joinery</option>
                            <option value="Handover">Final Handover & Sign-Off</option>
                            <option value="Safety">Site Safety & Compliance</option>
                            <option value="General">General QC Checklist</option>
                        </select>
                    </div>

                    <div>
                        <label class="block text-xs font-bold text-slate-300 mb-1">Artifact Type *</label>
                        <select name="type" id="builder-type-select" required class="w-full px-3 py-2 border border-slate-200 rounded-xl text-sm focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500 outline-none">
                            <option value="QC_CHECKLIST">Quality Control Checklist</option>
                            <option value="QUESTIONNAIRE">Questionnaire / Audit Form</option>
                            <option value="BUILD_STAGE_REVIEW">Build Stage Review</option>
                            <option value="DOCUMENT_UPLOAD">Document & Photo Sign-off</option>
                        </select>
                    </div>

                    <div class="sm:col-span-2">
                        <label class="block text-xs font-bold text-slate-300 mb-1">Description & Instructions for Inspector / Subcontractor</label>
                        <textarea name="description" id="builder-desc-textarea" rows="2" placeholder="Describe the purpose, tolerances, and quality criteria for this inspection..." class="w-full px-3.5 py-2 border border-slate-200 rounded-xl text-sm focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500 outline-none"></textarea>
                    </div>
                </div>

                <!-- Fields & Questions Builder Section -->
                <div class="space-y-3 pt-4 border-t border-slate-100">
                    <div class="flex items-center justify-between flex-wrap gap-2">
                        <div>
                            <h3 class="text-sm font-bold text-slate-300">Configured Inspection Questions & Fields</h3>
                            <p class="text-[11px] text-slate-400">Add pass/fail criteria, text measurements, photo uploads, and signature blocks.</p>
                        </div>

                        <!-- Quick Add Dropdown / Buttons (Full Field Types Palette) -->
                        <div class="flex items-center gap-1.5 flex-wrap">
                            <button type="button" onclick="addField('SINGLE_CHOICE')" class="px-2.5 py-1.5 bg-indigo-50 hover:bg-indigo-100 text-indigo-700 rounded-lg text-xs font-bold border border-indigo-200 transition-colors inline-flex items-center gap-1">
                                + Pass/Fail Choice
                            </button>
                            <button type="button" onclick="addField('MULTI_CHOICE')" class="px-2.5 py-1.5 bg-amber-50 hover:bg-amber-100 text-amber-800 rounded-lg text-xs font-bold border border-amber-200 transition-colors inline-flex items-center gap-1">
                                + Multi-Choice
                            </button>
                            <button type="button" onclick="addField('DROPDOWN')" class="px-2.5 py-1.5 bg-cyan-50 hover:bg-cyan-100 text-cyan-800 rounded-lg text-xs font-bold border border-cyan-200 transition-colors inline-flex items-center gap-1">
                                + Dropdown List
                            </button>
                            <button type="button" onclick="addField('PHOTO_UPLOAD')" class="px-2.5 py-1.5 bg-purple-50 hover:bg-purple-100 text-purple-700 rounded-lg text-xs font-bold border border-purple-200 transition-colors inline-flex items-center gap-1">
                                + Photo Upload
                            </button>
                            <button type="button" onclick="addField('SIGNATURE')" class="px-2.5 py-1.5 bg-rose-50 hover:bg-rose-100 text-rose-700 rounded-lg text-xs font-bold border border-rose-200 transition-colors inline-flex items-center gap-1">
                                + Signature
                            </button>
                            <button type="button" onclick="addField('TEXT')" class="px-2.5 py-1.5 bg-slate-100 hover:bg-slate-200 text-slate-700 rounded-lg text-xs font-semibold border border-slate-200 transition-colors">
                                + Short Text
                            </button>
                            <button type="button" onclick="addField('TEXTAREA')" class="px-2.5 py-1.5 bg-slate-100 hover:bg-slate-200 text-slate-700 rounded-lg text-xs font-semibold border border-slate-200 transition-colors">
                                + Long Textarea
                            </button>
                        </div>
                    </div>

                    <!-- Dynamic Fields Container -->
                    <div id="fields-list-container" class="space-y-3 pt-2">
                        <!-- Populated by JavaScript -->
                    </div>
                </div>

                <?php if ($project_context): ?>
                    <div class="p-3 bg-indigo-50/80 rounded-xl border border-indigo-200 flex items-center gap-2">
                        <input type="checkbox" name="attach_to_project_now" value="1" id="chk-attach-now" checked class="w-4 h-4 text-indigo-600 rounded">
                        <label for="chk-attach-now" class="text-xs font-semibold text-indigo-900 cursor-pointer">
                            Immediately attach this new template to project <strong><?php echo htmlspecialchars($project_context['project_code']); ?></strong> upon saving
                        </label>
                    </div>
                <?php endif; ?>

                <div class="flex items-center justify-end gap-3 pt-4 border-t border-slate-100">
                    <button type="button" onclick="closeCreateModal()" class="px-4 py-2.5 rounded-xl border border-slate-200 text-slate-600 text-xs font-semibold hover:bg-slate-50">
                        Cancel
                    </button>
                    <button type="submit" class="px-6 py-2.5 rounded-xl bg-indigo-600 hover:bg-indigo-700 text-white text-xs font-bold shadow-sm">
                        Save Template
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- ==================== PREVIEW QUESTIONS MODAL (Optimized for 40+ questions, multiple photo uploads, 2+ signatures) ==================== -->
    <div id="preview-modal" class="fixed inset-0 z-50 bg-slate-900/60 backdrop-blur-xs flex items-center justify-center p-4 hidden">
        <div class="bg-white rounded-3xl max-w-3xl w-full shadow-2xl border border-slate-200 flex flex-col max-h-[90vh] overflow-hidden">
            <!-- Modal Header (Sticky) -->
            <div class="p-6 border-b border-slate-100 flex items-start justify-between gap-4 bg-slate-50/60 shrink-0">
                <div class="space-y-1">
                    <div class="flex items-center gap-2">
                        <span id="preview-category-badge" class="text-[10px] font-bold px-2.5 py-0.5 rounded-full bg-slate-100 text-slate-700 border border-slate-200">Category</span>
                        <span id="preview-type-badge" class="text-[10px] font-bold px-2.5 py-0.5 rounded-md bg-indigo-50 text-indigo-700 border border-indigo-200">QC_CHECKLIST</span>
                    </div>
                    <h3 id="preview-title" class="text-xl font-bold text-slate-900 leading-tight">Template Preview</h3>
                    <p id="preview-description" class="text-xs text-slate-600 line-clamp-2 leading-relaxed">Template instructions</p>
                </div>
                <button type="button" onclick="closePreviewModal()" class="p-2 text-slate-400 hover:text-slate-600 hover:bg-slate-100 rounded-xl transition-colors font-bold text-base">✕</button>
            </div>

            <!-- Sub-Header Search & Stats Strip -->
            <div class="px-6 py-3 bg-slate-50/90 border-b border-slate-100 flex items-center justify-between gap-3 shrink-0">
                <span id="preview-field-count" class="text-xs text-slate-600 font-bold flex items-center gap-1.5">
                    <svg class="w-4 h-4 text-indigo-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path></svg>
                    <span>0 Questions Configured</span>
                </span>
                <div class="w-64">
                    <input type="text" id="modal-field-search" onkeyup="filterPreviewQuestions()" placeholder="Search questions in this preview..." class="w-full px-3 py-1.5 bg-white border border-slate-200 rounded-xl text-xs text-slate-700 outline-none focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500/20">
                </div>
            </div>

            <!-- Modal Body (Scrollable container supporting 40+ fields) -->
            <div id="preview-fields-list" class="p-6 space-y-3.5 overflow-y-auto flex-1 max-h-[60vh] bg-slate-50/30">
                <!-- Populated by JavaScript -->
            </div>

            <!-- Modal Footer (Sticky) -->
            <div class="p-4 bg-white border-t border-slate-100 flex items-center justify-between gap-3 shrink-0">
                <button type="button" onclick="closePreviewModal()" class="px-4 py-2.5 rounded-xl border border-slate-200 hover:bg-slate-50 text-slate-700 text-xs font-semibold transition-colors">
                    Close Preview
                </button>
                <button type="button" id="preview-clone-custom-btn" onclick="" class="px-5 py-2.5 rounded-xl bg-indigo-600 hover:bg-indigo-700 text-white text-xs font-bold transition-all shadow-sm flex items-center gap-1.5">
                    <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7v8a2 2 0 002 2h6M8 7V5a2 2 0 012-2h4.586a1 1 0 01.707.293l4.414 4.414a1 1 0 01.293.707V15a2 2 0 01-2 2h-2M8 7H6a2 2 0 00-2 2v10a2 2 0 002 2h8a2 2 0 002-2v-2"></path></svg>
                    <span>Clone into Custom Builder</span>
                </button>
            </div>
        </div>
    </div>

    <!-- JavaScript Field Builder & Preview Engine -->
    <script>
        // Central safely-encoded dataset from PHP
        const allTemplates = <?php echo json_encode($templates, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT); ?>;
        const allTemplateFields = <?php echo json_encode($template_fields_map, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT); ?>;

        function toggleMobileNav() {
            const menu = document.getElementById('mobile-nav-menu');
            const openIcon = document.getElementById('mobile-menu-open-icon');
            const closeIcon = document.getElementById('mobile-menu-close-icon');
            if (menu) {
                menu.classList.toggle('hidden');
                if (openIcon && closeIcon) {
                    openIcon.classList.toggle('hidden');
                    closeIcon.classList.toggle('hidden');
                }
            }
        }

        let fieldCounter = 0;

        function openCreateModal() {
            const container = document.getElementById('fields-list-container');
            if (container.children.length === 0) {
                // Pre-populate with standard starter set
                addField('SINGLE_CHOICE', 'Site Inspection Compliance', 'Pass, Fail, Requires Attention', true, 'Check against engineer specifications');
                addField('PHOTO_UPLOAD', 'Attach Site Photos', '', true, 'Minimum 2 photos of installation');
                addField('SIGNATURE', 'Subcontractor / Inspector Sign-Off', '', true, '');
            }
            document.getElementById('template-builder-modal').classList.remove('hidden');
        }

        function closeCreateModal() {
            document.getElementById('template-builder-modal').classList.add('hidden');
        }

        function addField(type = 'SINGLE_CHOICE', label = '', options = '', isRequired = true, helpText = '') {
            const container = document.getElementById('fields-list-container');
            const idx = fieldCounter++;

            if (type === 'SINGLE_CHOICE' && !options) {
                options = 'Pass, Fail, Requires Attention';
            } else if (type === 'MULTI_CHOICE' && !options) {
                options = 'Option 1, Option 2, Option 3';
            } else if (type === 'DROPDOWN' && !options) {
                options = 'Satisfactory, Minor Defect, Major Defect';
            }

            const isChoice = ['SINGLE_CHOICE', 'MULTI_CHOICE', 'DROPDOWN'].includes(type);

            const fieldDiv = document.createElement('div');
            fieldDiv.id = `field-item-${idx}`;
            fieldDiv.className = 'field-item bg-slate-50 border border-slate-200 rounded-xl p-4 space-y-3 relative transition-all';
            
            fieldDiv.innerHTML = `
                <div class="flex items-center justify-between gap-2">
                    <div class="flex items-center gap-2">
                        <span class="text-[11px] font-bold text-slate-700 uppercase tracking-wider flex items-center gap-1.5 bg-white px-2 py-0.5 rounded border border-slate-200">
                            <svg class="w-3.5 h-3.5 text-indigo-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16"></path></svg>
                            <span class="field-num-badge">Field #${container.children.length + 1}</span>
                        </span>
                        <div class="flex items-center gap-1">
                            <button type="button" onclick="moveFieldUp(this)" title="Move question up in order" class="btn-move-up p-1 rounded-md text-slate-600 hover:text-indigo-600 hover:bg-indigo-50 border border-slate-200 bg-white transition-all text-xs font-semibold flex items-center gap-0.5 shadow-2xs">
                                ▲ <span class="text-[10px] hidden sm:inline">Up</span>
                            </button>
                            <button type="button" onclick="moveFieldDown(this)" title="Move question down in order" class="btn-move-down p-1 rounded-md text-slate-600 hover:text-indigo-600 hover:bg-indigo-50 border border-slate-200 bg-white transition-all text-xs font-semibold flex items-center gap-0.5 shadow-2xs">
                                ▼ <span class="text-[10px] hidden sm:inline">Down</span>
                            </button>
                        </div>
                    </div>
                    <button type="button" onclick="removeField(this)" class="text-rose-500 hover:text-rose-700 text-xs font-semibold flex items-center gap-1">
                        ✕ Remove
                    </button>
                </div>

                <div class="grid grid-cols-1 sm:grid-cols-3 gap-3">
                    <div class="sm:col-span-2">
                        <label class="block text-[11px] font-bold text-slate-700 mb-1">Question / Prompt Label *</label>
                        <input type="text" name="field_label[]" value="${escapeHtml(label)}" required placeholder="e.g. Ground level verification" class="w-full px-3 py-1.5 bg-white border border-slate-200 rounded-lg text-xs outline-none focus:ring-1 focus:ring-indigo-500">
                    </div>

                    <div>
                        <label class="block text-[11px] font-bold text-slate-700 mb-1">Field Type</label>
                        <select name="field_type[]" onchange="handleTypeChange(this, ${idx})" class="w-full px-3 py-1.5 bg-white border border-slate-200 rounded-lg text-xs outline-none focus:ring-1 focus:ring-indigo-500">
                            <option value="SINGLE_CHOICE" ${type === 'SINGLE_CHOICE' ? 'selected' : ''}>Choice (Pass/Fail/etc)</option>
                            <option value="PHOTO_UPLOAD" ${type === 'PHOTO_UPLOAD' ? 'selected' : ''}>Photo Upload</option>
                            <option value="SIGNATURE" ${type === 'SIGNATURE' ? 'selected' : ''}>Digital Signature</option>
                            <option value="CHECKBOX" ${type === 'CHECKBOX' ? 'selected' : ''}>Checkbox / Confirmation</option>
                            <option value="TEXT" ${type === 'TEXT' ? 'selected' : ''}>Single-line Text / Metric</option>
                            <option value="TEXTAREA" ${type === 'TEXTAREA' ? 'selected' : ''}>Multi-line Notes</option>
                            <option value="DROPDOWN" ${type === 'DROPDOWN' ? 'selected' : ''}>Dropdown Select</option>
                            <option value="MULTI_CHOICE" ${type === 'MULTI_CHOICE' ? 'selected' : ''}>Multi-Choice</option>
                        </select>
                    </div>

                    <div id="options-row-${idx}" class="sm:col-span-3 ${isChoice ? '' : 'hidden'}">
                        <label class="block text-[11px] font-bold text-slate-700 mb-1">Choice Options (comma-separated)</label>
                        <input type="text" name="field_options[]" value="${escapeHtml(options)}" placeholder="e.g. Pass, Fail, Requires Attention" class="w-full px-3 py-1.5 bg-white border border-slate-200 rounded-lg text-xs outline-none focus:ring-1 focus:ring-indigo-500">
                    </div>

                    <div class="sm:col-span-2">
                        <label class="block text-[11px] font-bold text-slate-700 mb-1">Help Guidance Text (Optional)</label>
                        <input type="text" name="field_help[]" value="${escapeHtml(helpText)}" placeholder="e.g. Must measure 50mm minimum clearance" class="w-full px-3 py-1.5 bg-white border border-slate-200 rounded-lg text-xs outline-none focus:ring-1 focus:ring-indigo-500">
                    </div>

                    <div class="flex items-center gap-2 pt-4">
                        <input type="checkbox" name="field_required[]" value="1" id="req-${idx}" ${isRequired ? 'checked' : ''} class="w-4 h-4 text-indigo-600 rounded">
                        <label for="req-${idx}" class="text-xs font-medium text-slate-700 cursor-pointer">Required Field</label>
                    </div>
                </div>
            `;

            container.appendChild(fieldDiv);
            renumberFields();
        }

        function moveFieldUp(btn) {
            const item = btn.closest('.field-item');
            if (item && item.previousElementSibling) {
                item.parentNode.insertBefore(item, item.previousElementSibling);
                renumberFields();
            }
        }

        function moveFieldDown(btn) {
            const item = btn.closest('.field-item');
            if (item && item.nextElementSibling) {
                item.parentNode.insertBefore(item.nextElementSibling, item);
                renumberFields();
            }
        }

        function removeField(btn) {
            const item = btn.closest('.field-item');
            if (item) {
                item.remove();
                renumberFields();
            }
        }

        function renumberFields() {
            const container = document.getElementById('fields-list-container');
            if (!container) return;
            const items = container.querySelectorAll('.field-item');
            items.forEach((item, index) => {
                const badge = item.querySelector('.field-num-badge');
                if (badge) {
                    badge.innerText = `Field #${index + 1}`;
                }
                const upBtn = item.querySelector('.btn-move-up');
                const downBtn = item.querySelector('.btn-move-down');
                if (upBtn) {
                    upBtn.disabled = index === 0;
                    upBtn.classList.toggle('opacity-30', index === 0);
                    upBtn.classList.toggle('cursor-not-allowed', index === 0);
                }
                if (downBtn) {
                    downBtn.disabled = index === items.length - 1;
                    downBtn.classList.toggle('opacity-30', index === items.length - 1);
                    downBtn.classList.toggle('cursor-not-allowed', index === items.length - 1);
                }
            });
        }

        function handleTypeChange(selectElement, idx) {
            const isChoice = ['SINGLE_CHOICE', 'MULTI_CHOICE', 'DROPDOWN'].includes(selectElement.value);
            const optionsRow = document.getElementById(`options-row-${idx}`);
            if (optionsRow) {
                if (isChoice) {
                    optionsRow.classList.remove('hidden');
                } else {
                    optionsRow.classList.add('hidden');
                }
            }
        }

        // ==========================================
        // ROBUST PREVIEW MODAL HANDLER
        // ==========================================
        function openPreviewModal(templateId) {
            const tmpl = allTemplates.find(t => String(t.id) === String(templateId));
            if (!tmpl) {
                console.error('Template not found for ID:', templateId);
                return;
            }
            const fields = allTemplateFields[templateId] || [];

            document.getElementById('preview-title').innerText = tmpl.title || 'Untitled Template';
            document.getElementById('preview-category-badge').innerText = tmpl.category || 'General';
            document.getElementById('preview-type-badge').innerText = (tmpl.type || 'QC_CHECKLIST').replace(/_/g, ' ');
            document.getElementById('preview-description').innerText = tmpl.description || 'No additional instructions specified.';

            const countBadge = document.getElementById('preview-field-count');
            if (countBadge) {
                countBadge.innerHTML = `<svg class="w-4 h-4 text-indigo-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path></svg><span>${fields.length} Configured Questions & Fields</span>`;
            }

            const searchInput = document.getElementById('modal-field-search');
            if (searchInput) searchInput.value = '';

            const cloneBtn = document.getElementById('preview-clone-custom-btn');
            if (cloneBtn) {
                cloneBtn.onclick = function() {
                    closePreviewModal();
                    cloneTemplateIntoCustomBuilder(templateId);
                };
            }

            const list = document.getElementById('preview-fields-list');
            list.innerHTML = '';

            if (!fields || fields.length === 0) {
                list.innerHTML = '<div class="text-xs text-slate-400 italic text-center py-8 bg-white rounded-2xl border border-slate-200">No inspection questions configured for this template.</div>';
            } else {
                fields.forEach((f, i) => {
                    const row = document.createElement('div');
                    row.className = 'preview-item p-4 rounded-2xl border border-slate-200 bg-white space-y-2.5 shadow-2xs transition-all';
                    
                    const rawType = (f.field_type || 'SINGLE_CHOICE').toUpperCase().trim();
                    const typeDisplay = rawType.replace(/_/g, ' ');
                    const labelText = f.field_label || f.label || (`Inspection Item #${i + 1}`);

                    // Safely parse options
                    let parsedOptions = [];
                    if (f.options_json) {
                        if (Array.isArray(f.options_json)) {
                            parsedOptions = f.options_json;
                        } else if (typeof f.options_json === 'string') {
                            try {
                                const parsed = JSON.parse(f.options_json);
                                if (Array.isArray(parsed)) parsedOptions = parsed;
                                else if (typeof parsed === 'string') parsedOptions = parsed.split(',').map(s => s.trim()).filter(Boolean);
                            } catch(e) {
                                parsedOptions = f.options_json.split(',').map(s => s.trim()).filter(Boolean);
                            }
                        }
                    } else if (f.options) {
                        if (Array.isArray(f.options)) parsedOptions = f.options;
                        else if (typeof f.options === 'string') parsedOptions = f.options.split(',').map(s => s.trim()).filter(Boolean);
                    }

                    let controlPreviewHtml = '';

                    if (rawType.includes('SIGN') || rawType === 'SIGNATURE' || rawType === 'SIGNATURE_PAD' || rawType === 'DIGITAL_SIGNATURE') {
                        controlPreviewHtml = `
                            <div class="pt-1">
                                <div class="p-3.5 border border-slate-200 bg-slate-50/90 rounded-xl space-y-2">
                                    <div class="flex items-center justify-between text-[11px]">
                                        <span class="font-bold text-slate-700 flex items-center gap-1.5">
                                            <svg class="w-4 h-4 text-rose-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"></path></svg>
                                            Digital Signature Block
                                        </span>
                                        <span class="text-slate-400 font-mono text-[10px]">Touchscreen / Mouse Sign</span>
                                    </div>
                                    <div class="h-10 border-b border-dashed border-slate-300 flex items-end pb-1 text-[11px] text-slate-400 italic">
                                        Sign on site upon verification...
                                    </div>
                                </div>
                            </div>
                        `;
                    } else if (rawType.includes('PHOTO') || rawType.includes('UPLOAD') || rawType.includes('IMAGE') || rawType === 'PHOTO_UPLOAD' || rawType === 'PHOTO_EVIDENCE') {
                        controlPreviewHtml = `
                            <div class="pt-1">
                                <div class="p-3.5 border-2 border-dashed border-purple-200 bg-purple-50/50 hover:bg-purple-50/80 rounded-xl flex items-center justify-center gap-2 text-purple-700 text-xs font-semibold transition-colors">
                                    <svg class="w-4 h-4 text-purple-600 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 9a2 2 0 012-2h.93a2 2 0 001.664-.89l.812-1.22A2 2 0 0110.07 4h3.86a2 2 0 011.664.89l.812 1.22A2 2 0 0018.07 7H19a2 2 0 012 2v9a2 2 0 01-2 2H5a2 2 0 01-2-2V9z"></path><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 13a3 3 0 11-6 0 3 3 0 016 0z"></path></svg>
                                    <span>Photo Evidence Upload (Camera or Image Tap)</span>
                                </div>
                            </div>
                        `;
                    } else if (rawType === 'SINGLE_CHOICE' || rawType === 'RADIO') {
                        const opts = parsedOptions.length > 0 ? parsedOptions : ['Pass', 'Fail', 'N/A'];
                        controlPreviewHtml = '<div class="flex flex-wrap gap-1.5 pt-1">' + 
                            opts.map(o => {
                                const low = String(o).toLowerCase();
                                const isPass = low.includes('pass') || low.includes('yes') || low.includes('satisfactory') || low.includes('good');
                                const isFail = low.includes('fail') || low.includes('no') || low.includes('defect') || low.includes('bad');
                                const cls = isPass ? 'bg-emerald-50 border-emerald-300 text-emerald-800' : (isFail ? 'bg-rose-50 border-rose-300 text-rose-800' : 'bg-slate-50 border-slate-200 text-slate-700');
                                return '<span class="px-2.5 py-1 rounded-lg text-xs font-semibold border ' + cls + '">' + escapeHtml(o) + '</span>';
                            }).join('') + '</div>';
                    } else if (rawType === 'MULTI_CHOICE' || rawType === 'CHECKBOXES') {
                        const opts = parsedOptions.length > 0 ? parsedOptions : ['Option 1', 'Option 2', 'Option 3'];
                        controlPreviewHtml = '<div class="flex flex-wrap gap-1.5 pt-1">' + 
                            opts.map(o => '<span class="px-2.5 py-1 rounded-lg bg-slate-50 border border-slate-200 text-slate-700 text-xs font-medium flex items-center gap-1.5"><span class="w-3.5 h-3.5 rounded border border-slate-300 bg-white inline-block"></span>' + escapeHtml(o) + '</span>').join('') + '</div>';
                    } else if (rawType === 'DROPDOWN' || rawType === 'SELECT') {
                        const optsText = parsedOptions.length > 0 ? parsedOptions.join(', ') : 'Choose an option...';
                        controlPreviewHtml = '<div class="pt-1"><div class="w-full max-w-sm px-3.5 py-2 bg-slate-50 border border-slate-200 rounded-lg text-xs text-slate-600 flex items-center justify-between font-medium"><span>Select (' + escapeHtml(optsText) + ')</span><span class="text-slate-400">▾</span></div></div>';
                    } else if (rawType === 'CHECKBOX' || rawType === 'CONFIRMATION' || rawType === 'BOOLEAN') {
                        controlPreviewHtml = '<div class="pt-1 flex items-center gap-2"><div class="w-4 h-4 rounded border border-slate-300 bg-white flex items-center justify-center"></div><span class="text-xs text-slate-700 font-medium">Check to verify & confirm compliance</span></div>';
                    } else if (rawType === 'TEXTAREA' || rawType === 'NOTES') {
                        controlPreviewHtml = '<div class="pt-1"><div class="w-full h-14 p-2.5 bg-slate-50 border border-slate-200 rounded-lg text-xs text-slate-400 font-medium">Enter detailed notes / observations...</div></div>';
                    } else {
                        // Default Short Text
                        controlPreviewHtml = '<div class="pt-1"><div class="w-full px-3 py-2 bg-slate-50 border border-slate-200 rounded-lg text-xs text-slate-400 font-medium">Enter value / measurement...</div></div>';
                    }

                    row.innerHTML = 
                        '<div class="flex items-center justify-between gap-2 text-xs">' +
                            '<span class="font-bold text-slate-900 leading-snug">' + (i + 1) + '. ' + escapeHtml(labelText) + (f.is_required ? ' <span class="text-rose-500 font-bold">*</span>' : '') + '</span>' +
                            '<span class="text-[10px] font-bold px-2 py-0.5 rounded-md bg-indigo-50 text-indigo-700 border border-indigo-200 shrink-0 uppercase tracking-wider">' + escapeHtml(typeDisplay) + '</span>' +
                        '</div>' +
                        (f.help_text ? '<div class="text-[11px] text-slate-500 leading-relaxed italic">' + escapeHtml(f.help_text) + '</div>' : '') +
                        controlPreviewHtml;
                    list.appendChild(row);
                });
            }

            document.getElementById('preview-modal').classList.remove('hidden');
        }

        function closePreviewModal() {
            document.getElementById('preview-modal').classList.add('hidden');
        }

        function filterPreviewQuestions() {
            const query = (document.getElementById('modal-field-search').value || '').toLowerCase().trim();
            const items = document.querySelectorAll('#preview-fields-list .preview-item');
            items.forEach(item => {
                const match = item.innerText.toLowerCase().includes(query);
                item.style.display = match ? 'block' : 'none';
            });
        }

        function cloneTemplateIntoCustomBuilder(templateId) {
            const tmpl = allTemplates.find(t => String(t.id) === String(templateId));
            if (!tmpl) return;
            const fields = allTemplateFields[templateId] || [];

            // Open creator modal
            document.getElementById('template-builder-modal').classList.remove('hidden');

            // Populate form metadata
            const titleInput = document.getElementById('builder-title-input');
            if (titleInput) titleInput.value = tmpl.title + ' (Copy)';

            const catSelect = document.getElementById('builder-category-select');
            if (catSelect) catSelect.value = tmpl.category || 'General';

            const typeSelect = document.getElementById('builder-type-select');
            if (typeSelect) typeSelect.value = tmpl.type || 'QC_CHECKLIST';

            const descTextarea = document.getElementById('builder-desc-textarea');
            if (descTextarea) descTextarea.value = tmpl.description || '';

            // Clear builder fields
            const container = document.getElementById('fields-list-container');
            container.innerHTML = '';
            fieldCounter = 0;

            // Populate each field
            fields.forEach(f => {
                let options = '';
                if (f.options_json) {
                    try {
                        const parsed = JSON.parse(f.options_json);
                        if (Array.isArray(parsed)) options = parsed.join(', ');
                        else options = String(f.options_json);
                    } catch(e) {
                        options = String(f.options_json);
                    }
                }
                addField(f.field_type || 'SINGLE_CHOICE', f.field_label || '', options, !!f.is_required, f.help_text || '');
            });
        }

        function filterTemplates(type) {
            document.querySelectorAll('.filter-tab-btn').forEach(b => {
                b.className = 'filter-tab-btn px-3 py-1.5 rounded-xl bg-slate-100 hover:bg-slate-200 text-slate-700 font-semibold text-xs border border-slate-200';
            });
            const activeBtn = document.getElementById('tab-btn-' + type);
            if (activeBtn) {
                activeBtn.className = 'filter-tab-btn px-3 py-1.5 rounded-xl bg-indigo-50 text-indigo-700 font-bold text-xs border border-indigo-200';
            }

            document.querySelectorAll('.template-card').forEach(card => {
                const isStd = card.getAttribute('data-standard') === '1';
                if (type === 'ALL') {
                    card.classList.remove('hidden');
                } else if (type === 'STANDARD') {
                    card.classList.toggle('hidden', !isStd);
                } else if (type === 'CUSTOM') {
                    card.classList.toggle('hidden', isStd);
                }
            });
        }

        function searchTemplates() {
            const q = document.getElementById('template-search-input').value.toLowerCase().trim();
            document.querySelectorAll('.template-card').forEach(card => {
                const txt = card.getAttribute('data-search') || '';
                card.classList.toggle('hidden', !txt.includes(q));
            });
        }

        function escapeHtml(str) {
            if (!str) return '';
            return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
        }
    </script>

</body>
</html>