<script setup>
import { ExternalLink, MapPin, Search, CarFront } from "lucide-vue-next";
import { formatPublicMoney } from '~/content/utils';
import { wizardIcons } from "~/components/city-rental/icons";
import { normalizeCityRentalHref } from "~/components/city-rental/link-utils";
import { scoreCityRentalVehicle } from "~/components/city-rental/vehicle-adapter";

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

const { locale } = usePublicLocale();
const ui = usePublicUi();
const wizard = computed(() => props.wizard || {});
const wizardUi = computed(() => ui.value?.cityRentalWizard || {});
const checkAvailabilityUrl = computed(() =>
  normalizeCityRentalHref(wizard.value?.checkAvailabilityUrl),
);
const askWhatsappUrl = computed(() =>
  normalizeCityRentalHref(wizard.value?.askInWhatsappUrl),
);
const labels = computed(() => ({
  eyebrow: wizardUi.value.badgeLabel,
  title: wizardUi.value.title,
  estDaily: wizardUi.value.estDailyLabel,
  deposit: wizardUi.value.depositLabel,
  checkAvailability: wizardUi.value.checkAvailabilityLabel,
  askWhatsapp: wizardUi.value.askInWhatsappLabel,
  alsoConsider: wizardUi.value.alsoConsiderLabel,
  bestMatch: wizardUi.value.bestMatchLabel,
  route: wizardUi.value.routeQuestionLabel,
  passengers: wizardUi.value.passengersQuestionLabel,
  priority: wizardUi.value.priorityQuestionLabel,
  perDay: wizardUi.value.perDayLabel,
}));
const answers = reactive({
  route: '',
  passengers: '',
  priority: '',
});

const sourceCars = computed(() => Array.isArray(wizard.value?.cars) ? wizard.value.cars : []);

function normalizeTag(tag) {
  if (typeof tag === 'string') {
    return {
      label: tag,
      iconKey: '',
      color: 'bg-slate-50 text-slate-600 border-slate-200',
    };
  }

  return tag || {};
}

watch(
  () => props.wizard?.questions,
  (questions) => {
    const byId = new Map((questions || []).map((question) => [question.id, question]));

    answers.route = byId.get('route')?.options?.[0] || '';
    answers.passengers = byId.get('passengers')?.options?.[0] || '';
    answers.priority = byId.get('priority')?.options?.[0] || '';
  },
  { immediate: true },
);

function scoreCar(car) {
  return scoreCityRentalVehicle(car, answers);
}

function vehicleDetailUrl(vehicle) {
  return normalizeCityRentalHref(vehicle?.path || vehicle?.ctaUrl || '');
}

const sortedCars = computed(() => {
  return [...sourceCars.value]
    .map((car) => ({ ...car, score: scoreCar(car) }))
    .sort((left, right) => right.score - left.score);
});

const primary = computed(() => sortedCars.value[0] || null);
const alternatives = computed(() => sortedCars.value.slice(1, 3));
</script>

<template>
  <section class="mb-24">
    <div
      class="bg-white border border-slate-200 shadow-sm rounded-3xl sm:rounded-[2.5rem] p-5 sm:p-6 lg:p-10 relative overflow-hidden"
    >
      <div
        class="absolute top-0 right-0 w-[600px] h-[600px] bg-[radial-gradient(circle_at_top_right,rgba(255,95,0,0.04),transparent_70%)] pointer-events-none"
      />

      <div
        class="flex flex-col xl:flex-row gap-8 sm:gap-10 xl:gap-14 items-stretch relative z-10"
      >
        <div class="w-full xl:w-[440px] shrink-0 xl:py-4">
          <div
            class="inline-flex items-center gap-2 px-3 py-1 bg-slate-50 text-slate-600 rounded-full text-[10px] font-bold uppercase tracking-widest mb-6 border border-slate-200 shadow-sm"
          >
            <Search class="w-3.5 h-3.5 text-brand-orange" />
            {{ labels.eyebrow }}
          </div>
          <h2
            class="text-3xl md:text-4xl font-display font-bold text-slate-900 mb-6 sm:mb-8 leading-tight tracking-tight"
          >
            {{ labels.title }}
          </h2>

          <div class="space-y-6 sm:space-y-8">
            <div v-for="question in wizard.questions" :key="question.id">
              <label
                class="text-[11px] font-bold text-slate-400 uppercase tracking-wider flex items-center gap-2 mb-3"
              >
                <component
                  :is="wizardIcons[question.iconKey] || MapPin"
                  class="w-3.5 h-3.5"
                />
                {{
                  question.id === 'route'
                    ? labels.route
                    : question.id === 'passengers'
                      ? labels.passengers
                      : labels.priority
                }}
              </label>
              <div class="flex flex-wrap gap-1.5 sm:gap-2">
                <button
                  v-for="opt in question.options"
                  :key="opt"
                  type="button"
                  :class="[
                    'px-3 sm:px-4 py-2 sm:py-2.5 rounded-xl text-[13px] sm:text-sm font-medium transition-all border',
                    answers[question.id] === opt
                      ? question.id === 'priority'
                        ? 'bg-brand-orange border-brand-orange text-white shadow-md shadow-brand-orange/20 scale-[1.02]'
                        : 'bg-slate-900 border-slate-900 text-white shadow-md scale-[1.02]'
                      : 'bg-white border-slate-200 text-slate-600 hover:border-slate-300 hover:bg-slate-50',
                  ]"
                  @click="answers[question.id] = opt"
                >
                  {{ opt }}
                </button>
              </div>
            </div>
          </div>
        </div>

        <div
          class="flex-1 w-full bg-slate-50/50 rounded-2xl sm:rounded-[2.5rem] border border-slate-100 p-4 sm:p-6 md:p-8 flex flex-col justify-between"
        >
          <div
            v-if="primary"
            :key="primary.id"
            class="animate-in fade-in zoom-in-95 duration-500"
          >
            <div
              class="text-[10px] font-bold uppercase tracking-widest text-slate-400 mb-4 sm:mb-6 flex items-center justify-between"
            >
              <div class="flex items-center gap-2">
                <div class="w-2 h-2 rounded-full bg-green-500 animate-pulse" />
                {{ labels.bestMatch }}
              </div>
            </div>

            <div
              class="bg-white rounded-2xl sm:rounded-[2rem] p-5 sm:p-8 border border-slate-200 shadow-xl shadow-slate-200/40 relative overflow-hidden mb-6"
            >
              <div
                class="absolute top-0 right-0 w-24 h-24 sm:w-32 sm:h-32 bg-slate-50 rounded-bl-[80px] pointer-events-none"
              />
              <div
                class="flex flex-row gap-4 sm:gap-8 items-center sm:items-start relative z-10 mb-6 sm:mb-8"
              >
                <NuxtLink
                  v-if="vehicleDetailUrl(primary)"
                  :to="vehicleDetailUrl(primary)"
                  class="w-16 h-16 sm:w-28 sm:h-28 bg-slate-50 rounded-2xl sm:rounded-3xl flex items-center justify-center shrink-0 border border-slate-100 shadow-inner overflow-hidden group"
                  :aria-label="`Open ${primary.name} details`"
                >
                  <img
                    v-if="primary.image || primary.heroImage"
                    :src="primary.image || primary.heroImage"
                    :alt="primary.name"
                    class="w-full h-full object-contain p-2 sm:p-3 transition-transform duration-500 group-hover:scale-105"
                    loading="eager"
                  />
                  <component
                    v-else
                    :is="wizardIcons[primary.iconKey] || CarFront"
                    :class="[
                      'w-10 h-10 md:w-12 md:h-12',
                      primary.iconColor || 'text-brand-orange',
                    ]"
                    stroke-width="1"
                  />
                </NuxtLink>
                <div
                  v-else
                  class="w-16 h-16 sm:w-28 sm:h-28 bg-slate-50 rounded-2xl sm:rounded-3xl flex items-center justify-center shrink-0 border border-slate-100 shadow-inner overflow-hidden"
                >
                  <img
                    v-if="primary.image || primary.heroImage"
                    :src="primary.image || primary.heroImage"
                    :alt="primary.name"
                    class="w-full h-full object-contain p-2 sm:p-3"
                    loading="eager"
                  />
                  <component
                    v-else
                    :is="wizardIcons[primary.iconKey] || CarFront"
                    :class="[
                      'w-10 h-10 md:w-12 md:h-12',
                      primary.iconColor || 'text-brand-orange',
                    ]"
                    stroke-width="1"
                  />
                </div>
                <div class="flex-1">
                  <div class="flex flex-wrap gap-1.5 sm:gap-2 mb-2 sm:mb-3">
                    <span
                      v-for="tag in primary.tags"
                      :key="normalizeTag(tag).label || tag"
                      class="bg-slate-100 text-slate-600 text-[9px] sm:text-[10px] font-bold uppercase tracking-wider px-2 py-1 rounded-md"
                    >
                      {{ normalizeTag(tag).label || tag }}
                    </span>
                  </div>
                  <NuxtLink
                    v-if="vehicleDetailUrl(primary)"
                    :to="vehicleDetailUrl(primary)"
                    class="group inline-flex items-center gap-2 text-xl sm:text-3xl font-display font-bold text-slate-900 leading-tight sm:mb-3 hover:text-brand-orange transition-colors"
                  >
                    {{ primary.name }}
                    <ExternalLink class="w-4 h-4 sm:w-5 sm:h-5 text-slate-300 group-hover:text-brand-orange transition-colors" />
                  </NuxtLink>
                  <h3
                    v-else
                    class="text-xl sm:text-3xl font-display font-bold text-slate-900 leading-tight sm:mb-3"
                  >
                    {{ primary.name }}
                  </h3>
                  <p
                    class="hidden sm:block text-sm text-slate-500 leading-relaxed max-w-md"
                  >
                    {{ primary.desc }}
                  </p>
                </div>
              </div>

              <p
                class="sm:hidden text-[13px] text-slate-500 leading-relaxed mb-6 block relative z-10"
              >
                {{ primary.desc }}
              </p>

              <div
                class="grid grid-cols-2 gap-4 pt-5 sm:pt-6 border-t border-slate-100 relative z-10 mb-6 sm:mb-8"
              >
                <div>
                  <div
                    class="text-[10px] sm:text-xs font-bold text-slate-400 uppercase tracking-widest mb-0.5 sm:mb-1"
                  >
                    {{ labels.estDaily }}
                  </div>
                  <div
                    class="font-bold font-display text-xl sm:text-2xl text-slate-900"
                  >
                    {{ formatPublicMoney(primary.price, primary.currency || 'USD', locale.value, { forceFraction: false }) }}
                  </div>
                </div>
                <div>
                  <div
                    class="text-[10px] sm:text-xs font-bold text-slate-400 uppercase tracking-widest mb-0.5 sm:mb-1"
                  >
                    {{ labels.deposit }}
                  </div>
                  <div
                    class="font-bold font-display text-xl sm:text-2xl text-slate-900"
                  >
                      {{
                        primary.deposit == null
                          ? '—'
                          : formatPublicMoney(primary.deposit, primary.currency || 'USD', locale.value, { forceFraction: false })
                      }}
                  </div>
                </div>
              </div>

              <div
                class="flex flex-col sm:flex-row gap-2.5 sm:gap-3 relative z-10"
              >
                <NuxtLink
                  v-if="checkAvailabilityUrl"
                  :to="checkAvailabilityUrl"
                  class="flex-1 bg-slate-900 text-white font-bold py-3.5 sm:py-4 rounded-xl text-[13px] sm:text-sm hover:bg-slate-800 transition-colors shadow-lg shadow-slate-900/20 text-center"
                >
                  {{ labels.checkAvailability }}
                </NuxtLink>
                <a
                  v-if="askWhatsappUrl"
                  :href="askWhatsappUrl"
                  target="_blank"
                  rel="noreferrer"
                  class="flex-1 bg-[#25D366]/10 sm:bg-[#25D366]/20 text-[#25D366] font-bold py-3.5 sm:py-4 rounded-xl text-[13px] sm:text-sm hover:bg-[#25D366]/30 transition-colors text-center border sm:border border-[#25D366]/30"
                >
                  {{ labels.askWhatsapp }}
                </a>
              </div>
            </div>
          </div>

          <div
            class="animate-in fade-in slide-in-from-bottom-4 duration-500 delay-150"
          >
            <div
              class="text-[11px] sm:text-xs font-bold text-slate-400 mb-3 sm:mb-4 px-1 sm:px-2 tracking-wide uppercase"
            >
              {{ labels.alsoConsider }}
            </div>
            <div class="flex flex-col sm:grid sm:grid-cols-2 gap-2 sm:gap-3">
              <template v-for="alt in alternatives" :key="alt.id">
                <NuxtLink
                  v-if="vehicleDetailUrl(alt)"
                  :to="vehicleDetailUrl(alt)"
                  class="bg-white p-3 sm:p-4 rounded-xl sm:rounded-2xl border border-slate-200 flex items-center justify-between hover:border-slate-300 transition-colors cursor-pointer group shadow-sm hover:shadow-md"
                >
                  <div class="flex items-center gap-3">
                    <div
                      class="w-10 h-10 bg-slate-50 rounded-full flex items-center justify-center shrink-0 border border-slate-100 overflow-hidden"
                    >
                      <img
                        v-if="alt.image || alt.heroImage"
                        :src="alt.image || alt.heroImage"
                        :alt="alt.name"
                        class="w-full h-full object-contain p-1.5"
                        loading="lazy"
                      />
                      <component
                        v-else
                        :is="wizardIcons[alt.iconKey] || CarFront"
                        :class="['w-5 h-5', alt.iconColor || 'text-slate-400']"
                        stroke-width="1.2"
                      />
                    </div>
                    <div>
                      <div
                        class="font-bold text-[13px] sm:text-sm text-slate-900 leading-tight mb-0.5 sm:mb-1"
                      >
                        {{ alt.name }}
                      </div>
                      <div
                        class="text-[11px] sm:text-xs text-slate-500 font-medium"
                      >
                        ~{{ formatPublicMoney(alt.price, alt.currency || 'USD', locale.value, { forceFraction: false }) }}{{ labels.perDay }}
                      </div>
                    </div>
                  </div>
                  <ExternalLink
                    class="w-3.5 h-3.5 text-slate-300 group-hover:text-brand-orange transition-colors"
                  />
                </NuxtLink>
                <div
                  v-else
                  class="bg-white p-3 sm:p-4 rounded-xl sm:rounded-2xl border border-slate-200 flex items-center justify-between hover:border-slate-300 transition-colors cursor-pointer group shadow-sm hover:shadow-md"
                >
                  <div class="flex items-center gap-3">
                    <div
                      class="w-10 h-10 bg-slate-50 rounded-full flex items-center justify-center shrink-0 border border-slate-100 overflow-hidden"
                    >
                      <img
                        v-if="alt.image || alt.heroImage"
                        :src="alt.image || alt.heroImage"
                        :alt="alt.name"
                        class="w-full h-full object-contain p-1.5"
                        loading="lazy"
                      />
                      <component
                        v-else
                        :is="wizardIcons[alt.iconKey] || CarFront"
                        :class="['w-5 h-5', alt.iconColor || 'text-slate-400']"
                        stroke-width="1.2"
                      />
                    </div>
                    <div>
                      <div
                        class="font-bold text-[13px] sm:text-sm text-slate-900 leading-tight mb-0.5 sm:mb-1"
                      >
                        {{ alt.name }}
                      </div>
                      <div
                        class="text-[11px] sm:text-xs text-slate-500 font-medium"
                      >
                        ~{{ formatPublicMoney(alt.price, alt.currency || 'USD', locale.value, { forceFraction: false }) }}{{ labels.perDay }}
                      </div>
                    </div>
                  </div>
                  <ExternalLink
                    class="w-3.5 h-3.5 text-slate-300 group-hover:text-brand-orange transition-colors"
                  />
                </div>
              </template>
            </div>
          </div>
        </div>
      </div>
    </div>
  </section>
</template>
