<template>
  <AppLayout>
    <div class="builder-page">

      <!-- PAGE TITLE ROW — full width, above the flex body -->
      <div class="builder-title-row">
        <div class="builder-title-row__left">
          <Link :href="route('member.surveys.index')" class="builder-back-btn">
            <i class="ti ti-arrow-left"></i>
          </Link>
          <h1 class="builder-title">
            {{ survey
              ? (locale === 'ar' ? 'تعديل الاستبيان' : 'Edit Survey')
              : (locale === 'ar' ? 'استبيان جديد'    : 'New Survey') }}
          </h1>
        </div>
        <div class="builder-title-row__right">
          <button
            @click="showBank = !showBank"
            class="builder-bank-btn"
            :class="{ 'builder-bank-btn--active': showBank }"
          >
            📚 {{ locale === 'ar' ? 'بنك الأسئلة' : 'Question Bank' }}
          </button>
          <button @click="saveSurvey" :disabled="saving" class="ip-btn ip-btn--primary">
            <span v-if="saving">{{ locale === 'ar' ? 'جارٍ الحفظ…' : 'Saving…' }}</span>
            <span v-else>{{ survey ? (locale === 'ar' ? 'تحديث' : 'Update') : (locale === 'ar' ? 'حفظ' : 'Save') }}</span>
          </button>
        </div>
      </div>

      <!-- BUILDER BODY — flex row: main area + optional bank panel -->
      <div class="builder-body">

        <!-- MAIN BUILDER AREA -->
        <div class="builder-main">

          <!-- Survey Details card -->
          <div class="builder-card">

            <!-- Card header: title + Writing in EN/AR switcher -->
            <div class="builder-card__head">
              <p class="builder-card__label">
                {{ locale === 'ar' ? 'تفاصيل الاستبيان' : 'Survey Details' }}
              </p>
              
            </div>

            <!-- Title -->
            <div class="builder-field">
              <label class="builder-field__label">
                {{ locale === 'ar' ? 'عنوان الاستبيان *' : 'Survey Title *' }}
              </label>
              <input
                v-model="form.title_en"
                type="text"
                :placeholder="locale === 'ar' ? 'مثال: استبيان رضا العملاء' : 'e.g. Q1 Customer Satisfaction Survey'"
                class="builder-input"
              />
            </div>

            <!-- Description -->
            <div class="builder-field">
              <label class="builder-field__label">
                {{ locale === 'ar' ? 'مقدمة الاستبيان (اختياري)' : 'Introduction (optional)' }}
              </label>
             <textarea
                v-model="form.description_en"
                rows="3"
                :placeholder="locale === 'ar' ? 'مقدمة تظهر للمجيبين قبل البدء...' : 'Brief intro shown to respondents before they start...'"
                class="builder-input builder-input--textarea"
              ></textarea>
            </div>

            <!-- Row: Audience + Close date -->
            <div class="builder-row">
              <div class="builder-field">
                <label class="builder-field__label">
                  {{ locale === 'ar' ? 'الجمهور' : 'Audience' }}
                </label>
                <select v-model="form.audience" class="builder-input">
                  <option value="all">{{ locale === 'ar' ? 'جميع الأعضاء' : 'All Members' }}</option>
                  <option value="hub">{{ locale === 'ar' ? 'أعضاء هب محدد' : 'Specific Hub' }}</option>
                </select>
              </div>

              <div class="builder-field" v-if="form.audience === 'hub'">
                <label class="builder-field__label">
                  {{ locale === 'ar' ? 'الهب' : 'Hub' }}
                </label>
                <select v-model="form.hub_id" class="builder-input">
                  <option :value="null">{{ locale === 'ar' ? 'اختر الهب' : 'Select Hub' }}</option>
                  <option v-for="hub in allHubs" :key="hub.id" :value="hub.id">
                    {{ locale === 'ar' ? hub.name_ar : hub.name_en }}
                  </option>
                </select>
              </div>

              <div class="builder-field">
                <label class="builder-field__label">
                  {{ locale === 'ar' ? 'تاريخ الإغلاق (اختياري)' : 'Close Date (optional)' }}
                </label>
                <input v-model="form.closes_at" type="date" class="builder-input" />
              </div>
            </div>

            <!-- Toggles -->
            <div class="builder-toggles">
              <label class="builder-toggle">
                <div
                  @click="form.anonymous_responses = !form.anonymous_responses"
                  :class="{ 'builder-toggle__track--on': form.anonymous_responses }"
                  class="builder-toggle__track"
                >
                  <div class="builder-toggle__thumb" :class="{ 'builder-toggle__thumb--on': form.anonymous_responses }"></div>
                </div>
                <span class="builder-toggle__label">
                  {{ locale === 'ar' ? 'إخفاء هوية المجيبين' : 'Anonymous Responses' }}
                </span>
              </label>

              <label class="builder-toggle">
                <div
                  @click="form.show_results_to_members = !form.show_results_to_members"
                  :class="{ 'builder-toggle__track--on': form.show_results_to_members }"
                  class="builder-toggle__track"
                >
                  <div class="builder-toggle__thumb" :class="{ 'builder-toggle__thumb--on': form.show_results_to_members }"></div>
                </div>
                <span class="builder-toggle__label">
                  {{ locale === 'ar' ? 'مشاركة النتائج مع الأعضاء' : 'Share Results with Members' }}
                </span>
              </label>
            </div>
          </div>

          <!-- Questions -->
          <div
            v-for="(q, qi) in form.questions"
            :key="q._id"
            class="builder-card builder-question"
            :class="{ 'builder-question--active': activeQ === qi }"
            @click="activeQ = qi"
          >
            <div class="builder-q-header">
              <span class="builder-q-num">{{ qi + 1 }}</span>
              <span class="builder-q-type-badge" :class="`builder-q-type-badge--${q.type}`">
                {{ typeLabel(q.type) }}
              </span>
              <div style="flex:1"></div>
              <label class="builder-q-required">
                <input type="checkbox" v-model="q.is_required" />
                {{ locale === 'ar' ? 'إلزامي' : 'Required' }}
              </label>
              <button @click.stop="moveQ(qi, -1)" :disabled="qi === 0" class="builder-q-btn">
                <i class="ti ti-chevron-up"></i>
              </button>
              <button @click.stop="moveQ(qi, 1)" :disabled="qi === form.questions.length - 1" class="builder-q-btn">
                <i class="ti ti-chevron-down"></i>
              </button>
              <button @click.stop="removeQ(qi)" class="builder-q-btn builder-q-btn--danger">
                <i class="ti ti-x"></i>
              </button>
            </div>

            <div class="builder-q-body">
              <input
                v-model="q.question_en"
                type="text"
                :placeholder="locale === 'ar' ? typePlaceholderAr(q.type) : typePlaceholder(q.type)"
                class="builder-q-input"
              />

              <!-- MCQ / Multi-select options -->
              <div v-if="['multiple_choice', 'multi_select'].includes(q.type)" class="builder-q-options">
                <div
                  v-for="(opt, oi) in q.options_en"
                  :key="oi"
                  class="builder-q-option"
                >
                  <div class="builder-q-option-dot" :class="q.type === 'multi_select' ? 'builder-q-option-dot--square' : ''"></div>
                  <input
                    v-model="q.options_en[oi]"
                    type="text"
                    :placeholder="`${locale === 'ar' ? 'خيار' : 'Option'} ${oi + 1}`"
                    :dir="locale === 'ar' ? 'rtl' : 'ltr'"
                    class="builder-q-option-input"
                  />
                  <button @click="removeOption(q, oi)" class="builder-q-option-del">✕</button>
                </div>
                <button @click="addOption(q)" class="builder-add-option">
                  + {{ locale === 'ar' ? 'إضافة خيار' : 'Add Option' }}
                </button>
              </div>

              <!-- Yes / No preview -->
              <div v-if="q.type === 'yes_no'" class="builder-yes-no">
                <div class="builder-yes-no__yes">✓ {{ locale === 'ar' ? 'نعم' : 'Yes' }}</div>
                <div class="builder-yes-no__no">✕ {{ locale === 'ar' ? 'لا' : 'No' }}</div>
              </div>

              <!-- Rating preview -->
              <div v-if="q.type === 'rating'" class="builder-rating">
                <div class="builder-rating__dots">
                  <span v-for="n in q.rating_max" :key="n" class="builder-rating__dot">{{ n }}</span>
                </div>
                <div class="builder-rating__config">
                  <span class="builder-rating__config-label">{{ locale === 'ar' ? 'الحد الأقصى:' : 'Max:' }}</span>
                  <select v-model="q.rating_max" class="builder-rating__select">
                    <option v-for="n in [3,4,5,7,10]" :key="n" :value="n">{{ n }}</option>
                  </select>
                </div>
              </div>

              <!-- Text preview -->
              <div v-if="q.type === 'text'" class="builder-text-preview">
                {{ locale === 'ar' ? 'إجابة نصية مفتوحة' : 'Open text response' }}
              </div>

              <!-- Save to my bank -->
              <div class="builder-q-save-bank" @click.stop>
                <label class="builder-q-save-bank__label">
                  <input type="checkbox" v-model="q._save_to_bank" />
                  💾 {{ locale === 'ar' ? 'حفظ في بنك أسئلتي' : 'Save to my question bank' }}
                </label>
                <select
                  v-if="q._save_to_bank"
                  v-model="q._bank_section_id"
                  class="builder-q-save-bank__select"
                >
                  <option :value="null">{{ locale === 'ar' ? 'بدون قسم' : 'No section' }}</option>
                  <option v-for="s in bankSections" :key="s.id" :value="s.id">
                    {{ locale === 'ar' && s.name_ar ? s.name_ar : s.name_en }}
                  </option>
                </select>
              </div>

            </div>
          </div>

          <!-- Add Question Buttons -->
          <div class="builder-add-q">
            <p class="builder-add-q__label">
              {{ locale === 'ar' ? 'إضافة سؤال:' : 'Add a question:' }}
            </p>
            <div class="builder-add-q__types">
              <button
                v-for="t in questionTypes"
                :key="t.value"
                @click="addQuestion(t.value)"
                class="builder-type-btn"
                :class="`builder-type-btn--${t.value}`"
              >
                <span class="builder-type-btn__icon">{{ t.icon }}</span>
                <span>{{ locale === 'ar' ? t.labelAr : t.label }}</span>
              </button>
            </div>
          </div>

        </div><!-- /builder-main -->

        <!-- Question Bank Panel -->
        <div v-if="showBank" class="builder-bank">
          <div class="builder-bank__head">
            <h3 class="builder-bank__title">
              📚 {{ locale === 'ar' ? 'بنك الأسئلة' : 'Question Bank' }}
            </h3>
            <input
              v-model="bankSearch"
              type="text"
              :placeholder="locale === 'ar' ? 'بحث…' : 'Search…'"
              class="builder-bank__search"
            />
          </div>
          <div class="builder-bank__body">
            <div
              v-for="section in groupedBankItems"
              :key="section.id"
              class="builder-bank__section"
            >
              <div class="builder-bank__section-head" :class="`builder-bank__section-head--${section.color}`">
                {{ locale === 'ar' ? section.name_ar : section.name_en }}
              </div>
              <div
                v-for="item in section.items"
                :key="item.id"
                class="builder-bank__item"
                @click="addFromBank(item)"
              >
                <span class="builder-bank__item-type" :class="`builder-type-btn--${item.type}`">
                  {{ typeLabel(item.type) }}
                </span>
                <span class="builder-bank__item-q">
                  {{ locale === 'ar' && item.question_ar ? item.question_ar : item.question_en }}
                </span>
                <span v-if="item.is_personal" class="builder-bank__item-personal">
                  {{ locale === 'ar' ? 'لي' : 'Mine' }}
                </span>
                <button
                  v-if="item.is_personal"
                  @click.stop="deleteBankItem(item)"
                  class="builder-bank__item-del"
                  :title="locale === 'ar' ? 'حذف من بنكي' : 'Delete from my bank'"
                >✕</button>
                <span v-else class="builder-bank__item-plus">+</span>
              </div>
            </div>
          </div>
        </div>

      </div><!-- /builder-body -->
    </div><!-- /builder-page -->
  </AppLayout>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { Link, router } from '@inertiajs/vue3'
import AppLayout from '@/Layouts/AppLayout.vue'
import { useAuthStore } from '@/Stores/useAuthStore'


const props = defineProps({
  survey:       { type: Object, default: null },
  bankSections: { type: Array,  default: () => [] },
  bankItems:    { type: Array,  default: () => [] },
  allHubs:      { type: Array,  default: () => [] },
})

const authStore  = useAuthStore()
const locale     = computed(() => authStore.locale)
const showBank   = ref(false)
const saving     = ref(false)
const activeQ    = ref(null)
const bankSearch = ref('')

const questionTypes = [
  { value: 'multiple_choice', label: 'Multiple Choice', labelAr: 'اختيار واحد',  icon: '◉' },
  { value: 'multi_select',    label: 'Multi-Select',    labelAr: 'اختيار متعدد', icon: '☑' },
  { value: 'yes_no',          label: 'Yes / No',        labelAr: 'نعم / لا',     icon: '✓✕' },
  { value: 'rating',          label: 'Rating Scale',    labelAr: 'تقييم',        icon: '★' },
  { value: 'text',            label: 'Text',            labelAr: 'إجابة نصية',   icon: '¶' },
]

const typeLabel = (t) => {
  const map = { multiple_choice: 'MCQ', multi_select: 'Multi', yes_no: 'Yes/No', rating: 'Rating', text: 'Text' }
  return map[t] ?? t
}

const typePlaceholder = (t) => {
  const map = {
    multiple_choice: 'Type your multiple choice question here...',
    multi_select:    'Type your multi-select question here...',
    yes_no:          'Type your yes/no question here...',
    rating:          'Type your rating question here...',
    text:            'Type your open-ended question here...',
  }
  return map[t] ?? ''
}

const typePlaceholderAr = (t) => {
  const map = {
    multiple_choice: 'اكتب سؤال الاختيار من متعدد هنا...',
    multi_select:    'اكتب سؤال الاختيار المتعدد هنا...',
    yes_no:          'اكتب سؤال نعم/لا هنا...',
    rating:          'اكتب سؤال التقييم هنا...',
    text:            'اكتب السؤال المفتوح هنا...',
  }
  return map[t] ?? ''
}

let _idCounter = 0
const makeId = () => ++_idCounter

const defaultOptions   = (type) => {
  if (type === 'yes_no') return ['Yes', 'No']
  if (['multiple_choice', 'multi_select'].includes(type)) return ['', '', '']
  return []
}

const defaultOptionsAr = (type) => {
  if (type === 'yes_no') return ['نعم', 'لا']
  if (['multiple_choice', 'multi_select'].includes(type)) return ['', '', '']
  return []
}

const buildQuestion = (type, overrides = {}) => ({
  _id:              makeId(),
  question_en:      '',
  question_ar:      '',
  type,
  is_required:      true,
  rating_min:       1,
  rating_max:       5,
  options_en:       defaultOptions(type),
  options_ar:       defaultOptionsAr(type),
  bank_item_id:     null,
  _save_to_bank:    false,
  _bank_section_id: null,
  ...overrides,
})

const hydrateQuestions = () => {
  if (!props.survey?.questions) return []
  return props.survey.questions.map(q => buildQuestion(q.type, {
    ...q,
    options_en: q.options_en?.length ? q.options_en : defaultOptions(q.type),
    options_ar: q.options_ar?.length ? q.options_ar : defaultOptionsAr(q.type),
  }))
}

const form = reactive({
  title_en:                props.survey?.title_en ?? '',
  title_ar:                props.survey?.title_ar ?? '',
  description_en:          props.survey?.description_en ?? '',
  description_ar:          props.survey?.description_ar ?? '',
  audience:                props.survey?.audience ?? 'all',
  hub_id:                  props.survey?.hub_id ?? null,
  anonymous_responses:     props.survey?.anonymous_responses ?? true,
  show_results_to_members: props.survey?.show_results_to_members ?? false,
  closes_at:               props.survey?.closes_at ?? '',
  questions:               hydrateQuestions(),
})

const addQuestion = (type) => {
  form.questions.push(buildQuestion(type))
  activeQ.value = form.questions.length - 1
}

const removeQ = (i) => {
  form.questions.splice(i, 1)
  if (activeQ.value >= form.questions.length) activeQ.value = form.questions.length - 1
}

const moveQ = (i, dir) => {
  const j = i + dir
  if (j < 0 || j >= form.questions.length) return
  const tmp = form.questions[i]; form.questions[i] = form.questions[j]; form.questions[j] = tmp
}

const addOption = (q) => { q.options_en.push(''); q.options_ar.push('') }

const removeOption = (q, i) => { q.options_en.splice(i, 1); q.options_ar.splice(i, 1) }

const addFromBank = (item) => {
  form.questions.push(buildQuestion(item.type, {
    question_en:  item.question_en,
    question_ar:  item.question_ar,
    is_required:  item.is_required,
    rating_min:   item.rating_min,
    rating_max:   item.rating_max,
    options_en:   item.options_en?.length ? [...item.options_en] : defaultOptions(item.type),
    options_ar:   item.options_ar?.length ? [...item.options_ar] : defaultOptionsAr(item.type),
    bank_item_id: item.id,
  }))
  activeQ.value = form.questions.length - 1
}

const groupedBankItems = computed(() => {
  const search = bankSearch.value.toLowerCase()
  const filtered = props.bankItems.filter(i =>
    !search ||
    i.question_en.toLowerCase().includes(search) ||
    (i.question_ar && i.question_ar.includes(bankSearch.value))
  )
  const map = new Map()
  props.bankSections.forEach(s => map.set(s.id, { ...s, items: [] }))
  map.set(null, { id: null, name_en: 'General', name_ar: 'عام', color: 'gray', items: [] })
  filtered.forEach(item => {
    const bucket = map.get(item.question_bank_section_id) ?? map.get(null)
    bucket.items.push(item)
  })
  return [...map.values()].filter(s => s.items.length > 0)
})

// ── Delete personal bank item ─────────────────────────────
const deleteBankItem = async (item) => {
  if (!confirm(locale.value === 'ar' ? 'حذف هذا السؤال من بنكك؟' : 'Delete this question from your bank?')) return
  const csrfMeta = document.querySelector('meta[name="csrf-token"]')
  const token = csrfMeta ? csrfMeta.content : ''
  await fetch(`/app/surveys/bank-items/${item.id}`, {
    method: 'DELETE',
    headers: { 'X-CSRF-TOKEN': token, Accept: 'application/json' },
    credentials: 'include',
  })
  // Remove from local list so panel updates immediately without page reload
  const idx = props.bankItems.findIndex(i => i.id === item.id)
  if (idx > -1) props.bankItems.splice(idx, 1)
}

const saveSurvey = () => {
  if (!form.title_en.trim()) {
    alert(locale.value === 'ar' ? 'يرجى إدخال عنوان الاستبيان.' : 'Please enter a survey title in English.')
    return
  }
  saving.value = true
  const payload = {
    title_en:                form.title_en,
    title_ar:                form.title_ar || null,
    description_en:          form.description_en || null,
    description_ar:          form.description_ar || null,
    audience:                form.audience,
    hub_id:                  form.hub_id,
    anonymous_responses:     form.anonymous_responses,
    show_results_to_members: form.show_results_to_members,
    closes_at:               form.closes_at || null,
    questions: form.questions.map(q => ({
      question_en:      q.question_en,
      question_ar:      q.question_ar || null,
      type:             q.type,
      is_required:      q.is_required,
      rating_min:       q.rating_min,
      rating_max:       q.rating_max,
      bank_item_id:     q.bank_item_id,
      _save_to_bank:    q._save_to_bank,
      _bank_section_id: q._bank_section_id,
      options_en:   ['multiple_choice', 'multi_select', 'yes_no'].includes(q.type)
                      ? q.options_en.filter(o => o.trim()) : [],
      options_ar:   ['multiple_choice', 'multi_select', 'yes_no'].includes(q.type)
                      ? q.options_ar.filter(o => o.trim()) : [],
    })),
  }
  const onFinish = () => { saving.value = false }
  if (props.survey) {
    router.put(route('member.surveys.update', props.survey.id), payload, { onFinish })
  } else {
    router.post(route('member.surveys.store'), payload, { onFinish })
  }
}
</script>

<style scoped>
.builder-page {
  min-height: 100vh;
  background: var(--color-bg);
}

/* ── Title row ── */
.builder-title-row {
  max-width: 1250px;
  margin: 0 auto;
  padding: 24px 20px 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 16px;
  flex-wrap: wrap;
}

.builder-title-row__left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.builder-title-row__right {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
}

.builder-back-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  border-radius: var(--radius-md);
  background: var(--color-surface);
  border: 1px solid var(--color-border);
  color: var(--color-text-secondary);
  text-decoration: none;
  flex-shrink: 0;
  transition: background var(--transition-fast);
}
.builder-back-btn:hover { background: var(--color-surface-alt); opacity: 1; }

.builder-title {
  font-size: var(--text-lg);
  font-weight: var(--fw-bold);
  color: var(--color-text-primary);
}

.builder-bank-btn {
  font-size: var(--text-xs);
  font-weight: var(--fw-semibold);
  padding: 6px 14px;
  border-radius: var(--radius-sm);
  border: 1px solid var(--color-border);
  background: var(--color-surface);
  color: var(--color-text-secondary);
  cursor: pointer;
  transition: all var(--transition-fast);
  font-family: inherit;
}

.builder-bank-btn--active {
  background: var(--color-primary);
  border-color: var(--color-primary);
  color: #fff;
}

/* ── Body layout ── */
.builder-body {
  max-width: 1250px;
  margin: 0 auto;
  padding: var(--space-5) var(--space-5) var(--space-10);
  display: flex;
  gap: var(--space-6);
  align-items: flex-start;
}

.builder-main {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  gap: var(--space-4);
}

/* ── Cards ── */
.builder-card {
  background: var(--color-surface);
  border: 1px solid var(--color-border);
  border-radius: var(--radius-lg);
  padding: var(--space-5);
}

.builder-card__head {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: var(--space-4);
  flex-wrap: wrap;
  gap: var(--space-3);
}

.builder-card__label {
  font-size: var(--text-xs);
  font-weight: var(--fw-semibold);
  color: var(--color-primary);
  text-transform: uppercase;
  letter-spacing: 0.08em;
  margin: 0;
}

/* ── Writing in EN/AR switcher ── */
/* .builder-lang-switcher {
  display: flex;
  align-items: center;
  gap: 8px;
}

.builder-lang-switcher__label {
  font-size: 11px;
  color: var(--color-text-muted);
  white-space: nowrap;
}

.builder-lang-tabs {
  display: flex;
  border: 1px solid var(--color-border);
  border-radius: var(--radius-sm);
  overflow: hidden;
}

.builder-lang-tab {
  padding: 4px 12px;
  font-size: 11px;
  font-weight: 700;
  background: var(--color-surface-alt);
  color: var(--color-text-muted);
  border: none;
  cursor: pointer;
  font-family: inherit;
  transition: all var(--transition-fast);
}

.builder-lang-tab--active {
  background: var(--color-primary);
  color: #fff;
} */

/* ── Fields ── */
.builder-field {
  margin-bottom: var(--space-4);
}

.builder-field__label {
  display: block;
  font-size: var(--text-xs);
  font-weight: var(--fw-medium);
  color: var(--color-text-secondary);
  margin-bottom: var(--space-2);
}

.builder-input {
  width: 100%;
  background: var(--color-surface-alt);
  border: 1px solid var(--color-border-input);
  border-radius: var(--radius-md);
  padding: var(--space-3) var(--space-4);
  font-size: var(--text-sm);
  color: var(--color-text-primary);
  font-family: inherit;
  transition: border-color var(--transition-fast);
  outline: none;
}

.builder-input:focus { border-color: var(--color-border-focus); }
.builder-input--textarea { resize: vertical; }

.builder-row {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: var(--space-4);
}

/* ── Toggles ── */
.builder-toggles {
  display: flex;
  flex-wrap: wrap;
  gap: var(--space-4);
  margin-top: var(--space-2);
}

.builder-toggle {
  display: flex;
  align-items: center;
  gap: var(--space-3);
  cursor: pointer;
}

.builder-toggle__track {
  width: 40px;
  height: 22px;
  border-radius: var(--radius-pill);
  background: var(--color-border);
  position: relative;
  transition: background var(--transition-fast);
  cursor: pointer;
  flex-shrink: 0;
}

.builder-toggle__track--on { background: var(--color-primary); }

.builder-toggle__thumb {
  position: absolute;
  top: 3px;
  left: 3px;
  width: 16px;
  height: 16px;
  background: #fff;
  border-radius: 50%;
  transition: transform var(--transition-fast);
}

.builder-toggle__thumb--on { transform: translateX(18px); }

.builder-toggle__label {
  font-size: var(--text-sm);
  color: var(--color-text-secondary);
}

/* ── Question card ── */
.builder-question {
  cursor: pointer;
  transition: border-color var(--transition-fast);
  padding: 0;
  overflow: hidden;
}

.builder-question--active { border-color: var(--color-primary); }

.builder-q-header {
  display: flex;
  align-items: center;
  gap: var(--space-2);
  padding: var(--space-3) var(--space-4);
  background: var(--color-surface-alt);
  border-bottom: 1px solid var(--color-border);
}

.builder-q-num {
  font-size: var(--text-xs);
  font-family: monospace;
  color: var(--color-text-muted);
  width: 20px;
}

.builder-q-type-badge {
  font-size: var(--text-xs);
  font-weight: var(--fw-semibold);
  padding: 2px 8px;
  border-radius: var(--radius-sm);
}

.builder-q-required {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: var(--text-xs);
  color: var(--color-text-muted);
  cursor: pointer;
}

.builder-q-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 28px;
  height: 28px;
  border-radius: var(--radius-sm);
  border: none;
  background: transparent;
  color: var(--color-text-muted);
  cursor: pointer;
  transition: background var(--transition-fast), color var(--transition-fast);
  font-size: 14px;
}

.builder-q-btn:hover { background: var(--color-surface-alt); color: var(--color-text-primary); }
.builder-q-btn:disabled { opacity: 0.3; cursor: not-allowed; }
.builder-q-btn--danger:hover { color: var(--color-danger); }

.builder-q-body { padding: var(--space-4) var(--space-5); }

.builder-q-input {
  width: 100%;
  background: transparent;
  border: 0;
  border-bottom: 1px solid var(--color-border);
  color: var(--color-text-primary);
  font-size: var(--text-base);
  font-weight: var(--fw-medium);
  padding-bottom: var(--space-2);
  margin-bottom: var(--space-4);
  outline: none;
  font-family: inherit;
  transition: border-color var(--transition-fast);
}

.builder-q-input:focus { border-color: var(--color-primary); }

.builder-q-options { display: flex; flex-direction: column; gap: var(--space-2); }

.builder-q-option {
  display: flex;
  align-items: center;
  gap: var(--space-2);
}

.builder-q-option-dot {
  width: 14px;
  height: 14px;
  border-radius: 50%;
  border: 1px solid var(--color-border-input);
  flex-shrink: 0;
}

.builder-q-option-dot--square { border-radius: var(--radius-sm); }

.builder-q-option-input {
  flex: 1;
  background: transparent;
  border: 0;
  border-bottom: 1px solid var(--color-border-light);
  color: var(--color-text-secondary);
  font-size: var(--text-sm);
  padding: 4px 0;
  outline: none;
  font-family: inherit;
}

.builder-q-option-input:focus { border-color: var(--color-primary); }

.builder-q-option-del {
  color: var(--color-text-muted);
  font-size: var(--text-xs);
  background: transparent;
  border: none;
  cursor: pointer;
  padding: 2px;
}
.builder-q-option-del:hover { color: var(--color-danger); }

.builder-add-option {
  font-size: var(--text-xs);
  font-weight: var(--fw-semibold);
  color: var(--color-primary);
  background: transparent;
  border: none;
  cursor: pointer;
  margin-top: var(--space-1);
  padding: 0;
}

.builder-yes-no { display: flex; gap: var(--space-3); }

.builder-yes-no__yes {
  padding: var(--space-2) var(--space-4);
  border-radius: var(--radius-md);
  background: var(--color-success-soft);
  color: var(--color-success);
  font-size: var(--text-sm);
  font-weight: var(--fw-medium);
}

.builder-yes-no__no {
  padding: var(--space-2) var(--space-4);
  border-radius: var(--radius-md);
  background: var(--color-danger-soft);
  color: var(--color-danger);
  font-size: var(--text-sm);
  font-weight: var(--fw-medium);
}

.builder-rating { display: flex; align-items: center; gap: var(--space-4); }

.builder-rating__dots { display: flex; gap: 4px; flex-wrap: wrap; }

.builder-rating__dot {
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--color-surface-alt);
  border: 1px solid var(--color-border);
  border-radius: var(--radius-sm);
  font-size: var(--text-xs);
  color: var(--color-text-muted);
}

.builder-rating__config { display: flex; align-items: center; gap: var(--space-2); }

.builder-rating__config-label { font-size: var(--text-xs); color: var(--color-text-muted); }

.builder-rating__select {
  background: var(--color-surface-alt);
  border: 1px solid var(--color-border-input);
  border-radius: var(--radius-sm);
  color: var(--color-text-primary);
  font-size: var(--text-xs);
  padding: 3px 8px;
  outline: none;
}

.builder-text-preview {
  font-size: var(--text-sm);
  color: var(--color-text-muted);
  font-style: italic;
  padding: var(--space-3);
  border: 1px dashed var(--color-border);
  border-radius: var(--radius-md);
}

/* ── Add question row ── */
.builder-add-q {
  background: var(--color-surface);
  border: 1px dashed var(--color-border);
  border-radius: var(--radius-lg);
  padding: var(--space-5);
}

.builder-add-q__label {
  font-size: var(--text-xs);
  color: var(--color-text-muted);
  margin-bottom: var(--space-3);
}

.builder-add-q__types { display: flex; flex-wrap: wrap; gap: var(--space-2); }

/* ── Type buttons ── */
.builder-type-btn {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: var(--text-xs);
  font-weight: var(--fw-semibold);
  padding: 6px 12px;
  border-radius: var(--radius-sm);
  border: 1px solid;
  cursor: pointer;
  font-family: inherit;
  transition: opacity var(--transition-fast);
}
.builder-type-btn:hover { opacity: 0.85; }
.builder-type-btn__icon { font-size: 13px; }

.builder-type-btn--multiple_choice { background: var(--color-info-soft);    color: var(--color-info);    border-color: var(--color-info); }
.builder-type-btn--multi_select    { background: var(--color-primary-soft); color: var(--color-primary); border-color: var(--color-primary); }
.builder-type-btn--yes_no          { background: var(--color-success-soft); color: var(--color-success); border-color: var(--color-success); }
.builder-type-btn--rating          { background: var(--color-warning-soft); color: var(--color-warning); border-color: var(--color-warning); }
.builder-type-btn--text            { background: var(--color-surface-alt);  color: var(--color-text-secondary); border-color: var(--color-border); }

.builder-q-type-badge--multiple_choice { background: var(--color-info-soft);    color: var(--color-info); }
.builder-q-type-badge--multi_select    { background: var(--color-primary-soft); color: var(--color-primary); }
.builder-q-type-badge--yes_no          { background: var(--color-success-soft); color: var(--color-success); }
.builder-q-type-badge--rating          { background: var(--color-warning-soft); color: var(--color-warning); }
.builder-q-type-badge--text            { background: var(--color-surface-alt);  color: var(--color-text-secondary); }

/* ── Bank panel ── */
.builder-bank {
  width: 320px;
  flex-shrink: 0;
  position: sticky;
  top: 60px;
  max-height: calc(100vh - 80px);
  overflow-y: auto;
  background: var(--color-surface);
  border: 1px solid var(--color-border);
  border-radius: var(--radius-lg);
}

.builder-bank__head {
  padding: var(--space-4);
  border-bottom: 1px solid var(--color-border);
  position: sticky;
  top: 0;
  background: var(--color-surface);
  z-index: 1;
}

.builder-bank__title {
  font-size: var(--text-sm);
  font-weight: var(--fw-semibold);
  color: var(--color-text-primary);
  margin-bottom: var(--space-3);
}

.builder-bank__search {
  width: 100%;
  background: var(--color-surface-alt);
  border: 1px solid var(--color-border-input);
  border-radius: var(--radius-sm);
  padding: var(--space-2) var(--space-3);
  font-size: var(--text-xs);
  color: var(--color-text-primary);
  outline: none;
  font-family: inherit;
}

.builder-bank__body { padding: var(--space-3); }

.builder-bank__section { margin-bottom: var(--space-4); }

.builder-bank__section-head {
  font-size: var(--text-xs);
  font-weight: var(--fw-semibold);
  text-transform: uppercase;
  letter-spacing: 0.08em;
  padding: var(--space-2) var(--space-3);
  border-radius: var(--radius-sm);
  margin-bottom: var(--space-2);
}

.builder-bank__section-head--teal  { background: var(--color-primary-soft); color: var(--color-primary); }
.builder-bank__section-head--blue  { background: var(--color-info-soft);    color: var(--color-info); }
.builder-bank__section-head--coral { background: var(--color-danger-soft);  color: var(--color-danger); }
.builder-bank__section-head--gray  { background: var(--color-surface-alt);  color: var(--color-text-secondary); }

.builder-bank__item {
  display: flex;
  align-items: flex-start;
  gap: var(--space-2);
  padding: var(--space-2) var(--space-3);
  border-radius: var(--radius-sm);
  cursor: pointer;
  transition: background var(--transition-fast);
  margin-bottom: 2px;
}
.builder-bank__item:hover { background: var(--color-primary-soft); }

.builder-bank__item-type {
  font-size: 10px;
  font-weight: var(--fw-semibold);
  padding: 2px 6px;
  border-radius: var(--radius-sm);
  flex-shrink: 0;
  border: 1px solid;
}

.builder-bank__item-q {
  font-size: var(--text-xs);
  color: var(--color-text-secondary);
  flex: 1;
  line-height: 1.4;
}

.builder-bank__item-plus {
  font-size: var(--text-md);
  font-weight: var(--fw-bold);
  color: var(--color-primary);
  flex-shrink: 0;
  line-height: 1;
}

/* ── Mobile ── */
@media (max-width: 640px) {
  .builder-bank {
    width: 100%;
    position: static;
    max-height: 50vh;
  }
  .builder-body { flex-direction: column; }
}

/* ── Save to bank ── */
.builder-q-save-bank {
  display: flex;
  align-items: center;
  gap: var(--space-3);
  flex-wrap: wrap;
  margin-top: var(--space-4);
  padding-top: var(--space-3);
  border-top: 1px dashed var(--color-border);
}

.builder-q-save-bank__label {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: var(--text-xs);
  color: var(--color-text-muted);
  cursor: pointer;
}

.builder-q-save-bank__label input[type="checkbox"] {
  accent-color: var(--color-primary);
  cursor: pointer;
}

.builder-q-save-bank__select {
  font-size: var(--text-xs);
  background: var(--color-surface-alt);
  border: 1px solid var(--color-border-input);
  border-radius: var(--radius-sm);
  color: var(--color-text-primary);
  padding: 4px 8px;
  outline: none;
  font-family: inherit;
}

/* ── Personal bank item badge + delete ── */
.builder-bank__item-personal {
  font-size: 9px;
  font-weight: var(--fw-bold);
  background: var(--color-primary-soft);
  color: var(--color-primary);
  border-radius: var(--radius-pill);
  padding: 1px 6px;
  flex-shrink: 0;
  white-space: nowrap;
}

.builder-bank__item-del {
  font-size: 10px;
  color: var(--color-text-muted);
  background: transparent;
  border: none;
  cursor: pointer;
  padding: 2px 4px;
  border-radius: var(--radius-sm);
  flex-shrink: 0;
  transition: color var(--transition-fast), background var(--transition-fast);
}

.builder-bank__item-del:hover {
  color: var(--color-danger);
  background: var(--color-danger-soft);
}
</style>