<template>
  <div style="display:flex; flex-direction:column; height:100%; overflow:hidden;">
    <!-- Settings Header -->
    <div class="cw-lp-settings-hdr">
      <button type="button" class="cw-lp-back-btn" @click="deselectBlock">
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" width="14" height="14">
          <path fill-rule="evenodd" d="M17 10a.75.75 0 01-.75.75H5.612l4.158 3.96a.75.75 0 11-1.04 1.08l-5.5-5.25a.75.75 0 010-1.08l5.5-5.25a.75.75 0 111.04 1.08L5.612 9.25H16.25A.75.75 0 0117 10z" clip-rule="evenodd"/>
        </svg>
        Blocks
      </button>
      <span class="cw-lp-block-type">{{ blockTypeLabel(selectedBlock.type) }}</span>
      <button v-if="selectedBlock.type !== 'submit-button'" type="button" class="cw-lp-del-btn" @click="deleteBlock(selectedBlock.id)" title="Delete block">
        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="#ef4444" width="14" height="14"><path stroke-linecap="round" stroke-linejoin="round" d="M3 6h18M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2M10 11v6M14 11v6"/></svg>
      </button>
    </div>

    <div class="cw-lp-settings-body" style="flex: 1; overflow-y: auto; overflow-x: hidden; padding-bottom: 24px;">

      <!-- ── HEADING / TEXT CONTENT ── -->
      <template v-if="['heading', 'text'].includes(selectedBlock.type)">
        <div class="cw-lp-section">
          <div class="cw-lp-section-title">Content</div>
          <textarea class="cw-field-input" v-model="selectedBlock.content" rows="3" style="width:100%;height:auto;padding:8px"></textarea>
        </div>
        <div class="cw-lp-section">
          <div class="cw-lp-section-title">Typography</div>
          <div class="cw-settings-row">
            <span class="cw-settings-lbl">Font size</span>
            <div class="cw-unit-input">
              <input type="number" class="cw-field-input" v-model.number="selectedBlock.styles.fontSize" min="8" max="96" style="width:60px">
              <span class="cw-unit-tag">px</span>
            </div>
          </div>
          <div class="cw-settings-row">
            <span class="cw-settings-lbl">Text color</span>
            <CwColorPicker v-model="selectedBlock.styles.color" />
          </div>
          <div v-if="selectedBlock.type === 'heading'" class="cw-settings-row">
            <span class="cw-settings-lbl">Weight</span>
            <select class="cw-field-select" v-model.number="selectedBlock.styles.fontWeight">
              <option :value="400">Normal</option>
              <option :value="600">Semibold</option>
              <option :value="700">Bold</option>
              <option :value="800">Extra Bold</option>
            </select>
          </div>
        </div>
      </template>

      <!-- ── LOGO SETTINGS ── -->
      <template v-if="selectedBlock.type === 'logo'">
        <input ref="logoFileInputRef" type="file" accept="image/jpeg,image/png,image/gif,image/webp,image/svg+xml" style="display:none" @change="onImageFileSelected(selectedBlock, $event)">

        <div class="cw-lp-section">
          <div class="cw-lp-section-title">Logo Type</div>
          <select class="cw-field-select" v-model="selectedBlock.logoType" style="width:100%">
            <option value="image">Image Only</option>
            <option value="text">Text Only</option>
            <option value="image-text-side">Image &amp; Text (Side-by-Side)</option>
          </select>

          <div v-if="selectedBlock.logoType !== 'text'" style="margin-top:12px">
            <div class="cw-img-preview" @click="logoFileInputRef?.click()" style="margin-bottom:10px">
              <img v-if="selectedBlock.src" :src="selectedBlock.src" alt="logo preview">
              <div v-else class="cw-img-preview-empty">
                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="m18 9-6-6-6 6"/><path d="M12 3v14"/><path d="M5 21h14"/></svg>
                <span>Click to upload logo</span>
              </div>
              <div v-if="imageUploading" class="cw-img-uploading">
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="20" height="20" class="cw-spin"><path d="M12 2v4M12 18v4M4.93 4.93l2.83 2.83M16.24 16.24l2.83 2.83M2 12h4M18 12h4M4.93 19.07l2.83-2.83M16.24 7.76l2.83-2.83"/></svg>
                Uploading…
              </div>
            </div>

            <div class="cw-img-actions" style="margin-bottom:12px">
              <button type="button" class="cw-img-action-btn" @click="logoFileInputRef?.click()" :disabled="imageUploading">
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" width="13" height="13"><path d="M9.25 13.25a.75.75 0 001.5 0V4.636l2.955 3.129a.75.75 0 001.09-1.03l-4.25-4.5a.75.75 0 00-1.09 0l-4.25 4.5a.75.75 0 101.09 1.03L9.25 4.636v8.614z"/><path d="M3.5 12.75a.75.75 0 00-1.5 0v2.5A2.75 2.75 0 004.75 18h10.5A2.75 2.75 0 0018 15.25v-2.5a.75.75 0 00-1.5 0v2.5c0 .69-.56 1.25-1.25 1.25H4.75c-.69 0-1.25-.56-1.25-1.25v-2.5z"/></svg>
                {{ selectedBlock.src ? 'Replace' : 'Upload logo' }}
              </button>
              <button type="button" class="cw-img-action-btn" @click="openLibrary(selectedBlock, 'src', 'image', 'form-image')">
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" width="13" height="13"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><path d="M21 15l-5-5L5 21"/></svg>
                Library
              </button>
              <button v-if="selectedBlock.src" type="button" class="cw-img-action-btn cw-img-remove-btn" @click="selectedBlock.src = ''" title="Remove logo">
                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="#ef4444" width="14" height="14"><path stroke-linecap="round" stroke-linejoin="round" d="M3 6h18M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2M10 11v6M14 11v6"/></svg>
                Remove
              </button>
            </div>

            <div class="form-group-sm">
              <label class="cw-field-label">Logo Link URL</label>
              <input type="url" class="cw-field-input" v-model="selectedBlock.link" placeholder="https://..." style="width:100%">
            </div>
          </div>

          <div v-if="selectedBlock.logoType !== 'image'" class="form-group-sm" style="margin-top:12px">
            <label class="cw-field-label">Brand Text</label>
            <input type="text" class="cw-field-input" v-model="selectedBlock.brandText" style="width:100%">
          </div>
        </div>
      </template>

      <!-- ── IMAGE SETTINGS ── -->
      <template v-if="selectedBlock.type === 'image'">
        <input ref="imageFileInputRef" type="file" accept="image/jpeg,image/png,image/gif,image/webp,image/svg+xml" style="display:none" @change="onImageFileSelected(selectedBlock, $event)">

        <div class="cw-lp-section">
          <div class="cw-lp-section-title">Visual</div>
          <div class="cw-img-preview" @click="imageFileInputRef?.click()">
            <img v-if="selectedBlock.src" :src="selectedBlock.src" alt="preview">
            <div v-else class="cw-img-preview-empty">
              <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" width="28" height="28"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><path d="M21 15l-5-5L5 21"/></svg>
              <span>Click to upload</span>
            </div>
            <div v-if="imageUploading" class="cw-img-uploading">
              <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="20" height="20" class="cw-spin"><path d="M12 2v4M12 18v4M4.93 4.93l2.83 2.83M16.24 16.24l2.83 2.83M2 12h4M18 12h4M4.93 19.07l2.83-2.83M16.24 7.76l2.83-2.83"/></svg>
              Uploading…
            </div>
          </div>
          <div class="cw-img-actions">
            <button type="button" class="cw-img-action-btn" @click="imageFileInputRef?.click()" :disabled="imageUploading">
              <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" width="13" height="13"><path d="M9.25 13.25a.75.75 0 001.5 0V4.636l2.955 3.129a.75.75 0 001.09-1.03l-4.25-4.5a.75.75 0 00-1.09 0l-4.25 4.5a.75.75 0 101.09 1.03L9.25 4.636v8.614z"/><path d="M3.5 12.75a.75.75 0 00-1.5 0v2.5A2.75 2.75 0 004.75 18h10.5A2.75 2.75 0 0018 15.25v-2.5a.75.75 0 00-1.5 0v2.5c0 .69-.56 1.25-1.25 1.25H4.75c-.69 0-1.25-.56-1.25-1.25v-2.5z"/></svg>
              {{ selectedBlock.src ? 'Replace' : 'Upload image' }}
            </button>
            <button type="button" class="cw-img-action-btn" @click="openLibrary(selectedBlock, 'src', 'image', 'form-image')">
              <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" width="13" height="13"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><path d="M21 15l-5-5L5 21"/></svg>
              Library
            </button>
            <button v-if="selectedBlock.src" type="button" class="cw-img-action-btn cw-img-remove-btn" @click="selectedBlock.src = ''" title="Remove image">
              <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="#ef4444" width="14" height="14"><path stroke-linecap="round" stroke-linejoin="round" d="M3 6h18M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2M10 11v6M14 11v6"/></svg>
              Remove
            </button>
          </div>
        </div>

        <div class="cw-lp-section">
          <div class="cw-lp-section-title">Or paste URL</div>
          <input type="url" class="cw-field-input" v-model="selectedBlock.src" placeholder="https://example.com/image.jpg" style="width:100%">
        </div>

        <div class="cw-lp-section">
          <div class="cw-lp-section-title">Alt text</div>
          <input type="text" class="cw-field-input" v-model="selectedBlock.alt" placeholder="Describe this image…" style="width:100%">
        </div>

        <div class="cw-lp-section">
          <div class="cw-lp-section-title">Link</div>
          <input type="url" class="cw-field-input" v-model="selectedBlock.link" placeholder="https://…" style="width:100%">
        </div>
      </template>

      <!-- ── LINK BUTTON / SUBMIT BUTTON SETTINGS ── -->
      <template v-if="['button', 'submit-button'].includes(selectedBlock.type)">
        <div class="cw-lp-section">
          <div class="cw-lp-section-title">Button</div>
          <div class="form-group-sm">
            <label class="cw-field-label">Label</label>
            <input type="text" class="cw-field-input" v-model="selectedBlock.text" style="width:100%">
          </div>
          <div v-if="selectedBlock.type === 'button'" class="form-group-sm" style="margin-top:10px">
            <label class="cw-field-label">Link URL</label>
            <input type="url" class="cw-field-input" v-model="selectedBlock.href" placeholder="https://..." style="width:100%">
          </div>
          <div class="cw-settings-row" style="margin-top:10px">
            <span class="cw-settings-lbl">Background</span>
            <CwColorPicker v-model="selectedBlock.styles.backgroundColor" />
          </div>
          <div class="cw-settings-row">
            <span class="cw-settings-lbl">Text color</span>
            <CwColorPicker v-model="selectedBlock.styles.textColor" />
          </div>
          <div class="cw-settings-row">
            <span class="cw-settings-lbl">Font size</span>
            <div class="cw-unit-input">
              <input type="number" class="cw-field-input" v-model.number="selectedBlock.styles.fontSize" min="10" max="32" style="width:60px">
              <span class="cw-unit-tag">px</span>
            </div>
          </div>
        </div>
      </template>

      <!-- ── COLUMN SETTINGS ── -->
      <template v-if="selectedBlock.type === 'column'">
        <div class="cw-lp-section">
          <div class="cw-lp-section-title">Columns Layout</div>
          <div style="display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-top:8px">
            <button
              v-for="preset in COLUMN_PALETTE_PRESETS"
              :key="preset.label"
              type="button"
              class="cw-col-preset-card"
              @click="setColumnPreset(preset)"
              style="display:flex;align-items:center;gap:8px;border:1px solid #e5e7eb;border-radius:6px;padding:6px 10px;background:#fff;cursor:pointer"
            >
              <div style="width:36px;height:12px;display:flex">
                <div v-for="(w, idx) in preset.colWidths" :key="idx" :style="{ flex: w }" style="height:100%;border-right:1px solid #e5e7eb;background:#cbd5e1"></div>
              </div>
              <span style="font-size:11px;color:#374151;font-weight:500">{{ preset.label }}</span>
            </button>
          </div>
        </div>
      </template>

      <!-- ── DIVIDER SETTINGS ── -->
      <template v-if="selectedBlock.type === 'divider'">
        <div class="cw-lp-section">
          <div class="cw-lp-section-title">Appearance</div>
          <div class="cw-settings-row">
            <span class="cw-settings-lbl">Thickness</span>
            <div class="cw-unit-input">
              <input type="number" class="cw-field-input" v-model.number="selectedBlock.styles.dividerThickness" min="1" max="20" style="width:60px">
              <span class="cw-unit-tag">px</span>
            </div>
          </div>
          <div class="cw-settings-row">
            <span class="cw-settings-lbl">Color</span>
            <CwColorPicker v-model="selectedBlock.styles.borderColor" />
          </div>
        </div>
      </template>

      <!-- ── HTML SETTINGS ── -->
      <template v-if="selectedBlock.type === 'html'">
        <div class="cw-lp-section">
          <div class="cw-lp-section-title-row">
            <span class="cw-lp-section-title" style="margin:0">Code editor</span>
            <button type="button" class="cw-expand-btn" @click="openHtmlEditor(selectedBlock)">Expand</button>
          </div>
          <textarea class="cw-field-input" v-model="selectedBlock.html" spellcheck="false" placeholder="<p>Your HTML here…</p>" style="width:100%;height:140px;font-family:monospace;font-size:12px;padding:8px"></textarea>
        </div>
      </template>

      <!-- ══════════════ FORM FIELD SETTINGS ══════════════ -->
      <template v-if="isField(selectedBlock.type)">
        <div v-if="selectedBlock.type !== 'field-hidden'" class="cw-lp-section">
          <div class="cw-lp-section-title">Field</div>
          <div class="form-group-sm">
            <label class="cw-field-label">Label</label>
            <input type="text" class="cw-field-input" v-model="selectedBlock.label" style="width:100%">
          </div>
          <div v-if="hasPlaceholder(selectedBlock.type)" class="form-group-sm" style="margin-top:10px">
            <label class="cw-field-label">Placeholder</label>
            <input type="text" class="cw-field-input" v-model="selectedBlock.placeholder" style="width:100%">
          </div>
          <div class="form-group-sm" style="margin-top:10px">
            <label class="cw-field-label">Help Text</label>
            <input type="text" class="cw-field-input" v-model="selectedBlock.help" style="width:100%">
          </div>
          <div class="cw-settings-row" style="margin-top:10px">
            <span class="cw-settings-lbl">Required</span>
            <label class="fb-toggle">
              <input type="checkbox" v-model="selectedBlock.required">
              <span class="fb-toggle-track"></span>
            </label>
          </div>
        </div>

        <div v-if="selectedBlock.type === 'field-hidden'" class="cw-lp-section">
          <div class="cw-lp-section-title">Hidden Field</div>
          <div class="form-group-sm">
            <label class="cw-field-label">Field Name</label>
            <input type="text" class="cw-field-input" v-model="selectedBlock.label" style="width:100%">
          </div>
          <div class="form-group-sm" style="margin-top:10px">
            <label class="cw-field-label">Static Value</label>
            <input type="text" class="cw-field-input" v-model="selectedBlock.value" placeholder="Sent with every submission" style="width:100%">
          </div>
        </div>

        <div v-if="selectedBlock.type === 'field-radio'" class="cw-lp-section">
          <div class="cw-lp-section-title">Display As</div>
          <div class="cw-icon-btns" style="display:flex;gap:6px">
            <button type="button" class="cw-lp-tab" :class="{ 'is-active': (selectedBlock.displayAs || 'list') === 'list' }" @click="selectedBlock.displayAs = 'list'" style="border:1px solid #e5e7eb;border-radius:6px;padding:6px 12px">List</button>
            <button type="button" class="cw-lp-tab" :class="{ 'is-active': selectedBlock.displayAs === 'buttons' }" @click="selectedBlock.displayAs = 'buttons'" style="border:1px solid #e5e7eb;border-radius:6px;padding:6px 12px">Big Buttons</button>
          </div>
        </div>

        <div v-if="selectedBlock.type !== 'field-hidden'" class="cw-lp-section">
          <div class="cw-lp-section-title">{{ selectedBlock.type === 'field-radio' && selectedBlock.displayAs === 'buttons' ? 'Button Color' : 'Label Color' }}</div>
          <div class="cw-settings-row">
            <span class="cw-settings-lbl">Color</span>
            <CwColorPicker v-model="selectedBlock.styles.color" />
          </div>
        </div>

        <div v-if="canMapToContact(selectedBlock.type)" class="cw-lp-section">
          <div class="cw-lp-section-title">Maps to Contact Field</div>
          <select v-if="selectedBlock.type !== 'field-email'" class="cw-field-select" v-model="selectedBlock.contact_field" style="width:100%">
            <option :value="null">— Not mapped (custom) —</option>
            <option v-for="(f, key) in fieldRegistry" :key="key" :value="key" :disabled="key === 'email'">{{ f.label }}</option>
          </select>
          <input v-else type="text" class="cw-field-input" value="Email (required)" disabled style="width:100%">
        </div>

        <div v-if="hasOptions(selectedBlock.type)" class="cw-lp-section">
          <div class="cw-lp-section-title">Options</div>
          <div class="fb-options-list">
            <div class="fb-option-row" v-for="(opt, i) in selectedBlock.options" :key="i">
              <input type="text" :value="opt" @input="selectedBlock.options[i] = $event.target.value">
              <button type="button" @click="selectedBlock.options.splice(i, 1)">
                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12"/></svg>
              </button>
            </div>
          </div>
          <button type="button" class="fb-add-option-btn" @click="addOption">
            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M12 4.5v15m7.5-7.5h-15"/></svg>
            Add option
          </button>
        </div>
      </template>

      <!-- ── LAYOUT SETTINGS (shared) ── -->
      <div v-if="selectedBlock.type !== 'field-hidden'" class="cw-lp-section">
        <div class="cw-lp-section-title">Layout</div>
        <div v-if="!['image', 'submit-button'].includes(selectedBlock.type)" class="cw-settings-row">
          <span class="cw-settings-lbl">Width</span>
          <div class="cw-unit-input">
            <input type="number" v-model.number="selectedBlock.styles.width" min="10" max="100" class="cw-field-input" style="width:60px">
            <span class="cw-unit-tag">%</span>
          </div>
        </div>
        <div v-if="selectedBlock.type === 'spacer'" class="cw-settings-row">
          <span class="cw-settings-lbl">Height</span>
          <div class="cw-unit-input">
            <input type="number" class="cw-field-input" v-model.number="selectedBlock.styles.height" min="4" max="400" style="width:60px">
            <span class="cw-unit-tag">px</span>
          </div>
        </div>
        <div class="cw-settings-row">
          <span class="cw-settings-lbl">Block Alignment</span>
          <div class="cw-icon-btns">
            <button v-for="a in ['left','center','right']" :key="a" type="button" class="cw-icon-btn" :class="{ 'is-active': selectedBlock.styles.blockAlign === a }" @click="selectedBlock.styles.blockAlign = a" :title="a">
              <svg v-if="a==='left'" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" fill="currentColor" width="13" height="13"><path d="M1 2h14v2H1zm0 4h9v2H1zm0 4h11v2H1z"/></svg>
              <svg v-else-if="a==='center'" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" fill="currentColor" width="13" height="13"><path d="M1 2h14v2H1zm2 4h10v2H3zm-1 4h12v2H2z"/></svg>
              <svg v-else xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" fill="currentColor" width="13" height="13"><path d="M1 2h14v2H1zm5 4h9v2H6zm-5 4h14v2H1z"/></svg>
            </button>
          </div>
        </div>
        <div v-if="['heading', 'text', 'button', 'submit-button'].includes(selectedBlock.type)" class="cw-settings-row">
          <span class="cw-settings-lbl">Text Alignment</span>
          <div class="cw-icon-btns">
            <button v-for="a in ['left','center','right']" :key="a" type="button" class="cw-icon-btn" :class="{ 'is-active': selectedBlock.styles.textAlign === a }" @click="selectedBlock.styles.textAlign = a" :title="a">
              <svg v-if="a==='left'" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" fill="currentColor" width="13" height="13"><path d="M1 2h14v1.5H1zm0 3.5h9v1.5H1zm0 3.5h11v1.5H1zm0 3.5h8v1.5H1z"/></svg>
              <svg v-else-if="a==='center'" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" fill="currentColor" width="13" height="13"><path d="M1 2h14v1.5H1zm2 3.5h10v1.5H3zm-1 3.5h12v1.5H2zm2 3.5h8v1.5H4z"/></svg>
              <svg v-else xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" fill="currentColor" width="13" height="13"><path d="M1 2h14v1.5H1zm5 3.5h9v1.5H6zm3 3.5h5v1.5h-5zm-7 3.5h12v1.5H2z"/></svg>
            </button>
          </div>
        </div>
      </div>

      <!-- ── SPACING SETTINGS (shared, except spacer) ── -->
      <div v-if="!['spacer', 'field-hidden'].includes(selectedBlock.type)" class="cw-lp-section">
        <div class="cw-lp-section-title">Spacing</div>
        <div class="cw-spacing-label-row"><span class="cw-settings-lbl">Padding</span></div>
        <div class="cw-4side-grid">
          <div class="cw-side-input"><input type="number" class="cw-field-input" v-model.number="selectedBlock.styles.paddingTop" min="0"><span class="cw-side-label">T</span></div>
          <div class="cw-side-input"><input type="number" class="cw-field-input" v-model.number="selectedBlock.styles.paddingRight" min="0"><span class="cw-side-label">R</span></div>
          <div class="cw-side-input"><input type="number" class="cw-field-input" v-model.number="selectedBlock.styles.paddingBottom" min="0"><span class="cw-side-label">B</span></div>
          <div class="cw-side-input"><input type="number" class="cw-field-input" v-model.number="selectedBlock.styles.paddingLeft" min="0"><span class="cw-side-label">L</span></div>
        </div>
        <div class="cw-spacing-label-row" style="margin-top:10px"><span class="cw-settings-lbl">Margin</span></div>
        <div class="cw-4side-grid">
          <div class="cw-side-input"><input type="number" class="cw-field-input" v-model.number="selectedBlock.styles.marginTop" min="0"><span class="cw-side-label">T</span></div>
          <div class="cw-side-input"><input type="number" class="cw-field-input" v-model.number="selectedBlock.styles.marginRight" min="0"><span class="cw-side-label">R</span></div>
          <div class="cw-side-input"><input type="number" class="cw-field-input" v-model.number="selectedBlock.styles.marginBottom" min="0"><span class="cw-side-label">B</span></div>
          <div class="cw-side-input"><input type="number" class="cw-field-input" v-model.number="selectedBlock.styles.marginLeft" min="0"><span class="cw-side-label">L</span></div>
        </div>
      </div>

      <!-- ── BACKGROUND (shared, except link/submit button) ── -->
      <div v-if="!['button', 'submit-button', 'field-hidden'].includes(selectedBlock.type)" class="cw-lp-section">
        <div class="cw-lp-section-title">Background</div>
        <div class="cw-settings-row">
          <span class="cw-settings-lbl">Color</span>
          <div style="display:flex;align-items:center;gap:8px">
            <CwColorPicker v-model="selectedBlock.styles.bgColor" />
            <button v-if="selectedBlock.styles.bgColor" type="button" class="btn btn-outline btn-xs" style="padding:2px 6px;font-size:11px" @click="selectedBlock.styles.bgColor = ''">Clear</button>
          </div>
        </div>
      </div>

      <!-- ── ROUNDED CORNERS (shared) ── -->
      <div v-if="!['spacer', 'field-hidden'].includes(selectedBlock.type)" class="cw-lp-section">
        <div class="cw-lp-section-title">Rounded Corners</div>
        <div class="cw-settings-row">
          <span class="cw-settings-lbl">Radius</span>
          <div class="cw-unit-input">
            <input type="number" class="cw-field-input" v-model.number="selectedBlock.styles.borderRadius" min="0" max="60" style="width:60px">
            <span class="cw-unit-tag">px</span>
          </div>
        </div>
      </div>

      <!-- ── BORDERS (shared, not spacer/hidden/submit-button) ── -->
      <div v-if="!['spacer', 'field-hidden', 'submit-button'].includes(selectedBlock.type)" class="cw-lp-section">
        <div class="cw-lp-section-title">Border</div>
        <div class="cw-settings-row">
          <span class="cw-settings-lbl">Width</span>
          <div class="cw-unit-input">
            <input type="number" class="cw-field-input" v-model.number="selectedBlock.styles.borderWidth" min="0" max="20" style="width:60px">
            <span class="cw-unit-tag">px</span>
          </div>
        </div>
        <div class="cw-settings-row">
          <span class="cw-settings-lbl">Color</span>
          <CwColorPicker v-model="selectedBlock.styles.borderColor" />
        </div>
      </div>

    </div>

    <MediaLibraryModal
      :open="libraryOpen"
      :type="libraryType"
      :collection="libraryCollection"
      @close="libraryOpen = false"
      @select="onLibrarySelect"
    />
  </div>
</template>

<script setup>
import { inject, ref } from 'vue';
import CwColorPicker from '@/Components/CwColorPicker.vue';
import MediaLibraryModal from '@/Components/MediaLibrary/MediaLibraryModal.vue';
import {
  blockTypeLabel,
  hasPlaceholder,
  hasOptions,
  canMapToContact,
  isFieldBlock,
  COLUMN_PALETTE_PRESETS,
} from './formEditorUtils';

const {
  selectedBlock,
  selectedBlockId,
  deleteBlock,
  openHtmlEditor,
  saveHistory,
} = inject('formEditorState');

// Injected from the outer Pages/Forms/Builder.vue provide('formBuilderState', ...)
// - Vue's inject() walks the whole ancestor chain, not just the nearest
// provider, so this reaches past FormEditor's own provide.
const { fieldRegistry } = inject('formBuilderState', { fieldRegistry: {} });

function isField(type) {
  return isFieldBlock(type);
}

function deselectBlock() {
  selectedBlockId.value = null;
}

function setColumnPreset(preset) {
  selectedBlock.value.columnCount = preset.columnCount;
  selectedBlock.value.colWidths = preset.colWidths;
  const current = selectedBlock.value.columns || [];
  const next = [];
  for (let i = 0; i < preset.columnCount; i++) {
    next.push(current[i] || { id: crypto.randomUUID(), blocks: [] });
  }
  selectedBlock.value.columns = next;
}

function addOption() {
  if (!selectedBlock.value.options) selectedBlock.value.options = [];
  selectedBlock.value.options.push('Option ' + (selectedBlock.value.options.length + 1));
}

// ── Image/logo upload + media library (same pattern as EmailEditor's
// BlockSettings.vue, reusing the same generic upload endpoint) ────────────
const logoFileInputRef = ref(null);
const imageFileInputRef = ref(null);
const imageUploading = ref(false);

const libraryOpen = ref(false);
const libraryType = ref(null);
const libraryCollection = ref('library');
const libraryTarget = ref(null);

function openLibrary(block, field, type, collection) {
  libraryTarget.value = { block, field };
  libraryType.value = type;
  libraryCollection.value = collection;
  libraryOpen.value = true;
}

function onLibrarySelect(item) {
  if (libraryTarget.value) {
    libraryTarget.value.block[libraryTarget.value.field] = item.url;
    saveHistory();
  }
  libraryOpen.value = false;
}

async function onImageFileSelected(block, event) {
  const file = event.target.files?.[0];
  if (!file) return;
  imageUploading.value = true;
  try {
    const formData = new FormData();
    formData.append('image', file);
    const res = await window.axios.post(route('campaigns.upload-image'), formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
    });
    block.src = res.data.url;
    saveHistory();
  } catch (err) {
    window.alert('Image upload failed. Please try again.');
  } finally {
    imageUploading.value = false;
    if (imageFileInputRef.value) imageFileInputRef.value.value = '';
    if (logoFileInputRef.value) logoFileInputRef.value.value = '';
  }
}
</script>
