<%- include('../partials/header') %>
<%- include('../partials/sidebar') %>

<!-- CLEAN LIGHT SAAS DESIGN SYSTEM -->
<style>
  :root {
    --adm-bg: #f8fafc;
    --adm-surface: #ffffff;
    --adm-border: #e2e8f0;
    --adm-primary: #4f46e5;
    --adm-primary-hover: #4338ca;
    --adm-primary-lt: #eef2ff;
    --adm-text: #0f172a;
    --adm-text-muted: #64748b;
    --adm-radius: 12px;
    --adm-code-font: ui-monospace, 'SFMono-Regular', Menlo, Consolas, monospace;
  }

  .adm-tools-wrapper {
    flex-grow: 1;
    padding: clamp(12px, 2.5vw, 24px);
    max-width: 1440px;
    width: 100%;
    margin: 0 auto;
    background-color: var(--adm-bg);
  }

  /* ── 1. METRICS GRID ── */
  .adm-metrics-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 10px;
    margin-bottom: 18px;
  }
  @media (min-width: 992px) {
    .adm-metrics-grid { grid-template-columns: repeat(4, 1fr); gap: 16px; }
  }

  .adm-metric-card {
    background: var(--adm-surface);
    border: 1px solid var(--adm-border);
    border-radius: var(--adm-radius);
    padding: 14px 16px;
    display: flex;
    align-items: center;
    gap: 12px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.03);
  }
  .adm-metric-icon {
    width: 38px;
    height: 38px;
    border-radius: 9px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.2rem;
    flex-shrink: 0;
  }
  .adm-metric-val {
    font-size: 1.35rem;
    font-weight: 800;
    color: var(--adm-text);
    line-height: 1.1;
  }
  .adm-metric-lbl {
    font-size: 0.72rem;
    color: var(--adm-text-muted);
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: 0.04em;
  }

  /* ── 2. TOOLBAR ── */
  .adm-toolbar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 10px;
    margin-bottom: 16px;
    flex-wrap: wrap;
  }
  .adm-search-box {
    flex-grow: 1;
    min-width: 220px;
  }

  /* ── 3. TOOL ITEM CARD ── */
  .adm-tool-card {
    background: var(--adm-surface);
    border: 1px solid var(--adm-border);
    border-radius: var(--adm-radius);
    padding: 14px 16px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
    margin-bottom: 10px;
    transition: all 0.15s ease;
  }
  .adm-tool-card:hover {
    border-color: #a5b4fc;
    box-shadow: 0 4px 14px rgba(79, 70, 229, 0.08);
  }

  @media (max-width: 768px) {
    .adm-tool-card {
      flex-direction: column;
      align-items: flex-start;
      gap: 10px;
    }
    .adm-tool-actions {
      width: 100%;
      display: flex;
      justify-content: flex-end;
      border-top: 1px solid var(--adm-border);
      padding-top: 8px;
      gap: 6px;
    }
  }

  .adm-tool-icon-avatar {
    width: 40px;
    height: 40px;
    border-radius: 10px;
    background: var(--adm-primary-lt);
    border: 1px solid #c7d2fe;
    color: var(--adm-primary);
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
  }
  .adm-tool-icon-avatar svg {
    width: 22px;
    height: 22px;
  }

  /* ── 4. GUARANTEED WORKING MODAL TABS ── */
  .adm-modal-pills {
    background: #f8fafc;
    border-bottom: 1px solid var(--adm-border);
    padding: 8px 12px;
    display: flex;
    gap: 6px;
    overflow-x: auto;
    white-space: nowrap;
    scrollbar-width: none;
    -webkit-overflow-scrolling: touch;
    width: 100%;
  }
  .adm-modal-pills::-webkit-scrollbar { display: none; }

  .adm-pill-btn {
    padding: 7px 14px;
    border-radius: 20px;
    font-size: 0.8rem;
    font-weight: 700;
    color: var(--adm-text-muted);
    background: #ffffff;
    border: 1px solid var(--adm-border);
    cursor: pointer;
    flex-shrink: 0;
    transition: all 0.15s ease;
    user-select: none;
  }
  .adm-pill-btn:hover {
    color: var(--adm-primary);
    border-color: #a5b4fc;
  }
  .adm-pill-btn.active {
    background: var(--adm-primary) !important;
    color: #ffffff !important;
    border-color: var(--adm-primary) !important;
    box-shadow: 0 2px 8px rgba(79, 70, 229, 0.25);
  }

  /* Direct Display Control for Tab Panes */
  .tab-pane-content {
    display: none;
  }
  .tab-pane-content.active {
    display: block !important;
  }

  /* ── 5. RESPONSIVE SVG ICON PICKER ── */
  .adm-svg-box-picker {
    background: #f8fafc;
    border: 1px solid var(--adm-border);
    border-radius: 12px;
    padding: 12px;
  }
  
  .svg-picker-flex-wrap {
    display: flex;
    gap: 12px;
    align-items: center;
  }
  @media (max-width: 580px) {
    .svg-picker-flex-wrap {
      flex-direction: column;
      align-items: flex-start;
    }
  }

  .adm-live-preview-box {
    width: 52px;
    height: 52px;
    border-radius: 12px;
    background: linear-gradient(135deg, #4f46e5 0%, #06b6d4 100%);
    color: #ffffff;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 4px 12px rgba(79, 70, 229, 0.3);
    flex-shrink: 0;
  }
  .adm-live-preview-box svg { width: 28px; height: 28px; }

  .adm-svg-grid {
    display: grid;
    grid-template-columns: repeat(6, 1fr);
    gap: 6px;
    max-height: 180px;
    overflow-y: auto;
    width: 100%;
    padding: 2px;
  }
  @media (min-width: 768px) {
    .adm-svg-grid { grid-template-columns: repeat(9, 1fr); }
  }

  .adm-svg-btn {
    width: 100%;
    aspect-ratio: 1;
    background: #ffffff;
    border: 1.5px solid var(--adm-border);
    border-radius: 8px;
    color: var(--adm-text-muted);
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    padding: 4px;
    transition: all 0.15s ease;
  }
  .adm-svg-btn svg { width: 20px; height: 20px; }
  .adm-svg-btn:hover {
    border-color: var(--adm-primary);
    color: var(--adm-primary);
    background: var(--adm-primary-lt);
  }
  .adm-svg-btn.selected {
    background: var(--adm-primary) !important;
    border-color: var(--adm-primary) !important;
    color: #ffffff !important;
    box-shadow: 0 2px 8px rgba(79, 70, 229, 0.35);
  }

  /* IDE Code Editors */
  .adm-code-textarea {
    background: #090d16 !important;
    color: #38bdf8 !important;
    font-family: var(--adm-code-font) !important;
    font-size: 0.84rem !important;
    line-height: 1.6 !important;
    border-radius: 8px !important;
  }
  .adm-code-textarea.css-tint { color: #86efac !important; }
  .adm-code-textarea.js-tint { color: #fde047 !important; }
</style>

<div class="adm-tools-wrapper">
    
    <!-- Top Header -->
    <div class="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2">
        <div>
            <h1 class="fw-bold text-dark mb-0 fs-2 d-flex align-items-center gap-2">
                <i class="ti ti-tools text-primary"></i> Tools Management
            </h1>
            <div class="text-muted small">Manage client-side engines, SVG icons, SEO meta tags, and categories</div>
        </div>
        <button class="btn btn-primary fw-bold shadow-sm rounded-3 px-3 py-2" onclick="openAddToolModal()">
            <i class="ti ti-plus me-1"></i> Add New Tool
        </button>
    </div>

    <!-- 4 Metrics Cards -->
    <div class="adm-metrics-grid">
        <div class="adm-metric-card">
            <div class="adm-metric-icon bg-primary-lt text-primary"><i class="ti ti-box"></i></div>
            <div>
                <div class="adm-metric-val" id="statTotalTools">0</div>
                <div class="adm-metric-lbl">Total Registered</div>
            </div>
        </div>
        <div class="adm-metric-card">
            <div class="adm-metric-icon bg-success-lt text-success"><i class="ti ti-circle-check"></i></div>
            <div>
                <div class="adm-metric-val" id="statActiveTools">0</div>
                <div class="adm-metric-lbl">Active Live</div>
            </div>
        </div>
        <div class="adm-metric-card">
            <div class="adm-metric-icon bg-warning-lt text-warning"><i class="ti ti-flame"></i></div>
            <div>
                <div class="adm-metric-val" id="statTotalHits">0</div>
                <div class="adm-metric-lbl">Total Hits</div>
            </div>
        </div>
        <div class="adm-metric-card">
            <div class="adm-metric-icon bg-info-lt text-info"><i class="ti ti-category"></i></div>
            <div>
                <div class="adm-metric-val">5</div>
                <div class="adm-metric-lbl">Categories</div>
            </div>
        </div>
    </div>

    <!-- Tools List Card -->
    <div class="card border-0 shadow-sm rounded-4 p-3 p-md-4 bg-white">
        
        <!-- Search & Category Filters -->
        <div class="adm-toolbar">
            <div class="adm-search-box">
                <input type="search" id="toolFilterInput" class="form-control rounded-3 py-2" placeholder="Search tool by name or slug..." oninput="filterToolsList()">
            </div>
            <div>
                <select id="toolCatFilter" class="form-select rounded-3 py-2" onchange="filterToolsList()">
                    <option value="all">All Categories</option>
                    <option value="Developer">💻 Developer</option>
                    <option value="Text">📝 Text</option>
                    <option value="Security">🔒 Security</option>
                    <option value="Image">🖼️ Image</option>
                    <option value="Utility">⚙️ Utility</option>
                </select>
            </div>
        </div>

        <!-- Tool Cards List Container -->
        <div class="d-flex flex-column" id="toolsListContainer">
            <div class="text-center py-5 text-muted">
                <div class="spinner-border spinner-border-sm text-primary me-2"></div> Loading registered tools...
            </div>
        </div>

    </div>

</div>

<!-- =================================================== -->
<!-- 6-TAB MASTER STUDIO MODAL                           -->
<!-- =================================================== -->
<div class="modal fade" id="toolModal" tabindex="-1" data-bs-backdrop="static">
    <div class="modal-dialog modal-xl modal-dialog-centered" style="max-width: 1040px;">
        <div class="modal-content border-0 shadow-lg rounded-4 overflow-hidden" style="max-height: 94vh; display: flex; flex-direction: column; background: #ffffff;">
            
            <!-- Modal Header -->
            <div class="modal-header border-bottom py-2 py-md-3 px-3 px-md-4 bg-white sticky-top">
                <h5 class="modal-title fw-bold text-dark d-flex align-items-center gap-2 text-truncate" id="modalTitle">
                    <i class="ti ti-adjustments text-primary"></i> Configure Tool
                </h5>
                <button type="button" class="btn-close shadow-none" data-bs-dismiss="modal"></button>
            </div>
            
            <form id="toolForm" class="d-flex flex-column flex-grow-1 overflow-hidden">
                <input type="hidden" id="toolId">
                <input type="hidden" id="tIconSvg">
                
                <!-- 6 Guaranteed Working Tabs -->
                <div class="adm-modal-pills">
                    <button type="button" class="adm-pill-btn active" onclick="switchModalTab('tab1Basic', this)">
                        <i class="ti ti-icons me-1"></i> 1. Display & SVG
                    </button>
                    <button type="button" class="adm-pill-btn" onclick="switchModalTab('tab2Seo', this)">
                        <i class="ti ti-search text-warning me-1"></i> 2. SEO & SERP
                    </button>
                    <button type="button" class="adm-pill-btn" onclick="switchModalTab('tab3Html', this)">
                        <i class="ti ti-file-code text-primary me-1"></i> 3. HTML Engine
                    </button>
                    <button type="button" class="adm-pill-btn" onclick="switchModalTab('tab4Css', this)">
                        <i class="ti ti-palette text-success me-1"></i> 4. CSS
                    </button>
                    <button type="button" class="adm-pill-btn" onclick="switchModalTab('tab5Js', this)">
                        <i class="ti ti-brand-javascript text-warning me-1"></i> 5. JavaScript
                    </button>
                    <button type="button" class="adm-pill-btn" onclick="switchModalTab('tab6Faq', this)">
                        <i class="ti ti-help text-danger me-1"></i> 6. How-To & FAQs
                    </button>
                </div>

                <!-- Modal Body Scrollable -->
                <div class="modal-body p-3 p-md-4 overflow-y-auto" style="max-height: 64vh;">
                    
                    <!-- TAB 1: DISPLAY & SVG PICKER -->
                    <div class="tab-pane-content active" id="tab1Basic">
                        
                        <!-- Responsive SVG Picker -->
                        <div class="adm-svg-box-picker mb-3">
                            <div class="d-flex align-items-center justify-content-between mb-2">
                                <label class="form-label fw-bold small text-dark mb-0">
                                    <i class="ti ti-icons text-primary me-1"></i> Choose Tool SVG Icon
                                </label>
                                <span class="badge bg-primary-lt text-primary">Live Selected</span>
                            </div>
                            
                            <div class="svg-picker-flex-wrap">
                                <div class="adm-live-preview-box" id="iconPreviewBox" title="Selected SVG Icon Preview">
                                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/></svg>
                                </div>
                                
                                <div class="adm-svg-grid" id="svgPresetGrid">
                                    <!-- 36+ SVGs injected by JS -->
                                </div>
                            </div>

                            <div class="mt-2">
                                <a class="small text-decoration-none text-primary fw-bold" data-bs-toggle="collapse" href="#customSvgCollapse">
                                    + Or paste custom raw &lt;svg&gt; code
                                </a>
                                <div class="collapse mt-1" id="customSvgCollapse">
                                    <textarea id="customSvgInput" class="form-control font-monospace form-control-sm bg-white" rows="2" placeholder="<svg viewBox='0 0 24 24' ...>...</svg>" oninput="applyCustomSvg(this.value)"></textarea>
                                </div>
                            </div>
                        </div>

                        <div class="row g-2 g-md-3">
                            <div class="col-md-6">
                                <label class="form-label fw-bold small">Tool Name *</label>
                                <input type="text" id="tName" class="form-control rounded-3" placeholder="e.g. Word Counter" required oninput="autoGenerateSlug(this.value)">
                            </div>
                            <div class="col-md-3">
                                <label class="form-label fw-bold small">Category *</label>
                                <select id="tCategory" class="form-select rounded-3">
                                    <option value="Developer">💻 Developer</option>
                                    <option value="Text">📝 Text Tool</option>
                                    <option value="Security">🔒 Security</option>
                                    <option value="Image">🖼️ Image Tool</option>
                                    <option value="Utility">⚙️ Utility</option>
                                </select>
                            </div>
                            <div class="col-md-3">
                                <label class="form-label fw-bold small">URL Slug *</label>
                                <input type="text" id="tSlug" class="form-control rounded-3" placeholder="word-counter" required>
                            </div>

                            <div class="col-md-6">
                                <label class="form-label fw-bold small">Card Badge Tag</label>
                                <select id="tBadge" class="form-select rounded-3">
                                    <option value="Instant">⚡ Instant</option>
                                    <option value="Popular">⭐ Popular</option>
                                    <option value="Fast">🔥 Fast</option>
                                    <option value="New">✨ New</option>
                                    <option value="Free">🎁 Free</option>
                                    <option value="Pro">💎 Pro</option>
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label fw-bold small">Initial Hits Count</label>
                                <input type="number" id="tUsageCount" class="form-control rounded-3" value="0">
                            </div>
                        </div>
                    </div>

                    <!-- TAB 2: SEO & GOOGLE SERP -->
                    <div class="tab-pane-content" id="tab2Seo">
                        <div class="p-3 bg-light border rounded-3 mb-3">
                            <span class="badge bg-primary-lt text-primary mb-2"><i class="ti ti-brand-google me-1"></i>Google Search Result Preview</span>
                            <div class="bg-white p-2 p-md-3 rounded-3 border">
                                <div class="text-muted small text-truncate" id="serpUrlPreview">https://tools.heyswan.cloud/tool/word-counter</div>
                                <div class="fs-3 fw-bold text-primary text-truncate" id="serpTitlePreview">Tool Title Preview</div>
                                <div class="text-muted small line-clamp-2 mt-1" id="serpDescPreview">Tool Meta Description will appear here...</div>
                            </div>
                        </div>

                        <div class="row g-2 g-md-3">
                            <div class="col-12">
                                <label class="form-label fw-bold small text-primary">🎯 Primary Focus Keyword</label>
                                <input type="text" id="tKeyword" class="form-control rounded-3 border-primary" placeholder="e.g. online word counter" required>
                            </div>
                            <div class="col-12">
                                <div class="d-flex justify-content-between align-items-center mb-1">
                                    <label class="form-label fw-bold small mb-0">Google Meta Title</label>
                                    <small class="text-muted" id="titleCount">0 / 60</small>
                                </div>
                                <input type="text" id="tMetaTitle" class="form-control rounded-3" placeholder="Word Counter - Free Online Character & Word Density Tool" required maxlength="70">
                            </div>
                            <div class="col-12">
                                <div class="d-flex justify-content-between align-items-center mb-1">
                                    <label class="form-label fw-bold small mb-0">Google Meta Description</label>
                                    <small class="text-muted" id="descCount">0 / 160</small>
                                </div>
                                <textarea id="tMetaDesc" class="form-control rounded-3" rows="2" placeholder="Count words, characters, sentences, and paragraphs in real time with reading duration." required maxlength="180"></textarea>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label fw-bold small">Canonical URL Override</label>
                                <input type="text" id="tCanonical" class="form-control rounded-3" placeholder="https://tools.heyswan.cloud/tool/...">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label fw-bold small">OG Banner Image URL</label>
                                <input type="text" id="tOgImage" class="form-control rounded-3" placeholder="https://tools.heyswan.cloud/banner.png">
                            </div>
                            <div class="col-12">
                                <div class="form-check form-switch mt-1">
                                    <input class="form-check-input" type="checkbox" id="tIndexable" checked>
                                    <label class="form-check-label fw-bold text-dark" for="tIndexable">Allow Google Search Indexing</label>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- TAB 3: HTML ENGINE -->
                    <div class="tab-pane-content" id="tab3Html">
                        <div class="d-flex justify-content-between align-items-center mb-2 flex-wrap gap-1">
                            <label class="form-label fw-bold small text-dark mb-0"><i class="ti ti-file-code text-primary me-1"></i>Workspace HTML Markup</label>
                            <input type="file" id="fileUploadHtml" accept=".html,.txt" class="d-none" onchange="readFileInto(this, 'codeHtml')">
                            <button type="button" class="btn btn-sm btn-outline-primary rounded-pill px-3" onclick="document.getElementById('fileUploadHtml').click()">
                                <i class="ti ti-upload me-1"></i> Upload .html
                            </button>
                        </div>
                        <textarea id="codeHtml" class="form-control adm-code-textarea" rows="12" placeholder="<div class='custom-tool'>...</div>"></textarea>
                    </div>

                    <!-- TAB 4: CUSTOM CSS -->
                    <div class="tab-pane-content" id="tab4Css">
                        <div class="d-flex justify-content-between align-items-center mb-2 flex-wrap gap-1">
                            <label class="form-label fw-bold small text-dark mb-0"><i class="ti ti-palette text-success me-1"></i>Scoped CSS Styling</label>
                            <input type="file" id="fileUploadCss" accept=".css,.txt" class="d-none" onchange="readFileInto(this, 'codeCss')">
                            <button type="button" class="btn btn-sm btn-outline-success rounded-pill px-3" onclick="document.getElementById('fileUploadCss').click()">
                                <i class="ti ti-upload me-1"></i> Upload .css
                            </button>
                        </div>
                        <textarea id="codeCss" class="form-control adm-code-textarea css-tint" rows="12" placeholder=".custom-tool { ... }"></textarea>
                    </div>

                    <!-- TAB 5: JAVASCRIPT ENGINE -->
                    <div class="tab-pane-content" id="tab5Js">
                        <div class="d-flex justify-content-between align-items-center mb-2 flex-wrap gap-1">
                            <label class="form-label fw-bold small text-dark mb-0"><i class="ti ti-brand-javascript text-warning me-1"></i>Client-Side JS Engine</label>
                            <input type="file" id="fileUploadJs" accept=".js,.txt" class="d-none" onchange="readFileInto(this, 'codeJs')">
                            <button type="button" class="btn btn-sm btn-outline-warning rounded-pill px-3" onclick="document.getElementById('fileUploadJs').click()">
                                <i class="ti ti-upload me-1"></i> Upload .js
                            </button>
                        </div>
                        <textarea id="codeJs" class="form-control adm-code-textarea js-tint mb-2" rows="11" placeholder="(function() { 'use strict'; })();"></textarea>
                        <label class="form-label fw-bold small text-dark">External CDN Libraries (Optional)</label>
                        <input type="text" id="tCdnScripts" class="form-control rounded-3 font-monospace" placeholder="https://cdnjs.cloudflare.com/.../script.js">
                    </div>

                    <!-- TAB 6: HOW-TO & FAQS -->
                    <div class="tab-pane-content" id="tab6Faq">
                        <div class="mb-3">
                            <label class="form-label fw-bold small">About This Tool (SEO Description)</label>
                            <textarea id="tAbout" class="form-control rounded-3" rows="3" placeholder="Explain what this tool does and why users should choose it..."></textarea>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label fw-bold small">How to Use (1 step per line — auto generates 1, 2, 3 cards)</label>
                            <textarea id="tHowTo" class="form-control rounded-3" rows="3" placeholder="Paste your input data in the editor.&#10;Click Process to get instant output.&#10;Copy or download the result."></textarea>
                        </div>

                        <div class="d-flex justify-content-between align-items-center mb-2 border-top pt-2">
                            <h6 class="fw-bold text-dark mb-0">Google FAQs (Schema.org FAQPage)</h6>
                            <button type="button" class="btn btn-sm btn-outline-primary rounded-pill px-3" onclick="addFaqRow()">
                                <i class="ti ti-plus me-1"></i> Add FAQ
                            </button>
                        </div>
                        <div id="faqContainer" class="d-flex flex-column gap-2"></div>
                    </div>

                </div>

                <!-- Modal Footer -->
                <div class="modal-footer border-top py-2 px-3 bg-white sticky-bottom d-flex justify-content-between align-items-center">
                    <a id="liveTestBtn" href="#" target="_blank" class="btn btn-sm btn-outline-secondary rounded-3 d-none">
                        <i class="ti ti-external-link me-1"></i> Test Live
                    </a>
                    <div class="ms-auto d-flex align-items-center gap-2">
                        <button type="button" class="btn btn-sm btn-light rounded-3 px-3" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-sm btn-primary fw-bold rounded-3 px-4 shadow-sm">
                            <i class="ti ti-device-floppy me-1"></i> Save Tool
                        </button>
                    </div>
                </div>

            </form>

        </div>
    </div>
</div>

<script>
    let tools = [];

    // ── DIRECT FOOLPROOF TAB SWITCHER (NO BOOTSTRAP TAB BUG) ──
    function switchModalTab(targetTabId, btn) {
        document.querySelectorAll('.adm-modal-pills .adm-pill-btn').forEach(b => b.classList.remove('active'));
        if (btn) btn.classList.add('active');

        document.querySelectorAll('#toolModal .tab-pane-content').forEach(pane => {
            pane.classList.remove('active');
        });

        const target = document.getElementById(targetTabId);
        if (target) {
            target.classList.add('active');
        }
    }

    // ── 36+ EXTENSIVE BUILT-IN SVG ICONS COLLECTION ──
    const SVG_PRESETS = [
        { name: 'Code', svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/></svg>` },
        { name: 'CSS Palette', svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><circle cx="13.5" cy="6.5" r=".5"/><circle cx="17.5" cy="10.5" r=".5"/><circle cx="8.5" cy="7.5" r=".5"/><circle cx="6.5" cy="12.5" r=".5"/><path d="M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10c.926 0 1.648-.746 1.648-1.688 0-.437-.18-.835-.437-1.125-.29-.289-.438-.652-.438-1.125a1.64 1.64 0 0 1 1.668-1.668h1.996c3.051 0 5.555-2.503 5.555-5.554C21.965 6.012 17.461 2 12 2z"/></svg>` },
        { name: 'JavaScript', svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><path d="M20 4H4v16h16V4z"/><path d="M7 16V8l5 8V8"/><path d="M17 12h-4"/></svg>` },
        { name: 'Braces/JSON', svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><path d="M8 3H7a2 2 0 0 0-2 2v5a2 2 0 0 1-2 2 2 2 0 0 1 2 2v5a2 2 0 0 0 2 2h1"/><path d="M16 21h1a2 2 0 0 0 2-2v-5a2 2 0 0 1 2-2 2 2 0 0 1-2-2V5a2 2 0 0 0-2-2h-1"/></svg>` },
        { name: 'Terminal', svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><polyline points="4 17 10 11 4 5"/><line x1="12" y1="19" x2="20" y2="19"/></svg>` },
        { name: 'Scissors/Purge', svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><circle cx="6" cy="6" r="3"/><circle cx="6" cy="18" r="3"/><line x1="20" y1="4" x2="8.12" y2="15.88"/><line x1="14.47" y1="14.48" x2="20" y2="20"/><line x1="8.12" y1="8.12" x2="12" y2="12"/></svg>` },
        { name: 'Database', svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><ellipse cx="12" cy="5" rx="9" ry="3"/><path d="M21 12c0 1.66-4 3-9 3s-9-1.34-9-3"/><path d="M3 5v14c0 1.66 4 3 9 3s9-1.34 9-3V5"/></svg>` },
        { name: 'Binary/Code', svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><path d="M10 10H6V4h4v6z"/><path d="M18 20h-4v-6h4v6z"/><path d="M14 4h4v6h-4z"/><path d="M6 14h4v6H6z"/></svg>` },
        { name: 'Regex', svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><line x1="12" y1="2" x2="12" y2="22"/><line x1="4.93" y1="4.93" x2="19.07" y2="19.07"/><line x1="2" y1="12" x2="22" y2="12"/><line x1="4.93" y1="19.07" x2="19.07" y2="4.93"/></svg>` },
        { name: 'Text/File', svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/></svg>` },
        { name: 'Edit/Pen', svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>` },
        { name: 'Hash/Counter', svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><line x1="4" y1="9" x2="20" y2="9"/><line x1="4" y1="15" x2="20" y2="15"/><line x1="10" y1="3" x2="8" y2="21"/><line x1="16" y1="3" x2="14" y2="21"/></svg>` },
        { name: 'Copy/Paste', svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>` },
        { name: 'Book/Docs', svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/><path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"/></svg>` },
        { name: 'Lock', svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>` },
        { name: 'Shield', svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>` },
        { name: 'Key', svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><path d="M21 2l-2 2m-1.5 1.5L10 13l-4 4-2-2-2 2 4 4 2-2 2 2 4-4 7.5-7.5"/></svg>` },
        { name: 'Eye/View', svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>` },
        { name: 'Image', svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>` },
        { name: 'Crop/Resize', svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><path d="M6 2v14a2 2 0 0 0 2 2h14"/><path d="M18 22V8a2 2 0 0 0-2-2H2"/></svg>` },
        { name: 'Vector/SVG', svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/></svg>` },
        { name: 'Video', svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><polygon points="23 7 16 12 23 17 23 7"/><rect x="1" y="5" width="15" height="14" rx="2" ry="2"/></svg>` },
        { name: 'Wrench', svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/></svg>` },
        { name: 'Zap/Fast', svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>` },
        { name: 'Flame', svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><path d="M8.5 14.5A2.5 2.5 0 0 0 11 12c0-1.38-.5-2-1-3-1.072-2.143-.224-4.054 2-6 .5 2.5 2 4.9 4 6.5 2 1.6 3 3.5 3 5.5a7 7 0 1 1-14 0c0-1.153.433-2.294 1-3a2.5 2.5 0 0 0 2.5 2.5z"/></svg>` },
        { name: 'Sparkles', svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><path d="m12 3-1.912 5.813a2 2 0 0 1-1.275 1.275L3 12l5.813 1.912a2 2 0 0 1 1.275 1.275L12 21l1.912-5.813a2 2 0 0 1 1.275-1.275L21 12l-5.813-1.912a2 2 0 0 1-1.275-1.275L12 3Z"/></svg>` },
        { name: 'Sync/Converter', svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><polyline points="23 4 23 10 17 10"/><polyline points="1 20 1 14 7 14"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></svg>` },
        { name: 'Calculator', svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><rect x="4" y="2" width="16" height="20" rx="2"/><line x1="8" y1="6" x2="16" y2="6"/><line x1="16" y1="14" x2="16" y2="18"/><path d="M8 10h.01"/><path d="M12 10h.01"/><path d="M16 10h.01"/><path d="M8 14h.01"/><path d="M12 14h.01"/><path d="M8 18h.01"/><path d="M12 18h.01"/></svg>` },
        { name: 'Globe/Web', svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>` },
        { name: 'Link', svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg>` },
        { name: 'Cloud', svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><path d="M18 10h-1.26A8 8 0 1 0 9 20h9a5 5 0 0 0 0-10z"/></svg>` },
        { name: 'Zip/Archive', svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><polyline points="21 8 21 21 3 21 3 8"/><rect x="1" y="3" width="22" height="5"/><line x1="10" y1="12" x2="14" y2="12"/></svg>` },
        { name: 'Clock/Time', svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>` },
        { name: 'Check/Validate', svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>` },
        { name: 'Layers', svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><polygon points="12 2 2 7 12 12 22 7 12 2"/><polyline points="2 17 12 22 22 17"/><polyline points="2 12 12 17 22 12"/></svg>` }
    ];

    function renderSvgPicker() {
        const grid = document.getElementById('svgPresetGrid');
        grid.innerHTML = SVG_PRESETS.map((p, idx) => `
            <button type="button" class="adm-svg-btn ${idx === 0 ? 'selected' : ''}" title="${p.name}" onclick="selectSvgPreset(${idx})">
                ${p.svg}
            </button>
        `).join('');
    }

    function selectSvgPreset(index) {
        document.querySelectorAll('.adm-svg-btn').forEach((b, i) => {
            b.classList.toggle('selected', i === index);
        });
        const selected = SVG_PRESETS[index];
        document.getElementById('tIconSvg').value = selected.svg;
        document.getElementById('iconPreviewBox').innerHTML = selected.svg;
        document.getElementById('customSvgInput').value = '';
    }

    function applyCustomSvg(code) {
        if (code.trim().startsWith('<svg')) {
            document.getElementById('tIconSvg').value = code.trim();
            document.getElementById('iconPreviewBox').innerHTML = code.trim();
            document.querySelectorAll('.adm-svg-btn').forEach(b => b.classList.remove('selected'));
        }
    }

    // ── FETCH & RENDER TOOLS ──
    async function loadTools() {
        try {
            const res = await fetch('/api/admin/tools');
            tools = await res.json();
            
            const activeCount = tools.filter(t => t.active).length;
            const totalUsage = tools.reduce((sum, t) => sum + (t.usageCount || 0), 0);

            document.getElementById('statTotalTools').innerText = tools.length;
            document.getElementById('statActiveTools').innerText = activeCount;
            document.getElementById('statTotalHits').innerText = totalUsage.toLocaleString();

            renderToolsList(tools);
        } catch (e) {
            document.getElementById('toolsListContainer').innerHTML = '<div class="text-danger p-4 text-center">Failed to load tools.</div>';
        }
    }

    function renderToolsList(toolList) {
        const container = document.getElementById('toolsListContainer');
        if (!toolList || toolList.length === 0) {
            container.innerHTML = '<div class="text-center py-5 text-muted"><i class="ti ti-package-off fs-1 d-block mb-2"></i>No tools found. Click "+ Add New Tool".</div>';
            return;
        }

        container.innerHTML = toolList.map(t => {
            const iconHtml = (t.iconSvg && t.iconSvg.trim().startsWith('<svg')) ? t.iconSvg : SVG_PRESETS[0].svg;
            return `
            <div class="adm-tool-card">
                <div class="d-flex align-items-center gap-3">
                    <div class="adm-tool-icon-avatar">
                        ${iconHtml}
                    </div>
                    <div>
                        <div class="d-flex align-items-center gap-2 flex-wrap">
                            <h4 class="fw-bold text-dark mb-0 fs-3">${t.name}</h4>
                            <span class="badge bg-light text-dark border rounded-pill">${t.category}</span>
                            <span class="badge bg-primary-lt text-primary rounded-pill">${t.badge || 'Instant'}</span>
                            <span class="badge ${t.active ? 'bg-success-lt text-success' : 'bg-danger-lt text-danger'} rounded-pill fw-bold">
                                ${t.active ? '● Active' : '○ Disabled'}
                            </span>
                        </div>
                        <div class="text-muted small mt-1">
                            🎯 Focus: <strong class="text-primary">${t.seo?.targetKeyword || t.name}</strong> &bull; 
                            🔗 <a href="/tool/${t.slug}" target="_blank" class="text-secondary text-decoration-none">/tool/${t.slug} <i class="ti ti-external-link small"></i></a> &bull; 
                            🔥 Hits: <strong>${(t.usageCount || 0).toLocaleString()}</strong>
                        </div>
                    </div>
                </div>

                <div class="adm-tool-actions">
                    <button class="btn btn-sm btn-primary fw-bold rounded-pill px-3" onclick="editTool('${t.id}')">
                        <i class="ti ti-edit me-1"></i> Edit & Engine
                    </button>
                    <button class="btn btn-sm ${t.active ? 'btn-outline-warning' : 'btn-outline-success'} rounded-pill" onclick="toggleTool('${t.id}')">
                        ${t.active ? 'Disable' : 'Enable'}
                    </button>
                    <button class="btn btn-sm btn-outline-danger rounded-circle p-2" onclick="deleteTool('${t.id}')" title="Delete Tool">
                        <i class="ti ti-trash"></i>
                    </button>
                </div>
            </div>
            `;
        }).join('');
    }

    function filterToolsList() {
        const q = document.getElementById('toolFilterInput').value.toLowerCase().trim();
        const cat = document.getElementById('toolCatFilter').value;

        const filtered = tools.filter(t => {
            const matchQ = (t.name || '').toLowerCase().includes(q) || (t.slug || '').toLowerCase().includes(q) || (t.seo?.targetKeyword || '').toLowerCase().includes(q);
            const matchCat = cat === 'all' || (t.category || '').toLowerCase() === cat.toLowerCase();
            return matchQ && matchCat;
        });

        renderToolsList(filtered);
    }

    function openAddToolModal() {
        document.getElementById('toolForm').reset();
        document.getElementById('toolId').value = '';
        document.getElementById('codeHtml').value = '';
        document.getElementById('codeCss').value = '';
        document.getElementById('codeJs').value = '';
        document.getElementById('tCdnScripts').value = '';
        document.getElementById('faqContainer').innerHTML = '';
        document.getElementById('liveTestBtn').classList.add('d-none');
        document.getElementById('modalTitle').innerHTML = '<i class="ti ti-plus text-primary"></i> Add New Tool';
        
        selectSvgPreset(0);

        // Always reset to Tab 1
        switchModalTab('tab1Basic', document.querySelector('.adm-modal-pills .adm-pill-btn'));

        updateSerpPreview();
        addFaqRow('Is this tool free to use?', 'Yes, it is 100% free with unlimited access and zero data storage.');
        new bootstrap.Modal(document.getElementById('toolModal')).show();
    }

    function editTool(id) {
        const t = tools.find(x => x.id === id);
        if (!t) return;

        document.getElementById('toolId').value = t.id;
        document.getElementById('tName').value = t.name || '';
        document.getElementById('tCategory').value = t.category || 'Developer';
        document.getElementById('tSlug').value = t.slug || '';
        document.getElementById('tBadge').value = t.badge || 'Popular';
        document.getElementById('tUsageCount').value = t.usageCount || 0;

        // Load SVG Icon
        const currentSvg = (t.iconSvg && t.iconSvg.trim().startsWith('<svg')) ? t.iconSvg : SVG_PRESETS[0].svg;
        document.getElementById('tIconSvg').value = currentSvg;
        document.getElementById('iconPreviewBox').innerHTML = currentSvg;

        const matchedIdx = SVG_PRESETS.findIndex(p => p.svg.trim() === currentSvg.trim());
        if (matchedIdx !== -1) {
            selectSvgPreset(matchedIdx);
        } else {
            document.querySelectorAll('.adm-svg-btn').forEach(b => b.classList.remove('selected'));
            document.getElementById('customSvgInput').value = currentSvg;
        }

        document.getElementById('tKeyword').value = t.seo?.targetKeyword || '';
        document.getElementById('tMetaTitle').value = t.seo?.metaTitle || '';
        document.getElementById('tMetaDesc').value = t.seo?.metaDescription || '';
        document.getElementById('tCanonical').value = t.seo?.canonical || '';
        document.getElementById('tOgImage').value = t.seo?.ogImage || '';
        document.getElementById('tIndexable').checked = t.seo?.indexable !== false;

        document.getElementById('codeHtml').value = t.engine?.html || '';
        document.getElementById('codeCss').value = t.engine?.css || '';
        document.getElementById('codeJs').value = t.engine?.js || '';
        document.getElementById('tCdnScripts').value = t.engine?.cdnScripts || '';

        document.getElementById('tAbout').value = t.content?.about || '';
        document.getElementById('tHowTo').value = t.content?.howTo || '';

        document.getElementById('faqContainer').innerHTML = '';
        if (t.faqs && t.faqs.length > 0) {
            t.faqs.forEach(f => addFaqRow(f.q, f.a));
        } else {
            addFaqRow('Is this tool free?', 'Yes, 100% free.');
        }

        updateSerpPreview();

        const liveBtn = document.getElementById('liveTestBtn');
        liveBtn.href = '/tool/' + t.slug;
        liveBtn.classList.remove('d-none');

        // Always activate Tab 1 on edit
        switchModalTab('tab1Basic', document.querySelector('.adm-modal-pills .adm-pill-btn'));

        document.getElementById('modalTitle').innerHTML = `<i class="ti ti-edit text-primary"></i> Edit: ${t.name}`;
        new bootstrap.Modal(document.getElementById('toolModal')).show();
    }

    function autoGenerateSlug(val) {
        if (!document.getElementById('toolId').value) {
            document.getElementById('tSlug').value = val.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
            updateSerpPreview();
        }
    }

    // ── LIVE GOOGLE SERP PREVIEW ──
    function updateSerpPreview() {
        const title = document.getElementById('tMetaTitle').value.trim() || document.getElementById('tName').value.trim() || 'Tool Title Preview';
        const desc = document.getElementById('tMetaDesc').value.trim() || 'Tool description preview will appear here in Google search snippets...';
        const slug = document.getElementById('tSlug').value.trim() || 'tool-slug';

        document.getElementById('serpTitlePreview').innerText = title;
        document.getElementById('serpDescPreview').innerText = desc;
        document.getElementById('serpUrlPreview').innerText = `https://tools.heyswan.cloud/tool/${slug}`;

        document.getElementById('titleCount').innerText = `${document.getElementById('tMetaTitle').value.length} / 60`;
        document.getElementById('descCount').innerText = `${document.getElementById('tMetaDesc').value.length} / 160`;
    }

    document.getElementById('tMetaTitle').addEventListener('input', updateSerpPreview);
    document.getElementById('tMetaDesc').addEventListener('input', updateSerpPreview);
    document.getElementById('tSlug').addEventListener('input', updateSerpPreview);
    document.getElementById('tName').addEventListener('input', updateSerpPreview);

    // ── SAVE FORM ──
    document.getElementById('toolForm').onsubmit = async (e) => {
        e.preventDefault();
        
        const faqs = [];
        document.querySelectorAll('.faq-item-box').forEach(box => {
            const q = box.querySelector('.faq-q').value.trim();
            const a = box.querySelector('.faq-a').value.trim();
            if (q && a) faqs.push({ q, a });
        });

        const slug = document.getElementById('tSlug').value.trim().toLowerCase().replace(/[^a-z0-9-]/g, '-');

        const payload = {
            id: document.getElementById('toolId').value || undefined,
            name: document.getElementById('tName').value.trim(),
            category: document.getElementById('tCategory').value,
            slug: slug,
            badge: document.getElementById('tBadge').value,
            iconSvg: document.getElementById('tIconSvg').value || SVG_PRESETS[0].svg,
            usageCount: parseInt(document.getElementById('tUsageCount').value, 10) || 0,
            targetKeyword: document.getElementById('tKeyword').value.trim(),
            metaTitle: document.getElementById('tMetaTitle').value.trim(),
            metaDescription: document.getElementById('tMetaDesc').value.trim(),
            canonical: document.getElementById('tCanonical').value.trim() || `https://tools.heyswan.cloud/tool/${slug}`,
            ogImage: document.getElementById('tOgImage').value.trim(),
            indexable: document.getElementById('tIndexable').checked,
            about: document.getElementById('tAbout').value.trim(),
            howTo: document.getElementById('tHowTo').value.trim(),
            faqs: faqs,
            engine: {
                html: document.getElementById('codeHtml').value,
                css: document.getElementById('codeCss').value,
                js: document.getElementById('codeJs').value,
                cdnScripts: document.getElementById('tCdnScripts').value.trim()
            }
        };

        const res = await fetch('/api/admin/tools', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(payload)
        });

        if (res.ok) {
            bootstrap.Modal.getInstance(document.getElementById('toolModal')).hide();
            loadTools();
        } else {
            alert('Error saving tool. Please verify inputs.');
        }
    };

    function readFileInto(input, targetTextareaId) {
        const file = input.files[0];
        if (!file) return;

        const reader = new FileReader();
        reader.onload = function(e) {
            document.getElementById(targetTextareaId).value = e.target.result;
        };
        reader.readAsText(file);
        input.value = '';
    }

    function addFaqRow(q = '', a = '') {
        const container = document.getElementById('faqContainer');
        const div = document.createElement('div');
        div.className = 'card p-2 bg-light border rounded-3 faq-item-box';
        div.innerHTML = `
            <div class="d-flex justify-content-between gap-2 mb-1">
                <input type="text" class="form-control form-control-sm faq-q bg-white" placeholder="Question (e.g. Is this tool free?)" value="${q.replace(/"/g, '&quot;')}" required>
                <button type="button" class="btn btn-sm btn-link text-danger p-0" onclick="this.closest('.faq-item-box').remove()"><i class="ti ti-trash"></i></button>
            </div>
            <textarea class="form-control form-control-sm faq-a bg-white" rows="2" placeholder="Answer..." required>${a}</textarea>
        `;
        container.appendChild(div);
    }

    async function toggleTool(id) {
        await fetch('/api/admin/tools/toggle/' + id, { method: 'POST' });
        loadTools();
    }

    async function deleteTool(id) {
        if (confirm('Are you sure you want to delete this tool?')) {
            await fetch('/api/admin/tools/' + id, { method: 'DELETE' });
            loadTools();
        }
    }

    renderSvgPicker();
    loadTools();
</script>

<%- include('../partials/footer') %>