<script lang="ts" setup>
import { onMounted, watch } from 'vue'
import { useDedicatedConfiguratorStore, type DedicatedPlan, type DedicatedConfigGroup, type DedicatedCycle } from '@/stores/dedicatedConfigurator'
import OptionGroupSelector from './OptionGroupSelector.vue'
import CycleToggle from './CycleToggle.vue'

interface Props {
  plan: DedicatedPlan
  configGroups: DedicatedConfigGroup[]
  accountUrl: string
}

const props = defineProps<Props>()

const store = useDedicatedConfiguratorStore()

function pushUrlState(): void {
  if (typeof window === 'undefined') return
  const newUrl = store.shareUrl
  if (newUrl !== window.location.href) {
    window.history.replaceState({}, '', newUrl)
  }
}

let urlDebounce: ReturnType<typeof setTimeout> | null = null
function debouncePushUrl(): void {
  if (urlDebounce) clearTimeout(urlDebounce)
  urlDebounce = setTimeout(pushUrlState, 300)
}

function onSelectionChange(groupName: string, value: string): void {
  store.setSelection(groupName, value)
  debouncePushUrl()
}

function onCycleChange(c: DedicatedCycle): void {
  store.cycle = c
  debouncePushUrl()
}

onMounted(() => {
  store.init({
    plan: props.plan,
    configGroups: props.configGroups,
    accountUrl: props.accountUrl,
  })
  if (typeof window !== 'undefined') {
    store.hydrateFromUrl(window.location.search)
  }
})

watch(() => props.plan?.id, () => {
  store.init({
    plan: props.plan,
    configGroups: props.configGroups,
    accountUrl: props.accountUrl,
  })
})
</script>

<template>
  <div class="dedicated-configurator">
    <div class="dedicated-configurator__cycle">
      <div class="text-overline text-medium-emphasis mb-2">Billing cycle</div>
      <CycleToggle :model-value="store.cycle" @update:model-value="onCycleChange" />
    </div>

    <div class="dedicated-configurator__groups">
      <OptionGroupSelector
        v-for="group in configGroups"
        :key="group.id"
        :group="group"
        :selected="store.selections[group.name] ?? ''"
        :cycle="store.cycle"
        @update:selected="(v: string) => onSelectionChange(group.name, v)"
      />
    </div>
  </div>
</template>

<style lang="scss" scoped>
.dedicated-configurator {
  display: flex;
  flex-direction: column;
  gap: 28px;
}

.dedicated-configurator__cycle {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.dedicated-configurator__groups {
  display: flex;
  flex-direction: column;
  gap: 28px;
  padding: 24px;
  border-radius: 18px;
  background: rgba(var(--v-theme-surface), 0.4);
  border: 1px solid rgba(var(--v-theme-on-surface), 0.06);
  backdrop-filter: blur(12px);
}

.dedicated-configurator__footer-wrap {
  margin-top: 8px;
}
</style>
