<?php
/**
 * Landing Page Builder — Elementor-style visual editor
 * Shared partial included in create.php and edit.php
 *
 * Outputs:
 *  - #lpb-root  — full-screen builder UI
 *  - hidden input #layoutInput (name="layout") that stores JSON
 *
 * Compatible with existing syncLayout() / hydrate layout logic in both files.
 * The builder serialises its state into the same `layout` JSON field already
 * used by the toggles, so the back-end needs zero changes.
 *
 * JSON shape written to #layoutInput:
 * {
 *   "toggles": { sticky_buy, whatsapp, reviews, countdown },   ← kept as-is
 *   "sections": [ { id, type, settings:{} }, … ]               ← new
 * }
 */
?>

<!-- ═══════════════════════════════════════════════════
     LANDING PAGE BUILDER STYLES
═══════════════════════════════════════════════════ -->
<style>
/* ── Variables ── */
:root {
  --lpb-bg:          #0f1117;
  --lpb-panel:       #181c27;
  --lpb-panel2:      #1e2330;
  --lpb-border:      #2a2f3f;
  --lpb-accent:      #4f7eff;
  --lpb-accent2:     #7c4fff;
  --lpb-text:        #e4e8f0;
  --lpb-muted:       #6b7592;
  --lpb-success:     #22c55e;
  --lpb-danger:      #ef4444;
  --lpb-warn:        #f59e0b;
  --lpb-radius:      10px;
  --lpb-sidebar-w:   300px;
  --lpb-props-w:     320px;
  --lpb-toolbar-h:   56px;
}

/* ── Overlay trigger button ── */
#lpb-open-btn {
  background: linear-gradient(135deg, var(--lpb-accent), var(--lpb-accent2));
  border: none;
  border-radius: var(--lpb-radius);
  color: #fff;
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  gap: 10px;
  font-size: 15px;
  font-weight: 600;
  padding: 13px 24px;
  transition: all .25s;
  box-shadow: 0 4px 20px rgba(79,126,255,.4);
  width: 100%;
  justify-content: center;
  letter-spacing: .3px;
}
#lpb-open-btn:hover { transform: translateY(-2px); box-shadow: 0 8px 32px rgba(79,126,255,.55); }
#lpb-open-btn svg   { width:22px; height:22px; flex-shrink:0; }

.lpb-stats-row {
  display: flex; gap: 12px; margin-top: 12px;
}
.lpb-stat-badge {
  background: var(--lpb-panel2);
  border: 1px solid var(--lpb-border);
  border-radius: 8px;
  padding: 8px 14px;
  font-size: 12px;
  color: var(--lpb-muted);
  flex: 1; text-align: center;
}
.lpb-stat-badge strong { display:block; color: var(--lpb-text); font-size:18px; margin-bottom:2px; }

/* ── Full-screen overlay ── */
#lpb-root {
  position: fixed;
  inset: 0;
  z-index: 9999;
  display: none;
  flex-direction: column;
  background: var(--lpb-bg);
  font-family: inherit;
  color: var(--lpb-text);
}
#lpb-root.lpb-open { display: flex; }

/* ── Toolbar ── */
#lpb-toolbar {
  height: var(--lpb-toolbar-h);
  background: var(--lpb-panel);
  border-bottom: 1px solid var(--lpb-border);
  display: flex;
  align-items: center;
  padding: 0 16px;
  gap: 10px;
  flex-shrink: 0;
}
.lpb-brand {
  font-size: 16px;
  font-weight: 700;
  background: linear-gradient(135deg, var(--lpb-accent), var(--lpb-accent2));
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  margin-right: 8px;
  display: flex; align-items: center; gap: 8px;
}
.lpb-brand svg { width:22px; height:22px; fill: var(--lpb-accent); }
.lpb-toolbar-sep { width:1px; height:28px; background:var(--lpb-border); margin:0 4px; }
.lpb-toolbar-btn {
  background: transparent;
  border: 1px solid var(--lpb-border);
  border-radius: 7px;
  color: var(--lpb-text);
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  gap: 6px;
  font-size: 13px;
  padding: 6px 12px;
  transition: all .18s;
}
.lpb-toolbar-btn:hover  { background: var(--lpb-panel2); border-color: var(--lpb-accent); }
.lpb-toolbar-btn.active { background: var(--lpb-panel2); border-color: var(--lpb-accent); }
.lpb-toolbar-btn.primary {
  background: var(--lpb-accent);
  border-color: var(--lpb-accent);
  color: #fff;
  font-weight: 600;
}
.lpb-toolbar-btn.primary:hover { background: #3a6ae8; }
.lpb-toolbar-btn.danger { border-color: var(--lpb-danger); color: var(--lpb-danger); }
.lpb-toolbar-btn.danger:hover { background: rgba(239,68,68,.12); }
.lpb-viewport-btns { display:flex; gap:4px; margin-left:auto; margin-right: 8px; }
.lpb-vp-btn {
  background: transparent;
  border: 1px solid var(--lpb-border);
  border-radius: 6px;
  color: var(--lpb-muted);
  cursor: pointer;
  padding: 5px 9px;
  font-size: 14px;
  transition: all .18s;
}
.lpb-vp-btn.active, .lpb-vp-btn:hover {
  background: var(--lpb-panel2); border-color: var(--lpb-accent); color: var(--lpb-accent);
}
#lpb-undo-btn, #lpb-redo-btn {
  background: transparent; border: 1px solid var(--lpb-border);
  border-radius: 6px; color: var(--lpb-muted);
  cursor: pointer; padding: 5px 9px; font-size: 14px; transition: all .18s;
}
#lpb-undo-btn:hover, #lpb-redo-btn:hover { background: var(--lpb-panel2); color: var(--lpb-text); }
#lpb-undo-btn:disabled, #lpb-redo-btn:disabled { opacity:.35; cursor:default; }

/* ── Body ── */
#lpb-body {
  display: flex;
  flex: 1;
  overflow: hidden;
}

/* ── Left sidebar: section types ── */
#lpb-sidebar {
  width: var(--lpb-sidebar-w);
  background: var(--lpb-panel);
  border-right: 1px solid var(--lpb-border);
  display: flex;
  flex-direction: column;
  flex-shrink: 0;
  overflow: hidden;
}
#lpb-sidebar-header {
  padding: 14px 16px 10px;
  border-bottom: 1px solid var(--lpb-border);
  font-size: 11px;
  font-weight: 700;
  letter-spacing: 1px;
  color: var(--lpb-muted);
  text-transform: uppercase;
  display: flex; align-items: center; gap: 8px;
}
#lpb-sidebar-search {
  background: var(--lpb-panel2);
  border: 1px solid var(--lpb-border);
  border-radius: 7px;
  color: var(--lpb-text);
  font-size: 13px;
  padding: 8px 12px;
  margin: 10px 12px 0;
  outline: none;
  width: calc(100% - 24px);
  transition: border-color .18s;
}
#lpb-sidebar-search:focus { border-color: var(--lpb-accent); }
#lpb-sidebar-search::placeholder { color: var(--lpb-muted); }
#lpb-elements-list {
  overflow-y: auto;
  flex: 1;
  padding: 10px 10px 16px;
  scrollbar-width: thin;
  scrollbar-color: var(--lpb-border) transparent;
}
.lpb-category-label {
  font-size: 10px;
  font-weight: 700;
  letter-spacing: 1px;
  color: var(--lpb-muted);
  text-transform: uppercase;
  padding: 10px 6px 5px;
}
.lpb-element-card {
  align-items: center;
  background: var(--lpb-panel2);
  border: 1px solid var(--lpb-border);
  border-radius: 8px;
  color: var(--lpb-text);
  cursor: grab;
  display: flex;
  gap: 10px;
  margin-bottom: 6px;
  padding: 10px 12px;
  transition: all .18s;
  user-select: none;
}
.lpb-element-card:hover {
  border-color: var(--lpb-accent);
  background: rgba(79,126,255,.07);
  transform: translateX(3px);
}
.lpb-element-card:active { cursor: grabbing; }
.lpb-element-icon {
  font-size: 18px;
  width: 36px;
  height: 36px;
  background: rgba(79,126,255,.12);
  border-radius: 7px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}
.lpb-element-info { flex: 1; min-width: 0; }
.lpb-element-name { font-size: 13px; font-weight: 600; }
.lpb-element-desc { font-size: 11px; color: var(--lpb-muted); margin-top: 1px; }

/* ── Canvas ── */
#lpb-canvas-wrap {
  flex: 1;
  overflow: auto;
  display: flex;
  flex-direction: column;
  align-items: center;
  background: #0a0d14;
  padding: 20px;
  position: relative;
}
#lpb-canvas-frame {
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 20px 80px rgba(0,0,0,.6);
  overflow: hidden;
  transition: width .3s ease;
  position: relative;
  width: 100%;
  max-width: 1200px;
  min-height: 600px;
}
#lpb-canvas-frame.vp-tablet  { max-width: 768px; }
#lpb-canvas-frame.vp-mobile  { max-width: 390px; }

/* Empty state */
#lpb-empty-state {
  position: absolute;
  inset: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #9ca3af;
  pointer-events: none;
}
#lpb-empty-state.lpb-hidden { display: none; }
#lpb-empty-state svg { opacity: .25; width:64px; height:64px; margin-bottom:16px; }
#lpb-empty-state p  { font-size:16px; font-weight:600; color:#6b7280; }
#lpb-empty-state small { font-size:13px; color:#9ca3af; }

/* Drop targets */
#lpb-sections-list {
  min-height: 100%;
  padding-bottom: 40px;
}
.lpb-drop-zone {
  height: 8px;
  background: transparent;
  transition: all .2s;
  position: relative;
}
.lpb-drop-zone.drag-over {
  height: 48px;
  background: rgba(79,126,255,.12);
  border: 2px dashed var(--lpb-accent);
  border-radius: 8px;
}
.lpb-drop-zone.drag-over::after {
  /* content set via JS */
  position: absolute;
  inset: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  color: var(--lpb-accent);
  font-weight: 600;
}

/* Section wrapper in canvas */
.lpb-section-wrapper {
  position: relative;
  cursor: pointer;
  border: 2px solid transparent;
  transition: border-color .15s;
}
.lpb-section-wrapper:hover {
  border-color: rgba(79,126,255,.4);
}
.lpb-section-wrapper.lpb-selected {
  border-color: var(--lpb-accent) !important;
}
.lpb-section-controls {
  position: absolute;
  top: 0;
  right: 0;
  display: none;
  z-index: 10;
  gap: 4px;
  background: var(--lpb-accent);
  border-radius: 0 0 0 8px;
  padding: 4px 6px;
}
.lpb-section-wrapper:hover .lpb-section-controls,
.lpb-section-wrapper.lpb-selected .lpb-section-controls {
  display: flex;
}
.lpb-sc-btn {
  background: rgba(255,255,255,.2);
  border: none;
  border-radius: 4px;
  color: #fff;
  cursor: pointer;
  font-size: 12px;
  padding: 3px 6px;
  transition: background .15s;
  display:flex; align-items:center; gap:3px;
}
.lpb-sc-btn:hover { background: rgba(255,255,255,.35); }
.lpb-sc-btn.danger { background: rgba(239,68,68,.6); }
.lpb-sc-btn.danger:hover { background: var(--lpb-danger); }
.lpb-drag-handle {
  cursor: move;
  padding: 3px 6px;
  background: rgba(255,255,255,.15);
  border-radius: 4px;
  display:flex; align-items:center;
}
.lpb-section-type-badge {
  position: absolute;
  top: 0; left: 0;
  background: var(--lpb-accent);
  color: #fff;
  font-size: 10px;
  font-weight: 700;
  padding: 2px 8px;
  border-radius: 0 0 6px 0;
  letter-spacing: .5px;
  text-transform: uppercase;
  display: none;
}
.lpb-section-wrapper:hover .lpb-section-type-badge,
.lpb-section-wrapper.lpb-selected .lpb-section-type-badge {
  display: block;
}

/* ── Right: Properties panel ── */
#lpb-props {
  width: var(--lpb-props-w);
  background: var(--lpb-panel);
  border-left: 1px solid var(--lpb-border);
  display: flex;
  flex-direction: column;
  flex-shrink: 0;
  overflow: hidden;
}
#lpb-props-header {
  padding: 0 16px;
  height: 48px;
  border-bottom: 1px solid var(--lpb-border);
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 700;
  font-size: 13px;
}
#lpb-props-header .lpb-props-type {
  background: rgba(79,126,255,.15);
  color: var(--lpb-accent);
  border-radius: 5px;
  font-size: 10px;
  font-weight: 700;
  letter-spacing: .8px;
  padding: 2px 8px;
  text-transform: uppercase;
}
#lpb-props-body {
  overflow-y: auto;
  flex: 1;
  padding: 16px;
  scrollbar-width: thin;
  scrollbar-color: var(--lpb-border) transparent;
}
.lpb-no-selection {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: var(--lpb-muted);
  text-align: center;
  gap: 12px;
  padding: 24px;
}
.lpb-no-selection svg { opacity:.3; width:48px; height:48px; }
.lpb-no-selection p  { font-size:13px; }

/* ── Props form fields ── */
.lpb-field       { margin-bottom: 16px; }
.lpb-field label {
  display: block;
  font-size: 11px;
  font-weight: 700;
  letter-spacing: .6px;
  color: var(--lpb-muted);
  text-transform: uppercase;
  margin-bottom: 6px;
}
.lpb-field input[type=text],
.lpb-field input[type=number],
.lpb-field input[type=url],
.lpb-field textarea,
.lpb-field select {
  width: 100%;
  background: var(--lpb-panel2);
  border: 1px solid var(--lpb-border);
  border-radius: 7px;
  color: var(--lpb-text);
  font-size: 13px;
  padding: 8px 10px;
  outline: none;
  transition: border-color .18s;
  resize: vertical;
}
.lpb-field input[type=text]:focus,
.lpb-field input[type=number]:focus,
.lpb-field input[type=url]:focus,
.lpb-field textarea:focus,
.lpb-field select:focus { border-color: var(--lpb-accent); }
.lpb-field input[type=color] {
  width: 100%;
  height: 36px;
  border: 1px solid var(--lpb-border);
  border-radius: 7px;
  cursor: pointer;
  background: var(--lpb-panel2);
  padding: 2px 4px;
}
.lpb-field-row { display:flex; gap:8px; }
.lpb-field-row .lpb-field { flex:1; }
.lpb-section-divider {
  border: none;
  border-top: 1px solid var(--lpb-border);
  margin: 16px 0;
}
.lpb-props-section-label {
  font-size: 10px;
  font-weight: 700;
  letter-spacing: 1px;
  color: var(--lpb-muted);
  text-transform: uppercase;
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  gap: 8px;
}
.lpb-props-section-label::after {
  content: '';
  flex: 1;
  height: 1px;
  background: var(--lpb-border);
}
.lpb-toggle-field {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}
.lpb-toggle-field label {
  font-size: 13px;
  font-weight: 500;
  color: var(--lpb-text);
  text-transform: none;
  letter-spacing: 0;
  cursor: pointer;
}
.lpb-toggle {
  position: relative; width:40px; height:22px; cursor:pointer;
}
.lpb-toggle input { opacity:0; width:0; height:0; position:absolute; }
.lpb-toggle-track {
  position:absolute; inset:0;
  background: var(--lpb-border);
  border-radius: 22px;
  transition: background .2s;
}
.lpb-toggle input:checked ~ .lpb-toggle-track { background: var(--lpb-accent); }
.lpb-toggle-thumb {
  position:absolute;
  top:3px; left:3px;
  width:16px; height:16px;
  background:#fff;
  border-radius:50%;
  transition: transform .2s;
}
.lpb-toggle input:checked ~ .lpb-toggle-track .lpb-toggle-thumb {
  transform: translateX(18px);
}

/* Repeater (list items) */
.lpb-repeater-item {
  background: var(--lpb-panel2);
  border: 1px solid var(--lpb-border);
  border-radius: 8px;
  margin-bottom: 8px;
  overflow: hidden;
}
.lpb-repeater-head {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 12px;
  cursor: pointer;
  font-size: 13px;
  font-weight: 600;
  transition: background .15s;
}
.lpb-repeater-head:hover { background: rgba(255,255,255,.04); }
.lpb-repeater-body {
  border-top: 1px solid var(--lpb-border);
  padding: 12px;
}
.lpb-repeater-body.lpb-hidden { display: none; }
.lpb-add-item-btn {
  background: transparent;
  border: 1px dashed var(--lpb-border);
  border-radius: 7px;
  color: var(--lpb-accent);
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  font-size: 13px;
  padding: 8px;
  width: 100%;
  transition: all .18s;
}
.lpb-add-item-btn:hover { border-color: var(--lpb-accent); background: rgba(79,126,255,.07); }
.lpb-remove-item-btn {
  background: transparent;
  border: none;
  color: var(--lpb-danger);
  cursor: pointer;
  font-size: 14px;
  padding: 2px 6px;
  border-radius: 4px;
  transition: background .15s;
}
.lpb-remove-item-btn:hover { background: rgba(239,68,68,.12); }

/* Tabs in props (Layout/Style) */
.lpb-props-tabs { display:flex; border-bottom:1px solid var(--lpb-border); margin-bottom:14px; }
.lpb-props-tab  {
  flex:1; text-align:center;
  padding:8px; font-size:12px; font-weight:600;
  color:var(--lpb-muted); cursor:pointer;
  border-bottom:2px solid transparent;
  transition: all .18s;
}
.lpb-props-tab.active { color:var(--lpb-accent); border-bottom-color:var(--lpb-accent); }
.lpb-props-tabpane { display:none; }
.lpb-props-tabpane.active { display:block; }

/* ── Section renderers (canvas HTML) ── */
/* These are the live preview styles inside #lpb-canvas-frame */
.lpb-render-hero {
  position: relative;
  overflow: hidden;
  display: flex;
  align-items: center;
  min-height: 480px;
}
.lpb-render-hero .lpb-hero-bg {
  position: absolute;
  inset: 0;
  background-size: cover;
  background-position: center;
}
.lpb-render-hero .lpb-hero-overlay {
  position: absolute;
  inset: 0;
}
.lpb-render-hero .lpb-hero-content {
  position: relative;
  z-index: 2;
  max-width: 700px;
  padding: 60px 48px;
}
.lpb-render-hero .lpb-hero-badge {
  display: inline-block;
  border-radius: 100px;
  font-size: 12px;
  font-weight: 700;
  letter-spacing: .8px;
  padding: 4px 14px;
  margin-bottom: 20px;
  text-transform: uppercase;
}
.lpb-render-hero h1 {
  font-size: 48px;
  font-weight: 800;
  line-height: 1.15;
  margin-bottom: 16px;
}
.lpb-render-hero p {
  font-size: 17px;
  line-height: 1.7;
  margin-bottom: 32px;
  opacity: .85;
}
.lpb-render-hero .lpb-hero-btn {
  display: inline-block;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 700;
  padding: 14px 32px;
  text-decoration: none;
  transition: all .2s;
  cursor: pointer;
  border: none;
}
.lpb-render-features {
  padding: 64px 48px;
  background: #f9fafb;
}
.lpb-render-features h2 {
  text-align: center;
  font-size: 32px;
  font-weight: 800;
  margin-bottom: 8px;
}
.lpb-render-features .lpb-subtitle {
  text-align: center;
  color: #6b7280;
  margin-bottom: 48px;
  font-size: 16px;
}
.lpb-features-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
  gap: 24px;
}
.lpb-feature-item {
  background: #fff;
  border-radius: 14px;
  padding: 28px 24px;
  text-align: center;
  box-shadow: 0 2px 16px rgba(0,0,0,.06);
  transition: transform .2s;
}
.lpb-feature-item:hover { transform: translateY(-4px); }
.lpb-feature-icon {
  font-size: 36px;
  margin-bottom: 14px;
  display: block;
}
.lpb-feature-item h3 { font-size: 17px; font-weight: 700; margin-bottom: 8px; }
.lpb-feature-item p  { font-size: 14px; color: #6b7280; margin: 0; }

.lpb-render-testimonials {
  padding: 64px 48px;
}
.lpb-render-testimonials h2 {
  text-align: center;
  font-size: 32px;
  font-weight: 800;
  margin-bottom: 8px;
}
.lpb-render-testimonials .lpb-subtitle {
  text-align: center;
  color: #6b7280;
  margin-bottom: 48px;
  font-size: 16px;
}
.lpb-testimonials-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
  gap: 20px;
}
.lpb-testimonial-card {
  background: #fff;
  border-radius: 14px;
  padding: 24px;
  box-shadow: 0 2px 16px rgba(0,0,0,.07);
}
.lpb-testimonial-stars { color: #f59e0b; font-size: 16px; margin-bottom: 10px; }
.lpb-testimonial-text  { font-size: 14px; color: #374151; font-style: italic; margin-bottom: 16px; }
.lpb-testimonial-author { display:flex; align-items:center; gap:10px; }
.lpb-testimonial-avatar {
  width:40px; height:40px; border-radius:50%; background:#e5e7eb;
  display:flex; align-items:center; justify-content:center;
  font-size:16px; font-weight:700; color:#6b7280; flex-shrink:0;
}
.lpb-testimonial-name  { font-size:14px; font-weight:700; }
.lpb-testimonial-role  { font-size:12px; color:#9ca3af; }

.lpb-render-faq {
  padding: 64px 48px;
  background: #f9fafb;
  max-width: 760px;
  margin: 0 auto;
}
.lpb-render-faq h2 {
  text-align: center;
  font-size: 32px;
  font-weight: 800;
  margin-bottom: 8px;
}
.lpb-render-faq .lpb-subtitle {
  text-align: center;
  color: #6b7280;
  margin-bottom: 40px;
}
.lpb-faq-item {
  background: #fff;
  border-radius: 10px;
  margin-bottom: 10px;
  box-shadow: 0 1px 8px rgba(0,0,0,.05);
  overflow: hidden;
}
.lpb-faq-question {
  cursor: pointer;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 15px;
  font-weight: 600;
  padding: 16px 20px;
  user-select: none;
}
.lpb-faq-answer {
  font-size: 14px;
  color: #6b7280;
  line-height: 1.7;
  padding: 0 20px 16px;
  display: none;
}
.lpb-faq-item.open .lpb-faq-answer { display: block; }
.lpb-faq-icon { font-size: 18px; transition: transform .2s; }
.lpb-faq-item.open .lpb-faq-icon { transform: rotate(45deg); }

.lpb-render-countdown {
  padding: 48px;
  text-align: center;
}
.lpb-render-countdown h2 {
  font-size: 28px;
  font-weight: 800;
  margin-bottom: 10px;
}
.lpb-render-countdown p { font-size: 16px; margin-bottom: 28px; }
.lpb-countdown-timer {
  display: flex;
  gap: 16px;
  justify-content: center;
  flex-wrap: wrap;
}
.lpb-countdown-unit {
  border-radius: 12px;
  padding: 20px 24px;
  min-width: 90px;
  text-align: center;
}
.lpb-countdown-unit .lpb-number {
  font-size: 48px;
  font-weight: 900;
  line-height: 1;
  display: block;
}
.lpb-countdown-unit .lpb-label {
  font-size: 12px;
  font-weight: 700;
  letter-spacing: 1px;
  text-transform: uppercase;
  opacity: .7;
  margin-top: 4px;
  display: block;
}

.lpb-render-trust {
  padding: 40px 48px;
  background: #fff;
}
.lpb-render-trust h2 {
  text-align: center;
  font-size: 24px;
  font-weight: 800;
  margin-bottom: 32px;
}
.lpb-trust-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  justify-content: center;
}
.lpb-trust-badge-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  background: #f9fafb;
  border-radius: 12px;
  padding: 20px 24px;
  min-width: 130px;
}
.lpb-trust-badge-icon { font-size: 32px; }
.lpb-trust-badge-text { font-size: 13px; font-weight: 700; text-align:center; color:#1f2937; }
.lpb-trust-badge-sub  { font-size: 11px; color:#6b7280; text-align:center; }

.lpb-render-cta {
  padding: 64px 48px;
  text-align: center;
}
.lpb-render-cta h2 {
  font-size: 36px;
  font-weight: 800;
  margin-bottom: 12px;
}
.lpb-render-cta p { font-size: 17px; margin-bottom: 32px; opacity:.85; }
.lpb-render-cta .lpb-cta-btn {
  display: inline-block;
  border-radius: 8px;
  font-size: 17px;
  font-weight: 700;
  padding: 16px 40px;
  text-decoration: none;
  cursor: pointer;
  border: none;
}

.lpb-render-custom {
  padding: 40px 48px;
}

.lpb-render-image-text {
  display: flex;
  align-items: center;
  min-height: 360px;
  overflow: hidden;
}
.lpb-render-image-text.img-right { flex-direction: row-reverse; }
.lpb-render-image-text .lpb-img-col {
  flex: 1;
  min-height: 360px;
  background-size: cover;
  background-position: center;
}
.lpb-render-image-text .lpb-text-col {
  flex: 1;
  padding: 48px;
}
.lpb-render-image-text h2 { font-size:30px; font-weight:800; margin-bottom:12px; }
.lpb-render-image-text p  { font-size:16px; line-height:1.7; color:#4b5563; }
.lpb-render-image-text .lpb-it-btn {
  display: inline-block; margin-top:24px;
  border-radius:8px; font-size:15px; font-weight:700;
  padding:12px 28px; text-decoration:none; cursor:pointer; border:none;
}

.lpb-render-divider {
  padding: 24px 48px;
  text-align: center;
}
.lpb-render-divider hr { border-color: currentColor; opacity: .2; }

/* ── Scrollbars ── */
::-webkit-scrollbar        { width: 6px; height: 6px; }
::-webkit-scrollbar-track  { background: transparent; }
::-webkit-scrollbar-thumb  { background: var(--lpb-border); border-radius: 3px; }
::-webkit-scrollbar-thumb:hover { background: var(--lpb-muted); }

/* ── Drag ghost ── */
.lpb-dragging { opacity: .4; }
.lpb-ghost    { outline: 2px dashed var(--lpb-accent); outline-offset: 2px; }

/* ── Responsive label ── */
#lpb-vp-label {
  font-size: 11px;
  color: var(--lpb-muted);
  text-align: center;
  margin-bottom: 8px;
}
</style>

<!-- ═══════════════════════════════════════════════════
     OPEN BUTTON + STATS (shown in the tab, outside builder)
═══════════════════════════════════════════════════ -->
<div id="lpb-trigger-area" style="padding:12px 0;">
  <button type="button" id="lpb-open-btn">
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
      <rect x="3" y="3" width="7" height="7" rx="1"/>
      <rect x="14" y="3" width="7" height="7" rx="1"/>
      <rect x="3" y="14" width="7" height="7" rx="1"/>
      <rect x="14" y="14" width="7" height="7" rx="1"/>
    </svg>
    <?= __('lpb.open_builder', 'Open Landing Page Builder') ?>
  </button>
  <div class="lpb-stats-row">
    <div class="lpb-stat-badge">
      <strong id="lpb-stat-sections">0</strong>
      <?= __('lpb.sections', 'Sections') ?>
    </div>
    <div class="lpb-stat-badge" id="lpb-stat-status-badge">
      <strong>—</strong>
      <?= __('lpb.status', 'Status') ?>
    </div>
    <div class="lpb-stat-badge">
      <strong id="lpb-stat-type">—</strong>
      <?= __('lpb.last_type', 'Last Added') ?>
    </div>
  </div>
</div>

<!-- Keep the existing toggles hidden (they still save to JSON) -->
<div id="lpb-legacy-toggles" style="display:none;">
  <div class="form-check form-switch mb-3">
    <input class="form-check-input" type="checkbox" role="switch" id="toggle_sticky_buy">
    <label class="form-check-label fw-semibold" for="toggle_sticky_buy"><?= __('sections.sticky_buy') ?></label>
  </div>
  <div class="form-check form-switch mb-3">
    <input class="form-check-input" type="checkbox" role="switch" id="toggle_whatsapp">
    <label class="form-check-label fw-semibold" for="toggle_whatsapp"><?= __('sections.whatsapp') ?></label>
  </div>
  <div class="form-check form-switch mb-3">
    <input class="form-check-input" type="checkbox" role="switch" id="toggle_reviews">
    <label class="form-check-label fw-semibold" for="toggle_reviews"><?= __('sections.reviews') ?></label>
  </div>
  <div class="form-check form-switch mb-2">
    <input class="form-check-input" type="checkbox" role="switch" id="toggle_countdown">
    <label class="form-check-label fw-semibold" for="toggle_countdown"><?= __('sections.countdown') ?></label>
  </div>
</div>

<!-- ═══════════════════════════════════════════════════
     BUILDER OVERLAY
═══════════════════════════════════════════════════ -->
<div id="lpb-root">

  <!-- TOOLBAR -->
  <div id="lpb-toolbar">
    <span class="lpb-brand">
      <svg viewBox="0 0 24 24"><path d="M3 3h7v7H3zm11 0h7v7h-7zM3 14h7v7H3zm11 3l3-3 3 3-3 3z"/></svg>
      <?= __('lpb.toolbar_title','Page Builder') ?>
    </span>
    <div class="lpb-toolbar-sep"></div>
    <button type="button" class="lpb-toolbar-btn" id="lpb-undo-btn" title="<?= __('lpb.undo','Undo') ?>" disabled>↩</button>
    <button type="button" class="lpb-toolbar-btn" id="lpb-redo-btn" title="<?= __('lpb.redo','Redo') ?>" disabled>↪</button>
    <div class="lpb-toolbar-sep"></div>
    <button type="button" class="lpb-toolbar-btn" id="lpb-clear-btn">
      🗑 <?= __('lpb.clear', 'Clear All') ?>
    </button>
    <div class="lpb-viewport-btns">
      <div id="lpb-vp-label"><?= __("lpb.label_preview","Preview") ?></div>
      <button type="button" class="lpb-vp-btn active" data-vp="desktop" title="<?= __('lpb.vp_desktop','Desktop') ?>">🖥</button>
      <button type="button" class="lpb-vp-btn" data-vp="tablet" title="<?= __('lpb.vp_tablet','Tablet') ?>">📱</button>
      <button type="button" class="lpb-vp-btn" data-vp="mobile" title="<?= __('lpb.vp_mobile','Mobile') ?>">📲</button>
    </div>
    <button type="button" class="lpb-toolbar-btn primary" id="lpb-save-btn">
      ✓ <?= __('lpb.save_close', 'Save & Close') ?>
    </button>
    <button type="button" class="lpb-toolbar-btn danger" id="lpb-close-btn">✕</button>
  </div>

  <!-- BODY -->
  <div id="lpb-body">

    <!-- LEFT SIDEBAR -->
    <div id="lpb-sidebar">
      <div id="lpb-sidebar-header">
        <span>⚡</span> <?= __('lpb.label_elements','Elements') ?>
      </div>
      <input type="text" id="lpb-sidebar-search" placeholder="<?= htmlspecialchars(__('lpb.search_ph','Search elements…'), ENT_QUOTES) ?>">
      <div id="lpb-elements-list">
        <!-- Populated by JS -->
      </div>
    </div>

    <!-- CANVAS -->
    <div id="lpb-canvas-wrap">
      <div id="lpb-canvas-frame">
        <div id="lpb-empty-state">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
            <path d="M12 5v14M5 12h14"/>
          </svg>
          <p><?= __('lpb.empty_state','Your page is empty') ?></p>
          <small><?= __('lpb.empty_hint','Drag elements from the left panel or click to add') ?></small>
        </div>
        <div id="lpb-sections-list">
          <div class="lpb-drop-zone" data-index="0"></div>
        </div>
      </div>
    </div>

    <!-- PROPS PANEL -->
    <div id="lpb-props">
      <div id="lpb-props-header">
        <span>⚙️</span>
        <span id="lpb-props-title"><?= __('lpb.props_title','Properties') ?></span>
        <span class="lpb-props-type" id="lpb-props-type-badge" style="display:none"></span>
      </div>
      <div id="lpb-props-body">
        <div class="lpb-no-selection" id="lpb-no-selection">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
            <path d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/>
            <path 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"/>
          </svg>
          <p><?= __('lpb.no_selection','Select a section to edit its properties') ?></p>
        </div>
        <div id="lpb-props-content" style="display:none"></div>
      </div>
    </div>

  </div>
</div>

<!-- ═══════════════════════════════════════════════════
     BUILDER JAVASCRIPT
═══════════════════════════════════════════════════ -->
<!-- LPB i18n — translation strings -->
<script>
var lpbI18n = {
    confirmClose   : "<?= addslashes(__('lpb.confirm_close',    'Close without saving?')) ?>",
    confirmClear   : "<?= addslashes(__('lpb.confirm_clear',    'Remove all sections?')) ?>",
    saveToast      : "<?= addslashes(__('lpb.save_toast',       '✓ Landing page saved!')) ?>",
    statActive     : "<?= addslashes(__('lpb.stat_active',      '✓ Active')) ?>",
    dropHere       : "<?= addslashes(__('lpb.drop_here',        'Drop here')) ?>",
    emptyState     : "<?= addslashes(__('lpb.empty_state',      'Your page is empty')) ?>",
    emptyHint      : "<?= addslashes(__('lpb.empty_hint',       'Drag elements from the left panel or click to add')) ?>",
    toolbarTitle   : "<?= addslashes(__('lpb.toolbar_title',    'Page Builder')) ?>",
    btnClear       : "<?= addslashes(__('lpb.btn_clear',        'Clear All')) ?>",
    btnSave        : "<?= addslashes(__('lpb.btn_save',         'Save & Close')) ?>",
    btnAddItem     : "<?= addslashes(__('lpb.btn_add_item',     '+ Add Item')) ?>",
    labelPreview   : "<?= addslashes(__('lpb.label_preview',    'Preview')) ?>",
    labelElements  : "<?= addslashes(__('lpb.label_elements',   'Elements')) ?>",
    searchPh       : "<?= addslashes(__('lpb.search_ph',        'Search elements…')) ?>",
    propsTitle     : "<?= addslashes(__('lpb.props_title',      'Properties')) ?>",
    noSelection    : "<?= addslashes(__('lpb.no_selection',     'Select a section to edit its properties')) ?>",
    labelSections  : "<?= addslashes(__('lpb.sections',         'Sections')) ?>",
    labelStatus    : "<?= addslashes(__('lpb.status',           'Status')) ?>",
    labelLastType  : "<?= addslashes(__('lpb.last_type',        'Last Added')) ?>",
    vpDesktop      : "<?= addslashes(__('lpb.vp_desktop',       'Desktop')) ?>",
    vpTablet       : "<?= addslashes(__('lpb.vp_tablet',        'Tablet')) ?>",
    vpMobile       : "<?= addslashes(__('lpb.vp_mobile',        'Mobile')) ?>",
    ctrlUp         : "<?= addslashes(__('lpb.ctrl_up',          'Move Up')) ?>",
    ctrlDown       : "<?= addslashes(__('lpb.ctrl_down',        'Move Down')) ?>",
    ctrlDup        : "<?= addslashes(__('lpb.ctrl_dup',         'Duplicate')) ?>",
    ctrlDel        : "<?= addslashes(__('lpb.ctrl_del',         'Delete')) ?>",
    fHeading       : "<?= addslashes(__('lpb.f_heading',        'Heading')) ?>",
    fSubheading    : "<?= addslashes(__('lpb.f_subheading',     'Subheading')) ?>",
    fText          : "<?= addslashes(__('lpb.f_text',           'Text')) ?>",
    fHtml          : "<?= addslashes(__('lpb.f_html',           'HTML Code')) ?>",
    fBtnText       : "<?= addslashes(__('lpb.f_btn_text',       'Button Text')) ?>",
    fBtnUrl        : "<?= addslashes(__('lpb.f_btn_url',        'Button URL')) ?>",
    fImage         : "<?= addslashes(__('lpb.f_image',          'Image URL')) ?>",
    fBgImage       : "<?= addslashes(__('lpb.f_bg_image',       'Background Image URL')) ?>",
    fImgPos        : "<?= addslashes(__('lpb.f_img_pos',        'Image Position')) ?>",
    fAlign         : "<?= addslashes(__('lpb.f_align',          'Text Align')) ?>",
    fMinHeight     : "<?= addslashes(__('lpb.f_min_height',     'Min Height (px)')) ?>",
    fOverlay       : "<?= addslashes(__('lpb.f_overlay',        'Overlay Color')) ?>",
    fBgColor       : "<?= addslashes(__('lpb.f_bg_color',       'Background Color')) ?>",
    fTextColor     : "<?= addslashes(__('lpb.f_text_color',     'Text Color')) ?>",
    fBtnBg         : "<?= addslashes(__('lpb.f_btn_bg',         'Button Background')) ?>",
    fBtnColor      : "<?= addslashes(__('lpb.f_btn_color',      'Button Text Color')) ?>",
    fBadgeBg       : "<?= addslashes(__('lpb.f_badge_bg',       'Badge Background')) ?>",
    fBadgeColor    : "<?= addslashes(__('lpb.f_badge_color',    'Badge Text Color')) ?>",
    fTimerBg       : "<?= addslashes(__('lpb.f_timer_bg',       'Timer Background')) ?>",
    fTimerColor    : "<?= addslashes(__('lpb.f_timer_color',    'Timer Text Color')) ?>",
    fLineColor     : "<?= addslashes(__('lpb.f_line_color',     'Line Color')) ?>",
    fLineHeight    : "<?= addslashes(__('lpb.f_line_height',    'Line Height (px)')) ?>",
    fLineStyle     : "<?= addslashes(__('lpb.f_line_style',     'Line Style')) ?>",
    fBadge         : "<?= addslashes(__('lpb.f_badge',          'Badge Text')) ?>",
    oAlignLeft     : "<?= addslashes(__('lpb.align_left',       'Left')) ?>",
    oAlignCenter   : "<?= addslashes(__('lpb.align_center',     'Center')) ?>",
    oAlignRight    : "<?= addslashes(__('lpb.align_right',      'Right')) ?>",
    oImgLeft       : "<?= addslashes(__('lpb.img_left',         'Left')) ?>",
    oImgRight      : "<?= addslashes(__('lpb.img_right',        'Right')) ?>",
    oDivLine       : "<?= addslashes(__('lpb.div_line',         'Line')) ?>",
    oDivDashed     : "<?= addslashes(__('lpb.div_dashed',       'Dashed')) ?>",
    oDivDotted     : "<?= addslashes(__('lpb.div_dotted',       'Dotted')) ?>",
    elHero         : "<?= addslashes(__('lpb.el_hero',          'Hero Section')) ?>",
    elHeroDesc     : "<?= addslashes(__('lpb.el_hero_desc',     'Image + heading + CTA button')) ?>",
    elImgText      : "<?= addslashes(__('lpb.el_img_text',      'Image + Text')) ?>",
    elImgTextDesc  : "<?= addslashes(__('lpb.el_img_text_desc', 'Side-by-side image and text')) ?>",
    elFeatures     : "<?= addslashes(__('lpb.el_features',      'Features')) ?>",
    elFeaturesDesc : "<?= addslashes(__('lpb.el_features_desc', 'Feature cards grid')) ?>",
    elTestimonials : "<?= addslashes(__('lpb.el_testimonials',  'Testimonials')) ?>",
    elTestimDesc   : "<?= addslashes(__('lpb.el_testim_desc',   'Customer reviews')) ?>",
    elFaq          : "<?= addslashes(__('lpb.el_faq',           'FAQ')) ?>",
    elFaqDesc      : "<?= addslashes(__('lpb.el_faq_desc',      'Collapsible Q&A')) ?>",
    elCountdown    : "<?= addslashes(__('lpb.el_countdown',     'Countdown Timer')) ?>",
    elCountdownDesc: "<?= addslashes(__('lpb.el_countdown_desc','Urgency countdown')) ?>",
    elTrust        : "<?= addslashes(__('lpb.el_trust',         'Trust Badges')) ?>",
    elTrustDesc    : "<?= addslashes(__('lpb.el_trust_desc',    'Credibility badges')) ?>",
    elCta          : "<?= addslashes(__('lpb.el_cta',           'Call To Action')) ?>",
    elCtaDesc      : "<?= addslashes(__('lpb.el_cta_desc',      'Bold CTA section')) ?>",
    elDivider      : "<?= addslashes(__('lpb.el_divider',       'Divider')) ?>",
    elDividerDesc  : "<?= addslashes(__('lpb.el_divider_desc',  'Visual separator')) ?>",
    elCustom       : "<?= addslashes(__('lpb.el_custom',        'Custom HTML')) ?>",
    elCustomDesc   : "<?= addslashes(__('lpb.el_custom_desc',   'Free-form HTML block')) ?>",
    catLayout      : "<?= addslashes(__('lpb.cat_layout',       'Layout')) ?>",
    catContent     : "<?= addslashes(__('lpb.cat_content',      'Content')) ?>",
    catSocial      : "<?= addslashes(__('lpb.cat_social',       'Social Proof')) ?>",
    catConversion  : "<?= addslashes(__('lpb.cat_conversion',   'Conversion')) ?>",
    catAdvanced    : "<?= addslashes(__('lpb.cat_advanced',     'Advanced')) ?>",
    secContent     : "<?= addslashes(__('lpb.sec_content',      'Content')) ?>",
    secStyle       : "<?= addslashes(__('lpb.sec_style',        'Style')) ?>",
    secImage       : "<?= addslashes(__('lpb.sec_image',        'Image')) ?>",
    secHeader      : "<?= addslashes(__('lpb.sec_header',       'Header')) ?>",
    secItems       : "<?= addslashes(__('lpb.sec_items',        'Items')) ?>",
    secBgImage     : "<?= addslashes(__('lpb.sec_bg_image',     'Background Image')) ?>",
    openBtn        : "<?= addslashes(__('lpb.open_btn',         'Open Landing Page Builder')) ?>",
    undoTitle      : "<?= addslashes(__('lpb.undo',            'Undo')) ?>",
    redoTitle      : "<?= addslashes(__('lpb.redo',            'Redo')) ?>" ,

    elHeroDesc2    : "<?= addslashes(__('lpb.el_hero_desc2',     'Full-width hero with CTA')) ?>",
    elImgTextDesc2 : "<?= addslashes(__('lpb.el_img_text_desc2', 'Side-by-side image and text block')) ?>",
    elTestimDesc2  : "<?= addslashes(__('lpb.el_testim_desc2',   'Customer reviews section')) ?>",
    elFaqDesc2     : "<?= addslashes(__('lpb.el_faq_desc2',      'Frequently asked questions')) ?>",
    elCountdown2   : "<?= addslashes(__('lpb.el_countdown_desc2','Urgency countdown section')) ?>",
    elTrustDesc2   : "<?= addslashes(__('lpb.el_trust_desc2',    'Build credibility with badges')) ?>",
    labelHours     : "<?= addslashes(__('lpb.label_hours',     'Hours')) ?>",
    labelMinutes   : "<?= addslashes(__('lpb.label_minutes',   'Minutes')) ?>",
    labelSeconds   : "<?= addslashes(__('lpb.label_seconds',   'Seconds')) ?>",
    secHtml        : "<?= addslashes(__('lpb.sec_html',        'HTML')) ?>",
    warnHtml       : "<?= addslashes(__('lpb.warn_html',       '⚠ Raw HTML — use with care')) ?>",
    unknownType    : "<?= addslashes(__('lpb.unknown_type',    'Unknown section type')) ?>",
    rIcon          : "<?= addslashes(__('lpb.r_icon',          'Icon (emoji)')) ?>",
    rTitle         : "<?= addslashes(__('lpb.r_title',         'Title')) ?>",
    rDesc          : "<?= addslashes(__('lpb.r_desc',          'Description')) ?>",
    rName          : "<?= addslashes(__('lpb.r_name',          'Name')) ?>",
    rRole          : "<?= addslashes(__('lpb.r_role',          'Role / Title')) ?>",
    rStars         : "<?= addslashes(__('lpb.r_stars',         'Stars (1-5)')) ?>",
    rReview        : "<?= addslashes(__('lpb.r_review',        'Review Text')) ?>",
    rQuestion      : "<?= addslashes(__('lpb.r_question',      'Question')) ?>",
    rAnswer        : "<?= addslashes(__('lpb.r_answer',        'Answer')) ?>",
    rBadgeText     : "<?= addslashes(__('lpb.r_badge_text',    'Badge Text')) ?>",
    rSubText       : "<?= addslashes(__('lpb.r_sub_text',      'Sub-text')) ?>",
    rItem          : "<?= addslashes(__('lpb.r_item',          'Item')) ?>",
    /* ── Default content ── */
    dHeroBadge     : "<?= addslashes(__('lpb.d_hero_badge',      'منتج جديد')) ?>",
    dHeroHeading   : "<?= addslashes(__('lpb.d_hero_heading',    'حوّل حياتك اليوم')) ?>",
    dHeroSub       : "<?= addslashes(__('lpb.d_hero_sub',        'اكتشف المنتج الذي يغير كل شيء. جودة عالية وسعر لا يُقاوم.')) ?>",
    dHeroBtn       : "<?= addslashes(__('lpb.d_hero_btn',        'تسوق الآن')) ?>",
    dItHeading     : "<?= addslashes(__('lpb.d_it_heading',      'لماذا تختارنا')) ?>",
    dItText        : "<?= addslashes(__('lpb.d_it_text',         'نقدم أعلى جودة مع خدمة عملاء لا مثيل لها وتوصيل سريع.')) ?>",
    dItBtn         : "<?= addslashes(__('lpb.d_it_btn',          'اعرف المزيد')) ?>",
    dFeatHeading   : "<?= addslashes(__('lpb.d_feat_heading',    'لماذا تختارنا')) ?>",
    dFeatSub       : "<?= addslashes(__('lpb.d_feat_sub',        'كل ما تحتاجه في مكان واحد')) ?>",
    dFeat1Title    : "<?= addslashes(__('lpb.d_feat1_title',     'توصيل سريع')) ?>",
    dFeat1Desc     : "<?= addslashes(__('lpb.d_feat1_desc',      'نوصل طلبك خلال 24 ساعة مضمونة.')) ?>",
    dFeat2Title    : "<?= addslashes(__('lpb.d_feat2_title',     'دفع آمن')) ?>",
    dFeat2Desc     : "<?= addslashes(__('lpb.d_feat2_desc',      '100% آمن ومشفر.')) ?>",
    dFeat3Title    : "<?= addslashes(__('lpb.d_feat3_title',     'جودة مضمونة')) ?>",
    dFeat3Desc     : "<?= addslashes(__('lpb.d_feat3_desc',      'مواد فاخرة مصنوعة لتدوم.')) ?>",
    dFeat4Title    : "<?= addslashes(__('lpb.d_feat4_title',     'إرجاع مجاني')) ?>",
    dFeat4Desc     : "<?= addslashes(__('lpb.d_feat4_desc',      'سياسة إرجاع سهلة خلال 30 يوماً.')) ?>",
    dTestimHeading : "<?= addslashes(__('lpb.d_testim_heading',  'ماذا يقول عملاؤنا')) ?>",
    dTestimSub     : "<?= addslashes(__('lpb.d_testim_sub',      'موثوق من آلاف العملاء السعداء')) ?>",
    dTestimRole1   : "<?= addslashes(__('lpb.d_testim_role1',    'مشترٍ موثق')) ?>",
    dTestimRole2   : "<?= addslashes(__('lpb.d_testim_role2',    'عميل')) ?>",
    dTestim1Text   : "<?= addslashes(__('lpb.d_testim1_text',    'أحببت هذا المنتج كثيراً! غيّر حياتي تماماً.')) ?>",
    dTestim2Text   : "<?= addslashes(__('lpb.d_testim2_text',    'أفضل شراء قمت به هذا العام. الشحن سريع أيضاً!')) ?>",
    dTestim3Text   : "<?= addslashes(__('lpb.d_testim3_text',    'جودة ممتازة تماماً كما وُصف. سأشتري مجدداً!')) ?>",
    dFaqHeading    : "<?= addslashes(__('lpb.d_faq_heading',     'الأسئلة الشائعة')) ?>",
    dFaqSub        : "<?= addslashes(__('lpb.d_faq_sub',         'كل ما تحتاج معرفته')) ?>",
    dFaq1Q         : "<?= addslashes(__('lpb.d_faq1_q',          'كم يستغرق الشحن؟')) ?>",
    dFaq1A         : "<?= addslashes(__('lpb.d_faq1_a',          'يستغرق الشحن العادي 3-5 أيام. التوصيل السريع خلال 24 ساعة.')) ?>",
    dFaq2Q         : "<?= addslashes(__('lpb.d_faq2_q',          'هل يمكنني إرجاع المنتج؟')) ?>",
    dFaq2A         : "<?= addslashes(__('lpb.d_faq2_a',          'نعم، سياسة إرجاع سهلة خلال 30 يوماً بلا أسئلة.')) ?>",
    dFaq3Q         : "<?= addslashes(__('lpb.d_faq3_q',          'هل الدفع آمن؟')) ?>",
    dFaq3A         : "<?= addslashes(__('lpb.d_faq3_a',          'نعم، نستخدم تشفير SSL 256-bit لجميع المعاملات.')) ?>",
    dCntHeading    : "<?= addslashes(__('lpb.d_cnt_heading',     '⚡ عرض محدود المدة!')) ?>",
    dCntSub        : "<?= addslashes(__('lpb.d_cnt_sub',         'هذا العرض ينتهي قريباً. لا تفوت الفرصة!')) ?>",
    dTrustHeading  : "<?= addslashes(__('lpb.d_trust_heading',   'أنت في أيدٍ أمينة')) ?>",
    dTrust1Text    : "<?= addslashes(__('lpb.d_trust1_text',     'دفع آمن')) ?>",
    dTrust1Sub     : "<?= addslashes(__('lpb.d_trust1_sub',      'مشفر بـ SSL')) ?>",
    dTrust2Text    : "<?= addslashes(__('lpb.d_trust2_text',     'بائع موثق')) ?>",
    dTrust2Sub     : "<?= addslashes(__('lpb.d_trust2_sub',      '+1000 طلب')) ?>",
    dTrust3Text    : "<?= addslashes(__('lpb.d_trust3_text',     'توصيل سريع')) ?>",
    dTrust3Sub     : "<?= addslashes(__('lpb.d_trust3_sub',      '24-48 ساعة')) ?>",
    dTrust4Text    : "<?= addslashes(__('lpb.d_trust4_text',     'إرجاع سهل')) ?>",
    dTrust4Sub     : "<?= addslashes(__('lpb.d_trust4_sub',      'سياسة 30 يوم')) ?>",
    dTrust5Text    : "<?= addslashes(__('lpb.d_trust5_text',     'دعم 24/7')) ?>",
    dTrust5Sub     : "<?= addslashes(__('lpb.d_trust5_sub',      'دائماً هنا')) ?>",
    dCtaHeading    : "<?= addslashes(__('lpb.d_cta_heading',     'هل أنت مستعد للبدء؟')) ?>",
    dCtaSub        : "<?= addslashes(__('lpb.d_cta_sub',         'انضم لآلاف العملاء الراضين اليوم.')) ?>",
    dCtaBtn        : "<?= addslashes(__('lpb.d_cta_btn',         'اطلب الآن')) ?>",
    dCustomHtml    : "<?= addslashes(__('lpb.d_custom_html',     '<div style=\'padding:40px;text-align:center\'><h3>كتلة مخصصة</h3><p>عدّل هذه الكتلة بـ HTML الخاص بك</p></div>')) ?>" 
};
</script>
<script>
(function () {
'use strict';

/* ─────────────────────────────────────────────────
   ELEMENT DEFINITIONS
───────────────────────────────────────────────── */
const ELEMENTS = [
  {
    type: 'hero', category: lpbI18n.catLayout, icon: '🖼',
    name: lpbI18n.elHero, desc: lpbI18n.elHeroDesc2,
    get defaults() { return {
      badge: lpbI18n.dHeroBadge, badge_bg: '#4f7eff', badge_color: '#ffffff',
      heading: lpbI18n.dHeroHeading, subheading: lpbI18n.dHeroSub,
      btn_text: lpbI18n.dHeroBtn, btn_url: '#', btn_bg: '#4f7eff', btn_color: '#ffffff',
      bg_color: '#1a1a2e', text_color: '#ffffff', overlay_color: '#00000066',
      bg_image: '', align: 'left', min_height: '480'
    }}
  },
  {
    type: 'image_text', category: lpbI18n.catLayout, icon: '🖼',
    name: lpbI18n.elImgText, desc: lpbI18n.elImgTextDesc2,
    get defaults() { return {
      image: '', heading: lpbI18n.dItHeading, text: lpbI18n.dItText,
      btn_text: lpbI18n.dItBtn, btn_url: '#', btn_bg: '#4f7eff', btn_color: '#fff',
      img_position: 'left', bg_color: '#ffffff', text_color: '#1f2937'
    }}
  },
  {
    type: 'features', category: lpbI18n.catContent, icon: '✨',
    name: lpbI18n.elFeatures, desc: lpbI18n.elFeaturesDesc,
    get defaults() { return {
      heading: lpbI18n.dFeatHeading, subheading: lpbI18n.dFeatSub,
      bg_color: '#f9fafb', text_color: '#1f2937',
      items: [
        { icon: '🚀', title: lpbI18n.dFeat1Title, desc: lpbI18n.dFeat1Desc },
        { icon: '🔒', title: lpbI18n.dFeat2Title, desc: lpbI18n.dFeat2Desc },
        { icon: '💯', title: lpbI18n.dFeat3Title, desc: lpbI18n.dFeat3Desc },
        { icon: '🎁', title: lpbI18n.dFeat4Title, desc: lpbI18n.dFeat4Desc }
      ]
    }}
  },
  {
    type: 'testimonials', category: lpbI18n.catSocial, icon: '⭐',
    name: lpbI18n.elTestimonials, desc: lpbI18n.elTestimDesc2,
    get defaults() { return {
      heading: lpbI18n.dTestimHeading, subheading: lpbI18n.dTestimSub,
      bg_color: '#ffffff', text_color: '#1f2937',
      items: [
        { name: 'Sarah M.', role: lpbI18n.dTestimRole1, stars: 5, text: lpbI18n.dTestim1Text },
        { name: 'Ahmed K.', role: lpbI18n.dTestimRole2, stars: 5, text: lpbI18n.dTestim2Text },
        { name: 'Maria L.', role: lpbI18n.dTestimRole1, stars: 5, text: lpbI18n.dTestim3Text }
      ]
    }}
  },
  {
    type: 'faq', category: lpbI18n.catContent, icon: '❓',
    name: lpbI18n.elFaq, desc: lpbI18n.elFaqDesc2,
    get defaults() { return {
      heading: lpbI18n.dFaqHeading, subheading: lpbI18n.dFaqSub,
      bg_color: '#f9fafb', text_color: '#1f2937',
      items: [
        { q: lpbI18n.dFaq1Q, a: lpbI18n.dFaq1A },
        { q: lpbI18n.dFaq2Q, a: lpbI18n.dFaq2A },
        { q: lpbI18n.dFaq3Q, a: lpbI18n.dFaq3A }
      ]
    }}
  },
  {
    type: 'countdown', category: lpbI18n.catConversion, icon: '⏰',
    name: lpbI18n.elCountdown, desc: lpbI18n.elCountdown2,
    get defaults() { return {
      heading: lpbI18n.dCntHeading, subheading: lpbI18n.dCntSub,
      bg_color: '#1a1a2e', text_color: '#ffffff', timer_bg: '#2d2d4e', timer_color: '#ffffff',
      accent: '#4f7eff', hours: 24, minutes: 0, seconds: 0
    }}
  },
  {
    type: 'trust', category: lpbI18n.catConversion, icon: '🛡',
    name: lpbI18n.elTrust, desc: lpbI18n.elTrustDesc2,
    get defaults() { return {
      heading: lpbI18n.dTrustHeading,
      bg_color: '#ffffff', text_color: '#1f2937',
      items: [
        { icon: '🔒', text: lpbI18n.dTrust1Text, sub: lpbI18n.dTrust1Sub },
        { icon: '✅', text: lpbI18n.dTrust2Text, sub: lpbI18n.dTrust2Sub },
        { icon: '🚚', text: lpbI18n.dTrust3Text, sub: lpbI18n.dTrust3Sub },
        { icon: '↩',  text: lpbI18n.dTrust4Text, sub: lpbI18n.dTrust4Sub },
        { icon: '💬', text: lpbI18n.dTrust5Text, sub: lpbI18n.dTrust5Sub }
      ]
    }}
  },
  {
    type: 'cta', category: lpbI18n.catConversion, icon: '🎯',
    name: lpbI18n.elCta, desc: lpbI18n.elCtaDesc,
    get defaults() { return {
      heading: lpbI18n.dCtaHeading, subheading: lpbI18n.dCtaSub,
      btn_text: lpbI18n.dCtaBtn, btn_url: '#', btn_bg: '#ffffff', btn_color: '#4f7eff',
      bg_color: '#4f7eff', text_color: '#ffffff'
    }}
  },
  {
    type: 'divider', category: lpbI18n.catLayout, icon: '➖',
    name: lpbI18n.elDivider, desc: lpbI18n.elDividerDesc,
    defaults: { style: 'line', color: '#e5e7eb', height: '2', bg_color: '#ffffff' }
  },
  {
    type: 'custom', category: lpbI18n.catAdvanced, icon: '🛠',
    name: lpbI18n.elCustom, desc: lpbI18n.elCustomDesc,
    get defaults() { return { html: lpbI18n.dCustomHtml, bg_color: '#ffffff' }}
  }
];

/* ─────────────────────────────────────────────────
   STATE
───────────────────────────────────────────────── */
let state = {
  sections: [],
  selected: null
};
let history = [];
let historyIndex = -1;
let dragSrcType  = null;
let dragSrcIndex = null; // null = from sidebar, number = from canvas
let openRepeaterItems = {};

/* ─────────────────────────────────────────────────
   DOM REFS
───────────────────────────────────────────────── */
const root         = document.getElementById('lpb-root');
const openBtn      = document.getElementById('lpb-open-btn');
const saveBtn      = document.getElementById('lpb-save-btn');
const closeBtn     = document.getElementById('lpb-close-btn');
const clearBtn     = document.getElementById('lpb-clear-btn');
const undoBtn      = document.getElementById('lpb-undo-btn');
const redoBtn      = document.getElementById('lpb-redo-btn');
const canvasFrame  = document.getElementById('lpb-canvas-frame');
const sectionsList = document.getElementById('lpb-sections-list');
const emptyState   = document.getElementById('lpb-empty-state');
const elemList     = document.getElementById('lpb-elements-list');
const searchInput  = document.getElementById('lpb-sidebar-search');
const propsContent = document.getElementById('lpb-props-content');
const noSelection  = document.getElementById('lpb-no-selection');
const propsTitle   = document.getElementById('lpb-props-title');
const propsTypeBadge = document.getElementById('lpb-props-type-badge');
const layoutInput  = document.getElementById('layoutInput');
const statSections = document.getElementById('lpb-stat-sections');
const statType     = document.getElementById('lpb-stat-type');
const statStatus   = document.getElementById('lpb-stat-status-badge');

/* ─────────────────────────────────────────────────
   HISTORY
───────────────────────────────────────────────── */
function pushHistory() {
  history = history.slice(0, historyIndex + 1);
  history.push(JSON.stringify(state.sections));
  if (history.length > 50) history.shift();
  historyIndex = history.length - 1;
  syncUndoRedo();
}
function undo() {
  if (historyIndex <= 0) return;
  historyIndex--;
  state.sections = JSON.parse(history[historyIndex]);
  state.selected  = null;
  render(); syncUndoRedo();
}
function redo() {
  if (historyIndex >= history.length - 1) return;
  historyIndex++;
  state.sections = JSON.parse(history[historyIndex]);
  state.selected  = null;
  render(); syncUndoRedo();
}
function syncUndoRedo() {
  undoBtn.disabled = historyIndex <= 0;
  redoBtn.disabled = historyIndex >= history.length - 1;
}

/* ─────────────────────────────────────────────────
   UNIQUE ID
───────────────────────────────────────────────── */
function uid() { return 'lpb_' + Date.now().toString(36) + Math.random().toString(36).slice(2,6); }

/* ─────────────────────────────────────────────────
   RENDER SIDEBAR ELEMENTS
───────────────────────────────────────────────── */
function renderSidebar(filter = '') {
  const q = filter.toLowerCase();
  const categories = {};
  ELEMENTS.forEach(el => {
    if (q && !el.name.toLowerCase().includes(q) && !el.desc.toLowerCase().includes(q)) return;
    if (!categories[el.category]) categories[el.category] = [];
    categories[el.category].push(el);
  });
  elemList.innerHTML = '';
  Object.entries(categories).forEach(([cat, items]) => {
    const label = document.createElement('div');
    label.className = 'lpb-category-label';
    label.textContent = cat;
    elemList.appendChild(label);
    items.forEach(el => {
      const card = document.createElement('div');
      card.className = 'lpb-element-card';
      card.draggable = true;
      card.dataset.type = el.type;
      card.innerHTML = `
        <div class="lpb-element-icon">${el.icon}</div>
        <div class="lpb-element-info">
          <div class="lpb-element-name">${el.name}</div>
          <div class="lpb-element-desc">${el.desc}</div>
        </div>
      `;
      card.addEventListener('dragstart', e => {
        dragSrcType  = el.type;
        dragSrcIndex = null;
        e.dataTransfer.effectAllowed = 'copy';
      });
      card.addEventListener('click', () => {
        addSection(el.type, state.sections.length);
      });
      elemList.appendChild(card);
    });
  });
}

/* ─────────────────────────────────────────────────
   ADD / MOVE / DELETE SECTION
───────────────────────────────────────────────── */
function addSection(type, atIndex) {
  const def = ELEMENTS.find(e => e.type === type);
  if (!def) return;
  const section = { id: uid(), type, settings: JSON.parse(JSON.stringify(def.defaults)) };
  state.sections.splice(atIndex, 0, section);
  state.selected = section.id;
  pushHistory();
  render();
  updateStats(type);
  setTimeout(() => {
    const el = document.querySelector(`[data-section-id="${section.id}"]`);
    if (el) el.scrollIntoView({ behavior: 'smooth', block: 'center' });
  }, 80);
}
function deleteSection(id) {
  state.sections = state.sections.filter(s => s.id !== id);
  if (state.selected === id) state.selected = null;
  pushHistory();
  render();
}
function moveSection(id, dir) {
  const idx = state.sections.findIndex(s => s.id === id);
  if (idx === -1) return;
  const newIdx = idx + dir;
  if (newIdx < 0 || newIdx >= state.sections.length) return;
  const tmp = state.sections[idx];
  state.sections[idx] = state.sections[newIdx];
  state.sections[newIdx] = tmp;
  pushHistory(); render();
}
function duplicateSection(id) {
  const idx = state.sections.findIndex(s => s.id === id);
  if (idx === -1) return;
  const orig = state.sections[idx];
  const copy = { id: uid(), type: orig.type, settings: JSON.parse(JSON.stringify(orig.settings)) };
  state.sections.splice(idx + 1, 0, copy);
  state.selected = copy.id;
  pushHistory(); render();
}

/* ─────────────────────────────────────────────────
   RENDER CANVAS
───────────────────────────────────────────────── */
function render() {
  sectionsList.innerHTML = '';
  emptyState.classList.toggle('lpb-hidden', state.sections.length > 0);

  state.sections.forEach((section, idx) => {
    // Drop zone before
    sectionsList.appendChild(makeDropZone(idx));
    // Section wrapper
    const wrapper = document.createElement('div');
    wrapper.className = 'lpb-section-wrapper';
    wrapper.dataset.sectionId = section.id;
    if (state.selected === section.id) wrapper.classList.add('lpb-selected');

    // Type badge
    const badge = document.createElement('div');
    badge.className = 'lpb-section-type-badge';
    badge.textContent = (ELEMENTS.find(e => e.type === section.type)?.name || section.type).toUpperCase();
    wrapper.appendChild(badge);

    // Controls bar
    const controls = document.createElement('div');
    controls.className = 'lpb-section-controls';
    controls.innerHTML = `
      <span class="lpb-drag-handle" title="Drag to reorder">⠿</span>
      <button class="lpb-sc-btn" data-action="up" title="Move Up">↑</button>
      <button class="lpb-sc-btn" data-action="down" title="Move Down">↓</button>
      <button class="lpb-sc-btn" data-action="dup" title="Duplicate">⧉</button>
      <button class="lpb-sc-btn danger" data-action="del" title="Delete">✕</button>
    `;
    controls.addEventListener('click', e => {
      const action = e.target.closest('[data-action]')?.dataset.action;
      if (!action) return;
      e.stopPropagation();
      if (action === 'del') deleteSection(section.id);
      else if (action === 'up')  moveSection(section.id, -1);
      else if (action === 'down')moveSection(section.id,  1);
      else if (action === 'dup') duplicateSection(section.id);
    });
    wrapper.appendChild(controls);

    // Rendered HTML
    const inner = document.createElement('div');
    inner.innerHTML = renderSection(section);
    wrapper.appendChild(inner);

    // FAQ interactivity
    if (section.type === 'faq') {
      inner.querySelectorAll('.lpb-faq-question').forEach(q => {
        q.addEventListener('click', () => q.closest('.lpb-faq-item').classList.toggle('open'));
      });
    }

    // Select on click
    wrapper.addEventListener('click', e => {
      if (e.target.closest('.lpb-section-controls')) return;
      selectSection(section.id);
    });

    // Drag-to-reorder (canvas items)
    wrapper.draggable = true;
    wrapper.addEventListener('dragstart', e => {
      dragSrcType  = section.type;
      dragSrcIndex = idx;
      wrapper.classList.add('lpb-dragging');
      e.dataTransfer.effectAllowed = 'move';
    });
    wrapper.addEventListener('dragend', () => wrapper.classList.remove('lpb-dragging'));

    sectionsList.appendChild(wrapper);
  });

  // Final drop zone
  sectionsList.appendChild(makeDropZone(state.sections.length));

  // Sync props panel
  if (state.selected) {
    const sec = state.sections.find(s => s.id === state.selected);
    if (sec) renderProps(sec); else clearProps();
  } else clearProps();

  // Stats
  statSections.textContent = state.sections.length;
  syncLayout();
}

function makeDropZone(index) {
  const dz = document.createElement('div');
  dz.className = 'lpb-drop-zone';
  dz.dataset.index = index;
  dz.addEventListener('dragover', e => { e.preventDefault(); dz.classList.add('drag-over'); });
  dz.addEventListener('dragleave', () => dz.classList.remove('drag-over'));
  dz.addEventListener('drop', e => {
    e.preventDefault();
    dz.classList.remove('drag-over');
    const dropAt = parseInt(dz.dataset.index);
    if (dragSrcIndex !== null) {
      // reorder canvas item
      if (dragSrcIndex === dropAt || dragSrcIndex === dropAt - 1) return;
      const [moved] = state.sections.splice(dragSrcIndex, 1);
      const insertAt = dropAt > dragSrcIndex ? dropAt - 1 : dropAt;
      state.sections.splice(insertAt, 0, moved);
      dragSrcIndex = null;
      pushHistory(); render();
    } else if (dragSrcType) {
      addSection(dragSrcType, dropAt);
      dragSrcType = null;
    }
  });
  return dz;
}

/* ─────────────────────────────────────────────────
   SECTION RENDERERS
───────────────────────────────────────────────── */
function renderSection(sec) {
  const s = sec.settings;
  switch (sec.type) {

    case 'hero': return `
      <div class="lpb-render-hero" style="background-color:${s.bg_color||'#1a1a2e'}; min-height:${s.min_height||480}px;">
        ${s.bg_image ? `<div class="lpb-hero-bg" style="background-image:url('${esc(s.bg_image)}')"></div>` : ''}
        <div class="lpb-hero-overlay" style="background:${s.overlay_color||'transparent'}"></div>
        <div class="lpb-hero-content" style="text-align:${s.align||'left'}; margin:${s.align==='center'?'0 auto':'0'};">
          ${s.badge ? `<span class="lpb-hero-badge" style="background:${s.badge_bg||'#4f7eff'};color:${s.badge_color||'#fff'}">${esc(s.badge)}</span>` : ''}
          <h1 style="color:${s.text_color||'#fff'}">${esc(s.heading||'')}</h1>
          ${s.subheading ? `<p style="color:${s.text_color||'#fff'}">${esc(s.subheading)}</p>` : ''}
          ${s.btn_text ? `<button class="lpb-hero-btn" style="background:${s.btn_bg||'#4f7eff'};color:${s.btn_color||'#fff'}">${esc(s.btn_text)}</button>` : ''}
        </div>
      </div>`;

    case 'image_text': return `
      <div class="lpb-render-image-text ${s.img_position==='right'?'img-right':''}" style="background:${s.bg_color||'#fff'}">
        <div class="lpb-img-col" style="background-image:url('${esc(s.image||'')}'); background-color:#e5e7eb; ${!s.image?'display:flex;align-items:center;justify-content:center;font-size:48px;':''}">${!s.image?'🖼':''}</div>
        <div class="lpb-text-col">
          <h2 style="color:${s.text_color||'#1f2937'}">${esc(s.heading||'')}</h2>
          <p style="color:${s.text_color||'#1f2937'}">${esc(s.text||'')}</p>
          ${s.btn_text ? `<button class="lpb-it-btn" style="background:${s.btn_bg||'#4f7eff'};color:${s.btn_color||'#fff'}">${esc(s.btn_text)}</button>` : ''}
        </div>
      </div>`;

    case 'features': {
      const items = (s.items||[]).map(it => `
        <div class="lpb-feature-item">
          <span class="lpb-feature-icon">${esc(it.icon||'✨')}</span>
          <h3>${esc(it.title||'')}</h3>
          <p>${esc(it.desc||'')}</p>
        </div>`).join('');
      return `
        <div class="lpb-render-features" style="background:${s.bg_color||'#f9fafb'}">
          <h2 style="color:${s.text_color||'#1f2937'}">${esc(s.heading||'')}</h2>
          ${s.subheading?`<p class="lpb-subtitle">${esc(s.subheading)}</p>`:''}
          <div class="lpb-features-grid">${items}</div>
        </div>`; }

    case 'testimonials': {
      const items = (s.items||[]).map(it => {
        const stars = '⭐'.repeat(Math.min(5, it.stars||5));
        const initials = (it.name||'?').split(' ').map(w=>w[0]).join('').slice(0,2).toUpperCase();
        return `
          <div class="lpb-testimonial-card">
            <div class="lpb-testimonial-stars">${stars}</div>
            <p class="lpb-testimonial-text">"${esc(it.text||'')}"</p>
            <div class="lpb-testimonial-author">
              <div class="lpb-testimonial-avatar">${initials}</div>
              <div>
                <div class="lpb-testimonial-name">${esc(it.name||'')}</div>
                <div class="lpb-testimonial-role">${esc(it.role||'')}</div>
              </div>
            </div>
          </div>`;
      }).join('');
      return `
        <div class="lpb-render-testimonials" style="background:${s.bg_color||'#fff'}">
          <h2 style="color:${s.text_color||'#1f2937'}">${esc(s.heading||'')}</h2>
          ${s.subheading?`<p class="lpb-subtitle">${esc(s.subheading)}</p>`:''}
          <div class="lpb-testimonials-grid">${items}</div>
        </div>`; }

    case 'faq': {
      const items = (s.items||[]).map(it => `
        <div class="lpb-faq-item">
          <div class="lpb-faq-question">
            <span>${esc(it.q||'')}</span>
            <span class="lpb-faq-icon">+</span>
          </div>
          <div class="lpb-faq-answer">${esc(it.a||'')}</div>
        </div>`).join('');
      return `
        <div class="lpb-render-faq" style="background:${s.bg_color||'#f9fafb'};max-width:100%">
          <h2 style="color:${s.text_color||'#1f2937'}">${esc(s.heading||'')}</h2>
          ${s.subheading?`<p class="lpb-subtitle">${esc(s.subheading)}</p>`:''}
          ${items}
        </div>`; }

    case 'countdown': {
      return `
        <div class="lpb-render-countdown" style="background:${s.bg_color||'#1a1a2e'}">
          <h2 style="color:${s.text_color||'#fff'}">${esc(s.heading||'')}</h2>
          <p style="color:${s.text_color||'#fff'}">${esc(s.subheading||'')}</p>
          <div class="lpb-countdown-timer">
            ${[['00','Hours'],['00','Minutes'],['00','Seconds']].map(([n,l]) => `
              <div class="lpb-countdown-unit" style="background:${s.timer_bg||'#2d2d4e'}">
                <span class="lpb-number" style="color:${s.timer_color||'#fff'}">${n}</span>
                <span class="lpb-label" style="color:${s.timer_color||'#fff'}">${l}</span>
              </div>`).join('')}
          </div>
        </div>`; }

    case 'trust': {
      const items = (s.items||[]).map(it => `
        <div class="lpb-trust-badge-item">
          <span class="lpb-trust-badge-icon">${esc(it.icon||'✅')}</span>
          <span class="lpb-trust-badge-text">${esc(it.text||'')}</span>
          ${it.sub?`<span class="lpb-trust-badge-sub">${esc(it.sub)}</span>`:''}
        </div>`).join('');
      return `
        <div class="lpb-render-trust" style="background:${s.bg_color||'#fff'}">
          ${s.heading?`<h2 style="color:${s.text_color||'#1f2937'}">${esc(s.heading)}</h2>`:''}
          <div class="lpb-trust-grid">${items}</div>
        </div>`; }

    case 'cta': return `
      <div class="lpb-render-cta" style="background:${s.bg_color||'#4f7eff'}">
        <h2 style="color:${s.text_color||'#fff'}">${esc(s.heading||'')}</h2>
        <p style="color:${s.text_color||'#fff'}">${esc(s.subheading||'')}</p>
        ${s.btn_text?`<button class="lpb-render-cta .lpb-cta-btn" style="background:${s.btn_bg||'#fff'};color:${s.btn_color||'#4f7eff'};border-radius:8px;font-size:17px;font-weight:700;padding:16px 40px;border:none;cursor:pointer">${esc(s.btn_text)}</button>`:''}
      </div>`;

    case 'divider': return `
      <div class="lpb-render-divider" style="background:${s.bg_color||'#fff'}">
        <hr style="border-top:${s.height||2}px solid ${s.color||'#e5e7eb'}; opacity:1">
      </div>`;

    case 'custom': return `
      <div class="lpb-render-custom" style="background:${s.bg_color||'#fff'}">${s.html||''}</div>`;

    default: return `<div style="padding:20px;color:#999">Unknown section type: ${sec.type}</div>`;
  }
}

function esc(str) {
  return String(str||'').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}

/* ─────────────────────────────────────────────────
   PROPERTIES PANEL
───────────────────────────────────────────────── */
function selectSection(id) {
  state.selected = id;
  const sec = state.sections.find(s => s.id === id);
  if (!sec) return;
  // Update selected class on wrappers
  document.querySelectorAll('.lpb-section-wrapper').forEach(w => {
    w.classList.toggle('lpb-selected', w.dataset.sectionId === id);
  });
  renderProps(sec);
}

function clearProps() {
  propsContent.style.display = 'none';
  noSelection.style.display  = '';
  propsTitle.textContent = lpbI18n.propsTitle;
  propsTypeBadge.style.display = 'none';
}

function renderProps(sec) {
  noSelection.style.display  = 'none';
  propsContent.style.display = 'block';
  const def = ELEMENTS.find(e => e.type === sec.type);
  propsTitle.textContent = def?.name || sec.type;
  propsTypeBadge.textContent = sec.type.toUpperCase();
  propsTypeBadge.style.display = '';
  propsContent.innerHTML = buildPropsForm(sec);
  bindPropsEvents(sec);
}

function buildPropsForm(sec) {
  const s = sec.settings;
  const field = (key, label, type='text', extra='') =>
    `<div class="lpb-field"><label>${label}</label><input type="${type}" data-key="${key}" value="${esc(s[key]||'')}" ${extra}></div>`;
  const textarea = (key, label, rows=3) =>
    `<div class="lpb-field"><label>${label}</label><textarea data-key="${key}" rows="${rows}">${esc(s[key]||'')}</textarea></div>`;
  const colorField = (key, label) =>
    `<div class="lpb-field"><label>${label}</label><input type="color" data-key="${key}" value="${s[key]||'#ffffff'}"></div>`;
  const selectField = (key, label, options) =>
    `<div class="lpb-field"><label>${label}</label><select data-key="${key}">${options.map(([v,l]) => `<option value="${v}" ${s[key]===v?'selected':''}>${l}</option>`).join('')}</select></div>`;
  const section = label => `<div class="lpb-props-section-label">${label}</div>`;
  const hr = () => `<hr class="lpb-section-divider">`;

  switch (sec.type) {

    case 'hero': return `
      ${section(lpbI18n.secContent)}
      ${field('badge','Badge Text')}
      ${field('heading',lpbI18n.fHeading)}
      ${textarea('subheading','Subheading')}
      ${field('btn_text',lpbI18n.fBtnText)}
      ${field('btn_url',lpbI18n.fBtnUrl,'text')}
      ${hr()}${section(lpbI18n.secStyle)}
      <div class="lpb-field-row">
        ${colorField('bg_color',lpbI18n.fBgColor)}
        ${colorField('text_color',lpbI18n.fTextColor)}
      </div>
      <div class="lpb-field-row">
        ${colorField('btn_bg',lpbI18n.fBtnBg)}
        ${colorField('btn_color',lpbI18n.fBtnColor)}
      </div>
      <div class="lpb-field-row">
        ${colorField('badge_bg',lpbI18n.fBadgeBg)}
        ${colorField('badge_color',lpbI18n.fBadgeColor)}
      </div>
      ${selectField('align',lpbI18n.fAlign,[['left',lpbI18n.oAlignLeft],['center',lpbI18n.oAlignCenter],['right',lpbI18n.oAlignRight]])}
      ${field('min_height',lpbI18n.fMinHeight,'number')}
      ${field('overlay_color',lpbI18n.fOverlay,'text','placeholder="#00000066"')}
      ${hr()}${section(lpbI18n.secBgImage)}
      ${field('bg_image',lpbI18n.fBgImage,'text')}`;

    case 'image_text': return `
      ${section(lpbI18n.secContent)}
      ${field('heading',lpbI18n.fHeading)}
      ${textarea('text','Text')}
      ${field('btn_text',lpbI18n.fBtnText)}
      ${field('btn_url',lpbI18n.fBtnUrl,'text')}
      ${hr()}${section(lpbI18n.secImage)}
      ${field('image',lpbI18n.fImage,'text')}
      ${selectField('img_position',lpbI18n.fImgPos,[['left',lpbI18n.oImgLeft],['right',lpbI18n.oImgRight]])}
      ${hr()}${section(lpbI18n.secStyle)}
      <div class="lpb-field-row">
        ${colorField('bg_color',lpbI18n.fBgColor)}
        ${colorField('text_color',lpbI18n.fTextColor)}
      </div>
      <div class="lpb-field-row">
        ${colorField('btn_bg',lpbI18n.fBtnBg)}
        ${colorField('btn_color',lpbI18n.fBtnColor)}
      </div>`;

    case 'features': return `
      ${section(lpbI18n.secHeader)}
      ${field('heading',lpbI18n.fHeading)}
      ${field('subheading',lpbI18n.fSubheading)}
      <div class="lpb-field-row">
        ${colorField('bg_color',lpbI18n.fBgColor)}
        ${colorField('text_color',lpbI18n.fTextColor)}
      </div>
      ${hr()}${section(lpbI18n.secItems)}
      ${buildRepeater(sec, 'items', ['icon','title','desc'], ['Icon (emoji)','Title','Description'])}`;

    case 'testimonials': return `
      ${section(lpbI18n.secHeader)}
      ${field('heading',lpbI18n.fHeading)}
      ${field('subheading',lpbI18n.fSubheading)}
      <div class="lpb-field-row">
        ${colorField('bg_color',lpbI18n.fBgColor)}
        ${colorField('text_color',lpbI18n.fTextColor)}
      </div>
      ${hr()}${section(lpbI18n.secItems)}
      ${buildRepeater(sec, 'items', ['name','role','stars','text'], ['Name','Role / Title','Stars (1-5)','Review Text'])}`;

    case 'faq': return `
      ${section(lpbI18n.secHeader)}
      ${field('heading',lpbI18n.fHeading)}
      ${field('subheading',lpbI18n.fSubheading)}
      <div class="lpb-field-row">
        ${colorField('bg_color',lpbI18n.fBgColor)}
        ${colorField('text_color',lpbI18n.fTextColor)}
      </div>
      ${hr()}${section(lpbI18n.secItems)}
      ${buildRepeater(sec, 'items', ['q','a'], ['Question','Answer'])}`;

    case 'countdown': return `
      ${section(lpbI18n.secContent)}
      ${field('heading',lpbI18n.fHeading)}
      ${textarea('subheading','Subheading',2)}
      ${hr()}${section(lpbI18n.secStyle)}
      <div class="lpb-field-row">
        ${colorField('bg_color',lpbI18n.fBgColor)}
        ${colorField('text_color',lpbI18n.fTextColor)}
      </div>
      <div class="lpb-field-row">
        ${colorField('timer_bg',lpbI18n.fTimerBg)}
        ${colorField('timer_color',lpbI18n.fTimerColor)}
      </div>`;

    case 'trust': return `
      ${section(lpbI18n.secHeader)}
      ${field('heading',lpbI18n.fHeading)}
      <div class="lpb-field-row">
        ${colorField('bg_color',lpbI18n.fBgColor)}
        ${colorField('text_color',lpbI18n.fTextColor)}
      </div>
      ${hr()}${section(lpbI18n.secItems)}
      ${buildRepeater(sec, 'items', ['icon','text','sub'], ['Icon (emoji)','Badge Text','Sub-text'])}`;

    case 'cta': return `
      ${section(lpbI18n.secContent)}
      ${field('heading',lpbI18n.fHeading)}
      ${textarea('subheading','Subheading',2)}
      ${field('btn_text',lpbI18n.fBtnText)}
      ${field('btn_url',lpbI18n.fBtnUrl,'text')}
      ${hr()}${section(lpbI18n.secStyle)}
      <div class="lpb-field-row">
        ${colorField('bg_color',lpbI18n.fBgColor)}
        ${colorField('text_color',lpbI18n.fTextColor)}
      </div>
      <div class="lpb-field-row">
        ${colorField('btn_bg',lpbI18n.fBtnBg)}
        ${colorField('btn_color',lpbI18n.fBtnColor)}
      </div>`;

    case 'divider': return `
      ${colorField('bg_color',lpbI18n.fBgColor)}
      ${colorField('color',lpbI18n.fLineColor)}
      ${field('height',lpbI18n.fLineHeight,'number')}
      ${selectField('style',lpbI18n.fLineStyle,[['line',lpbI18n.oDivLine],['dashed',lpbI18n.oDivDashed],['dotted',lpbI18n.oDivDotted]])}`;

    case 'custom': return `
      ${colorField('bg_color',lpbI18n.fBgColor)}
      ${hr()}${section('HTML')}
      <div class="lpb-field"><label>Custom HTML</label><textarea data-key="html" rows="10">${esc(s.html||'')}</textarea></div>
      <small style="color:var(--lpb-warn);font-size:11px">⚠ Raw HTML — use with care</small>`;

    default: return '<p style="color:var(--lpb-muted);font-size:13px">No properties available.</p>';
  }
}

function buildRepeater(sec, key, fields, labels) {
  const items = sec.settings[key] || [];
  let html = '';
  items.forEach((item, i) => {
    const isOpen = openRepeaterItems[`${sec.id}_${key}_${i}`];
    html += `
      <div class="lpb-repeater-item">
        <div class="lpb-repeater-head" data-repeater-toggle="${sec.id}_${key}_${i}">
          <span>#${i+1} — ${esc(item[fields[0]]||'Item')}</span>
          <button type="button" class="lpb-remove-item-btn" data-repeater-key="${key}" data-repeater-index="${i}">✕</button>
        </div>
        <div class="lpb-repeater-body ${isOpen ? '' : 'lpb-hidden'}" data-repeater-body="${sec.id}_${key}_${i}">
          ${fields.map((f,fi) => `
            <div class="lpb-field">
              <label>${labels[fi]||f}</label>
              ${f==='text'||f==='a' ? `<textarea data-repeater-key="${key}" data-repeater-field="${f}" data-repeater-index="${i}" rows="2">${esc(item[f]||'')}</textarea>`
              : `<input type="text" data-repeater-key="${key}" data-repeater-field="${f}" data-repeater-index="${i}" value="${esc(item[f]||'')}">` }
            </div>`).join('')}
        </div>
      </div>`;
  });
  html += `<button type="button" class="lpb-add-item-btn" data-repeater-add="${key}">${lpbI18n.btnAddItem}</button>`;
  return html;
}

function bindPropsEvents(sec) {
  // Simple inputs / textareas / selects / colors
  propsContent.querySelectorAll('[data-key]').forEach(el => {
    el.addEventListener('input', () => {
      const s = state.sections.find(s => s.id === sec.id);
      if (!s) return;
      s.settings[el.dataset.key] = el.value;
      rerenderSection(sec.id);
    });
    el.addEventListener('change', () => {
      pushHistory();
    });
  });

  // Repeater toggles
  propsContent.querySelectorAll('[data-repeater-toggle]').forEach(el => {
    el.addEventListener('click', e => {
      if (e.target.closest('[data-repeater-index]')) return;
      const k = el.dataset.repeaterToggle;
      const body = propsContent.querySelector(`[data-repeater-body="${k}"]`);
      if (!body) return;
      body.classList.toggle('lpb-hidden');
      openRepeaterItems[k] = !body.classList.contains('lpb-hidden');
    });
  });

  // Repeater field inputs
  propsContent.querySelectorAll('[data-repeater-key][data-repeater-field]').forEach(el => {
    el.addEventListener('input', () => {
      const s = state.sections.find(s => s.id === sec.id);
      if (!s) return;
      const key   = el.dataset.repeaterKey;
      const field = el.dataset.repeaterField;
      const idx   = parseInt(el.dataset.repeaterIndex);
      if (!s.settings[key]) s.settings[key] = [];
      if (!s.settings[key][idx]) s.settings[key][idx] = {};
      s.settings[key][idx][field] = el.value;
      rerenderSection(sec.id);
    });
    el.addEventListener('change', pushHistory);
  });

  // Repeater remove
  propsContent.querySelectorAll('[data-repeater-index][data-repeater-key]').forEach(el => {
    if (!el.classList.contains('lpb-remove-item-btn')) return;
    el.addEventListener('click', e => {
      e.stopPropagation();
      const s = state.sections.find(s => s.id === sec.id);
      if (!s) return;
      const key = el.dataset.repeaterKey;
      const idx = parseInt(el.dataset.repeaterIndex);
      s.settings[key].splice(idx, 1);
      pushHistory();
      renderProps(s);
      rerenderSection(sec.id);
    });
  });

  // Repeater add
  propsContent.querySelectorAll('[data-repeater-add]').forEach(el => {
    el.addEventListener('click', () => {
      const s = state.sections.find(s => s.id === sec.id);
      if (!s) return;
      const key   = el.dataset.repeaterAdd;
      const def   = ELEMENTS.find(e => e.type === sec.type);
      const proto = def?.defaults[key]?.[0] || {};
      const newItem = {};
      Object.keys(proto).forEach(k => newItem[k] = proto[k]);
      if (!s.settings[key]) s.settings[key] = [];
      s.settings[key].push(newItem);
      pushHistory();
      renderProps(s);
      rerenderSection(sec.id);
    });
  });
}

/* Re-render only one section's HTML without rebuilding the whole canvas */
function rerenderSection(id) {
  const wrapper = document.querySelector(`[data-section-id="${id}"]`);
  if (!wrapper) { render(); return; }
  const sec = state.sections.find(s => s.id === id);
  if (!sec) return;
  // Replace the last child (the inner content div)
  const existingInner = wrapper.querySelector('.lpb-render-hero, .lpb-render-features, .lpb-render-testimonials, .lpb-render-faq, .lpb-render-countdown, .lpb-render-trust, .lpb-render-cta, .lpb-render-divider, .lpb-render-custom, .lpb-render-image-text');
  if (existingInner) {
    const tmp = document.createElement('div');
    tmp.innerHTML = renderSection(sec);
    existingInner.replaceWith(tmp.firstChild);
    // Re-bind FAQ
    if (sec.type === 'faq') {
      wrapper.querySelectorAll('.lpb-faq-question').forEach(q => {
        q.addEventListener('click', () => q.closest('.lpb-faq-item').classList.toggle('open'));
      });
    }
  } else { render(); }
  syncLayout();
}

/* ─────────────────────────────────────────────────
   VIEWPORT
───────────────────────────────────────────────── */
document.querySelectorAll('.lpb-vp-btn').forEach(btn => {
  btn.addEventListener('click', () => {
    document.querySelectorAll('.lpb-vp-btn').forEach(b => b.classList.remove('active'));
    btn.classList.add('active');
    canvasFrame.className = 'lpb-canvas-frame';
    if (btn.dataset.vp !== 'desktop') canvasFrame.classList.add('vp-' + btn.dataset.vp);
  });
});

/* ─────────────────────────────────────────────────
   OPEN / CLOSE / SAVE
───────────────────────────────────────────────── */
openBtn.addEventListener('click', () => {
  root.classList.add('lpb-open');
  document.body.style.overflow = 'hidden';
});

function closeBuilder() {
  root.classList.remove('lpb-open');
  document.body.style.overflow = '';
}

saveBtn.addEventListener('click', () => {
  syncLayout();
  closeBuilder();
  updateStats();
  showSaveToast();
});

closeBtn.addEventListener('click', () => {
  if (state.sections.length > 0 && !confirm(lpbI18n.confirmClose)) return;
  closeBuilder();
});

clearBtn.addEventListener('click', () => {
  if (state.sections.length && !confirm(lpbI18n.confirmClear)) return;
  state.sections = []; state.selected = null;
  pushHistory(); render();
});

undoBtn.addEventListener('click', undo);
redoBtn.addEventListener('click', redo);

searchInput.addEventListener('input', () => renderSidebar(searchInput.value));

/* ─────────────────────────────────────────────────
   SYNC TO HIDDEN INPUT (preserve existing toggles)
───────────────────────────────────────────────── */
function syncLayout() {
  if (!layoutInput) return;
  let existing = {};
  try { existing = JSON.parse(layoutInput.value || '{}'); } catch(e) {}

  // Preserve legacy toggles
  const toggleSticky    = document.getElementById('toggle_sticky_buy');
  const toggleWhatsapp  = document.getElementById('toggle_whatsapp');
  const toggleReviews   = document.getElementById('toggle_reviews');
  const toggleCountdown = document.getElementById('toggle_countdown');

  layoutInput.value = JSON.stringify({
    toggles: {
      sticky_buy: toggleSticky?.checked  ? 1 : (existing.toggles?.sticky_buy  || 0),
      whatsapp:   toggleWhatsapp?.checked ? 1 : (existing.toggles?.whatsapp   || 0),
      reviews:    toggleReviews?.checked  ? 1 : (existing.toggles?.reviews    || 0),
      countdown:  toggleCountdown?.checked? 1 : (existing.toggles?.countdown  || 0)
    },
    sections: state.sections
  });
}

/* ─────────────────────────────────────────────────
   HYDRATE FROM EXISTING DATA
───────────────────────────────────────────────── */
function hydrateFromLayout() {
  const raw = layoutInput?.value || '';
  if (!raw) return;
  try {
    const data = JSON.parse(raw);
    if (Array.isArray(data.sections) && data.sections.length) {
      state.sections = data.sections;
    }
    // Hydrate toggles
    if (data.toggles) {
      const t = data.toggles;
      const toggleSticky    = document.getElementById('toggle_sticky_buy');
      const toggleWhatsapp  = document.getElementById('toggle_whatsapp');
      const toggleReviews   = document.getElementById('toggle_reviews');
      const toggleCountdown = document.getElementById('toggle_countdown');
      if (toggleSticky)    toggleSticky.checked    = !!t.sticky_buy;
      if (toggleWhatsapp)  toggleWhatsapp.checked  = !!t.whatsapp;
      if (toggleReviews)   toggleReviews.checked   = !!t.reviews;
      if (toggleCountdown) toggleCountdown.checked = !!t.countdown;
    }
  } catch(e) {}
}

/* ─────────────────────────────────────────────────
   STATS UPDATE
───────────────────────────────────────────────── */
function updateStats(lastType) {
  statSections.textContent = state.sections.length;
  if (lastType) {
    const def = ELEMENTS.find(e => e.type === lastType);
    statType.textContent = def?.name || lastType;
  }
  const badge = statStatus.querySelector('strong');
  if (badge) badge.textContent = state.sections.length ? '✓ Active' : '—';
}

/* ─────────────────────────────────────────────────
   SAVE TOAST
───────────────────────────────────────────────── */
function showSaveToast() {
  const toast = document.createElement('div');
  toast.style.cssText = `
    position:fixed; bottom:24px; left:50%; transform:translateX(-50%);
    background:#22c55e; color:#fff; font-weight:700;
    padding:12px 28px; border-radius:10px; z-index:99999;
    box-shadow:0 8px 32px rgba(34,197,94,.4); font-size:15px;
    animation: lpb-toast-in .3s ease;
  `;
  toast.textContent = lpbI18n.saveToast;
  document.body.appendChild(toast);
  setTimeout(() => { toast.style.opacity='0'; toast.style.transition='opacity .4s'; setTimeout(()=>toast.remove(),400); }, 2500);
}

/* ─────────────────────────────────────────────────
   KEYBOARD SHORTCUTS
───────────────────────────────────────────────── */
document.addEventListener('keydown', e => {
  if (!root.classList.contains('lpb-open')) return;
  if (e.key === 'Escape') closeBuilder();
  if ((e.ctrlKey || e.metaKey) && e.key === 'z' && !e.shiftKey) { e.preventDefault(); undo(); }
  if ((e.ctrlKey || e.metaKey) && (e.key === 'y' || (e.key === 'z' && e.shiftKey))) { e.preventDefault(); redo(); }
  if ((e.ctrlKey || e.metaKey) && e.key === 's') {
    e.preventDefault();
    syncLayout(); closeBuilder(); showSaveToast();
  }
  if (e.key === 'Delete' && state.selected && !e.target.matches('input,textarea')) {
    deleteSection(state.selected);
  }
});

/* ─────────────────────────────────────────────────
   INIT
───────────────────────────────────────────────── */
window.addEventListener('DOMContentLoaded', () => {
  // نقل #lpb-root خارج الـ form حتى لا تتداخل inputs الـ builder مع submit الـ form
  const lpbRoot = document.getElementById('lpb-root');
  if (lpbRoot && lpbRoot.closest('form')) {
    document.body.appendChild(lpbRoot);
  }

  hydrateFromLayout();
  pushHistory();
  renderSidebar();
  render();
  updateStats();
});

// Also sync on form submit
const productForm = document.getElementById('productForm');
if (productForm) productForm.addEventListener('submit', syncLayout);

})();
</script>

<style>
@keyframes lpb-toast-in {
  from { transform: translateX(-50%) translateY(20px); opacity:0; }
  to   { transform: translateX(-50%) translateY(0);    opacity:1; }
}
</style>