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

      <!-- PROGRESS BAR (sticky top) -->
      <div class="take-progress-bar">
        <div class="take-progress-bar__inner">
          <div
            class="take-progress-bar__fill"
            :style="`width: ${progressPct}%`"
          ></div>
        </div>
      </div>

      <div class="take-body">

        <!-- ── Survey Header ── -->
        <div class="take-survey-header">
          <div class="take-survey-header__meta">
            <span class="take-survey-header__count">
              <i class="ti ti-list-check"></i>
              {{ survey.questions.length }}
              {{ locale === 'ar' ? 'سؤال' : 'questions' }}
            </span>
            <span v-if="survey.closes_at" class="take-survey-header__closes">
              <i class="ti ti-clock"></i>
              {{ locale === 'ar' ? 'ينتهي في' : 'Closes' }}
              {{ formatDate(survey.closes_at) }}
            </span>
          </div>

          <h1 class="take-survey-header__title" :dir="locale === 'ar' ? 'rtl' : 'ltr'">
            {{ locale === 'ar' && survey.title_ar ? survey.title_ar : survey.title_en }}
          </h1>

          <div
            v-if="survey.description_en || survey.description_ar"
            class="take-survey-header__desc"
            :dir="locale === 'ar' ? 'rtl' : 'ltr'"
          >
            {{ locale === 'ar' && survey.description_ar ? survey.description_ar : survey.description_en }}
          </div>
        </div>

        <!-- ── Questions ── -->
        <div class="take-questions">
          <div
            v-for="(q, qi) in survey.questions"
            :key="q.id"
            class="take-q-card"
            :class="{ 'take-q-card--error': errors[q.id] }"
          >
            <!-- Question text -->
            <div class="take-q-label" :dir="locale === 'ar' ? 'rtl' : 'ltr'">
              <span class="take-q-num">{{ qi + 1 }}</span>
              <span class="take-q-text">
                {{ locale === 'ar' && q.question_ar ? q.question_ar : q.question_en }}
                <span v-if="q.is_required" class="take-q-required">*</span>
              </span>
            </div>

            <p v-if="errors[q.id]" class="take-q-error">
              {{ locale === 'ar' ? 'هذا السؤال إلزامي.' : 'This question is required.' }}
            </p>

            <!-- ─── Multiple choice ─── -->
            <div v-if="q.type === 'multiple_choice'" class="take-options">
              <div
                v-for="(opt, oi) in (locale === 'ar' && q.options_ar?.length ? q.options_ar : q.options_en)"
                :key="oi"
                @click="answers[q.id] = oi"
                :class="{ 'take-option--selected': answers[q.id] === oi }"
                class="take-option"
                :dir="locale === 'ar' ? 'rtl' : 'ltr'"
              >
                <div class="take-option__dot" :class="{ 'take-option__dot--selected': answers[q.id] === oi }">
                  <div v-if="answers[q.id] === oi" class="take-option__dot-inner"></div>
                </div>
                <span>{{ opt }}</span>
              </div>
            </div>

            <!-- ─── Multi-select ─── -->
            <div v-else-if="q.type === 'multi_select'" class="take-options">
              <div
                v-for="(opt, oi) in (locale === 'ar' && q.options_ar?.length ? q.options_ar : q.options_en)"
                :key="oi"
                @click="toggleMulti(q.id, oi)"
                :class="{ 'take-option--selected': isMultiSelected(q.id, oi) }"
                class="take-option take-option--multi"
                :dir="locale === 'ar' ? 'rtl' : 'ltr'"
              >
                <div class="take-option__check" :class="{ 'take-option__check--selected': isMultiSelected(q.id, oi) }">
                  <i v-if="isMultiSelected(q.id, oi)" class="ti ti-check" style="font-size:11px;"></i>
                </div>
                <span>{{ opt }}</span>
              </div>
            </div>

            <!-- ─── Yes / No ─── -->
            <div v-else-if="q.type === 'yes_no'" class="take-yes-no">
              <button
                @click="answers[q.id] = 'yes'"
                :class="{ 'take-yes-no__yes--selected': answers[q.id] === 'yes' }"
                class="take-yes-no__yes"
              >
                ✓ {{ locale === 'ar' ? 'نعم' : 'Yes' }}
              </button>
              <button
                @click="answers[q.id] = 'no'"
                :class="{ 'take-yes-no__no--selected': answers[q.id] === 'no' }"
                class="take-yes-no__no"
              >
                ✕ {{ locale === 'ar' ? 'لا' : 'No' }}
              </button>
            </div>

            <!-- ─── Rating ─── -->
            <div v-else-if="q.type === 'rating'" class="take-rating">
              <div class="take-rating__dots">
                <button
                  v-for="n in ratingRange(q)"
                  :key="n"
                  @click="answers[q.id] = n"
                  :class="{ 'take-rating__dot--selected': answers[q.id] === n }"
                  class="take-rating__dot"
                >{{ n }}</button>
              </div>
              <div class="take-rating__labels">
                <span>{{ locale === 'ar' ? 'منخفض' : 'Low' }}</span>
                <span>{{ locale === 'ar' ? 'مرتفع' : 'High' }}</span>
              </div>
            </div>

            <!-- ─── Text ─── -->
            <div v-else-if="q.type === 'text'">
              <textarea
                v-model="answers[q.id]"
                rows="4"
                :placeholder="locale === 'ar' ? 'اكتب إجابتك هنا...' : 'Type your answer here...'"
                :dir="locale === 'ar' ? 'rtl' : 'ltr'"
                class="take-textarea"
              ></textarea>
            </div>

          </div>
        </div>

        <!-- ── Submit ── -->
        <div class="take-submit-area">
          <p v-if="hasErrors" class="take-submit-error">
            {{ locale === 'ar'
              ? 'يرجى الإجابة على جميع الأسئلة الإلزامية.'
              : 'Please answer all required questions.' }}
          </p>
          <button
            @click="submitSurvey"
            :disabled="submitting"
            class="take-submit-btn"
          >
            <span v-if="submitting">
              {{ locale === 'ar' ? 'جارٍ الإرسال…' : 'Submitting…' }}
            </span>
            <span v-else>
              {{ locale === 'ar' ? 'إرسال الإجابات ←' : 'Submit Response →' }}
            </span>
          </button>
          <p class="take-submit-note">
            {{ survey.anonymous_responses
              ? (locale === 'ar' ? 'إجاباتك مجهولة الهوية.' : 'Your response is anonymous.')
              : (locale === 'ar' ? 'سيتم تسجيل إجاباتك باسمك.' : 'Your response will be recorded with your name.') }}
          </p>
        </div>

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

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

const props = defineProps({
  survey: { type: Object, required: true },
})

const authStore = useAuthStore()
const locale     = computed(() => authStore.locale)

const answers    = reactive({})
const errors     = reactive({})
const submitting = ref(false)
const hasErrors  = ref(false)

// ── Progress ────────────────────────────────────────────────────
const progressPct = computed(() => {
  const total    = props.survey.questions.length
  if (!total) return 0
  const answered = props.survey.questions.filter(q => {
    const a = answers[q.id]
    if (Array.isArray(a)) return a.length > 0
    return a !== undefined && a !== '' && a !== null
  }).length
  return Math.round((answered / total) * 100)
})

// ── Rating range ────────────────────────────────────────────────
const ratingRange = (q) => {
  const min = q.rating_min ?? 1
  const max = q.rating_max ?? 5
  return Array.from({ length: max - min + 1 }, (_, i) => min + i)
}

// ── Multi-select helpers ────────────────────────────────────────
const toggleMulti = (qId, oi) => {
  if (!answers[qId]) answers[qId] = []
  const idx = answers[qId].indexOf(oi)
  if (idx === -1) answers[qId].push(oi)
  else answers[qId].splice(idx, 1)
}

const isMultiSelected = (qId, oi) => {
  return Array.isArray(answers[qId]) && answers[qId].includes(oi)
}

// ── Format date ─────────────────────────────────────────────────
const formatDate = (d) => {
  if (!d) return ''
  return new Date(d).toLocaleDateString(locale === 'ar' ? 'ar-EG' : 'en-GB', {
    day: '2-digit', month: 'short', year: 'numeric',
  })
}

// ── Submit ───────────────────────────────────────────────────────
const submitSurvey = () => {
  let valid = true
  hasErrors.value = false

  props.survey.questions.forEach(q => {
    errors[q.id] = false
    if (!q.is_required) return

    const a = answers[q.id]
    const empty = a === undefined || a === null || a === '' || (Array.isArray(a) && a.length === 0)

    if (empty) {
      errors[q.id] = true
      valid = false
    }
  })

  if (!valid) {
    hasErrors.value = true
    window.scrollTo({ top: 0, behavior: 'smooth' })
    return
  }

  submitting.value = true

  router.post(
    route('member.surveys.respond', props.survey.id),
    { answers },
    { onFinish: () => { submitting.value = false } }
  )
}
</script>

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

/* ── Progress bar ── */
.take-progress-bar {
  position: sticky;
  top: 0;
  z-index: var(--z-dropdown);
  background: var(--color-header-bg);
  padding: 0 0 3px;
}

.take-progress-bar__inner {
  height: 3px;
  background: rgba(255,255,255,0.1);
}

.take-progress-bar__fill {
  height: 100%;
  background: var(--color-primary);
  transition: width 0.4s ease;
}

/* ── Body ── */
.take-body {
  max-width: 680px;
  margin: 0 auto;
  padding: var(--space-6) var(--space-5) var(--space-12);
}

/* ── Survey header ── */
.take-survey-header {
  margin-bottom: var(--space-6);
}

.take-survey-header__meta {
  display: flex;
  align-items: center;
  gap: var(--space-4);
  margin-bottom: var(--space-3);
}

.take-survey-header__count,
.take-survey-header__closes {
  display: flex;
  align-items: center;
  gap: var(--space-1);
  font-size: var(--text-xs);
  color: var(--color-text-muted);
}

.take-survey-header__count i,
.take-survey-header__closes i {
  font-size: 13px;
  color: var(--color-primary);
}

.take-survey-header__title {
  font-size: var(--text-xl);
  font-weight: var(--fw-bold);
  color: var(--color-text-primary);
  line-height: 1.3;
  margin-bottom: var(--space-3);
}

.take-survey-header__desc {
  background: var(--color-surface);
  border: 1px solid var(--color-border);
  border-left: 3px solid var(--color-primary);
  border-radius: var(--radius-md);
  padding: var(--space-4);
  font-size: var(--text-sm);
  color: var(--color-text-secondary);
  line-height: 1.7;
}

/* ── Questions ── */
.take-questions {
  display: flex;
  flex-direction: column;
  gap: var(--space-4);
  margin-bottom: var(--space-6);
}

.take-q-card {
  background: var(--color-surface);
  border: 1px solid var(--color-border);
  border-radius: var(--radius-lg);
  padding: var(--space-5);
  transition: border-color var(--transition-fast);
}

.take-q-card--error {
  border-color: var(--color-danger);
}

.take-q-label {
  display: flex;
  align-items: flex-start;
  gap: var(--space-3);
  margin-bottom: var(--space-4);
}

.take-q-num {
  font-size: var(--text-xs);
  font-family: monospace;
  color: var(--color-text-muted);
  background: var(--color-surface-alt);
  width: 24px;
  height: 24px;
  border-radius: var(--radius-sm);
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  margin-top: 2px;
}

.take-q-text {
  font-size: var(--text-base);
  font-weight: var(--fw-medium);
  color: var(--color-text-primary);
  line-height: 1.5;
  flex: 1;
}

.take-q-required {
  color: var(--color-danger);
  margin-left: 3px;
}

.take-q-error {
  font-size: var(--text-xs);
  color: var(--color-danger);
  margin-bottom: var(--space-3);
  margin-top: calc(-1 * var(--space-2));
}

/* ── Options (MCQ / Multi) ── */
.take-options {
  display: flex;
  flex-direction: column;
  gap: var(--space-2);
}

.take-option {
  display: flex;
  align-items: center;
  gap: var(--space-3);
  padding: var(--space-3) var(--space-4);
  border: 1px solid var(--color-border);
  border-radius: var(--radius-md);
  cursor: pointer;
  font-size: var(--text-sm);
  color: var(--color-text-secondary);
  transition: border-color var(--transition-fast), background var(--transition-fast), color var(--transition-fast);
  background: var(--color-surface-alt);
}

.take-option:hover {
  border-color: var(--color-primary);
  color: var(--color-text-primary);
}

.take-option--selected {
  border-color: var(--color-primary);
  background: var(--color-primary-soft);
  color: var(--color-text-primary);
}

.take-option__dot {
  width: 16px;
  height: 16px;
  border-radius: 50%;
  border: 2px solid var(--color-border-input);
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: border-color var(--transition-fast);
}

.take-option__dot--selected {
  border-color: var(--color-primary);
}

.take-option__dot-inner {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: var(--color-primary);
}

.take-option__check {
  width: 16px;
  height: 16px;
  border-radius: var(--radius-sm);
  border: 2px solid var(--color-border-input);
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: border-color var(--transition-fast), background var(--transition-fast);
}

.take-option__check--selected {
  border-color: var(--color-primary);
  background: var(--color-primary);
  color: #fff;
}

/* ── Yes / No ── */
.take-yes-no {
  display: flex;
  gap: var(--space-3);
}

.take-yes-no__yes,
.take-yes-no__no {
  flex: 1;
  padding: var(--space-3) var(--space-4);
  border-radius: var(--radius-md);
  border: 1px solid var(--color-border);
  font-size: var(--text-sm);
  font-weight: var(--fw-medium);
  cursor: pointer;
  transition: all var(--transition-fast);
  background: var(--color-surface-alt);
  color: var(--color-text-secondary);
  text-align: center;
}

.take-yes-no__yes:hover       { border-color: var(--color-success); color: var(--color-success); }
.take-yes-no__yes--selected   { background: var(--color-success-soft); border-color: var(--color-success); color: var(--color-success); }
.take-yes-no__no:hover        { border-color: var(--color-danger); color: var(--color-danger); }
.take-yes-no__no--selected    { background: var(--color-danger-soft); border-color: var(--color-danger); color: var(--color-danger); }

/* ── Rating ── */
.take-rating__dots {
  display: flex;
  flex-wrap: wrap;
  gap: var(--space-2);
  margin-bottom: var(--space-2);
}

.take-rating__dot {
  width: 42px;
  height: 42px;
  border-radius: var(--radius-md);
  border: 1px solid var(--color-border-input);
  background: var(--color-surface-alt);
  color: var(--color-text-secondary);
  font-size: var(--text-sm);
  font-weight: var(--fw-medium);
  cursor: pointer;
  transition: all var(--transition-fast);
  display: flex;
  align-items: center;
  justify-content: center;
}

.take-rating__dot:hover {
  border-color: var(--color-warning);
  color: var(--color-warning);
}

.take-rating__dot--selected {
  background: var(--color-warning);
  border-color: var(--color-warning);
  color: #fff;
  font-weight: var(--fw-bold);
}

.take-rating__labels {
  display: flex;
  justify-content: space-between;
  font-size: var(--text-xs);
  color: var(--color-text-muted);
}

/* ── Text ── */
.take-textarea {
  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;
  line-height: 1.6;
  resize: vertical;
  outline: none;
  transition: border-color var(--transition-fast);
}

.take-textarea:focus {
  border-color: var(--color-border-focus);
}

/* ── Submit area ── */
.take-submit-area {
  display: flex;
  flex-direction: column;
  gap: var(--space-3);
  align-items: center;
}

.take-submit-error {
  font-size: var(--text-sm);
  color: var(--color-danger);
  font-weight: var(--fw-medium);
}

.take-submit-btn {
  width: 100%;
  padding: var(--space-4);
  background: var(--color-primary);
  color: #fff;
  border: none;
  border-radius: var(--radius-lg);
  font-size: var(--text-base);
  font-weight: var(--fw-semibold);
  cursor: pointer;
  transition: opacity var(--transition-fast), box-shadow var(--transition-fast);
  box-shadow: var(--shadow-button);
  font-family: inherit;
}

.take-submit-btn:hover:not(:disabled) {
  opacity: 0.9;
  box-shadow: 0 6px 20px rgba(29,158,117,0.4);
}

.take-submit-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.take-submit-note {
  font-size: var(--text-xs);
  color: var(--color-text-muted);
  text-align: center;
}
</style>
