<script lang="ts" setup>
import { computed, ref } from 'vue'
import type { DedicatedConfigGroup, DedicatedCycle, DedicatedPlan } from '@/stores/dedicatedConfigurator'

interface Props {
  plan: DedicatedPlan
  configGroups: DedicatedConfigGroup[]
  selections: Record<string, string>
  cycle: DedicatedCycle
  baselinePrice: number
  cycleSubtotal: number
  setupFee: number
  baselineSetupFee: number
  isSetupFeeWaived: boolean
  monthlyEffective: number
  cycleTotal: number
  checkoutUrl: string
  shareUrl: string
}

const props = defineProps<Props>()

const cycleLabel: Record<DedicatedCycle, string> = {
  monthly: 'Monthly',
  quarterly: 'Quarterly (3 months)',
  semi_annual: 'Semi-Annual (6 months)',
  annual: 'Annual (12 months)',
}

const cycleSuffix: Record<DedicatedCycle, string> = {
  monthly: '/mo',
  quarterly: '/qtr',
  semi_annual: '/6mo',
  annual: '/yr',
}

interface LineItem {
  label: string
  detail: string
  amount: number
  isBaseline?: boolean
}

const lineItems = computed<LineItem[]>(() => {
  const items: LineItem[] = []

  // Always show the baseline first.
  items.push({
    label: props.plan.name,
    detail: 'Locked baseline build',
    amount: props.baselinePrice,
    isBaseline: true,
  })

  // Then each selected upgrade — only if it has a non-zero contribution.
  for (const group of props.configGroups) {
    const valueSlug = props.selections[group.name]
    if (!valueSlug) continue

    const opt = group.options[0]
    if (!opt) continue

    const value = opt.values.find(v => v.value === valueSlug)
    if (!value) continue

    const raw = props.cycle === 'monthly'
      ? value.monthly_price
      : props.cycle === 'quarterly'
        ? value.quarterly_price
        : props.cycle === 'semi_annual'
          ? value.semi_annual_price
          : value.annual_price
    const cost = raw ? parseFloat(raw) : 0

    if (cost === 0 && !value.is_default) {
      // Free non-default selection (e.g., choosing AlmaLinux 9 over "No OS")
      // — show as no-extra-cost row to confirm the choice.
      items.push({
        label: group.name.replace('Dedicated 14th Gen — ', ''),
        detail: value.label,
        amount: 0,
      })
      continue
    }

    if (cost === 0) continue // skip default-included rows

    items.push({
      label: group.name.replace('Dedicated 14th Gen — ', ''),
      detail: value.label,
      amount: cost,
    })
  }

  return items
})

const copied = ref<boolean>(false)

async function copyShareLink(): Promise<void> {
  try {
    await navigator.clipboard.writeText(props.shareUrl)
  } catch {
    const ta = document.createElement('textarea')
    ta.value = props.shareUrl
    ta.style.position = 'fixed'
    ta.style.opacity = '0'
    document.body.appendChild(ta)
    ta.select()
    try { document.execCommand('copy') } catch { /* ignore */ }
    document.body.removeChild(ta)
  }
  copied.value = true
  setTimeout(() => { copied.value = false }, 2000)
}

function formatPrice(amount: number): string {
  return amount.toFixed(2)
}
</script>

<template>
  <aside class="build-summary" aria-label="Build summary">
    <div class="build-summary__head">
      <div class="text-overline text-medium-emphasis">Build summary</div>
      <h3 class="build-summary__title">{{ plan.name }}</h3>
      <div class="build-summary__cycle-row">
        <VIcon icon="tabler-calendar-month" size="14" class="me-1" />
        <span>{{ cycleLabel[cycle] }}</span>
      </div>
    </div>

    <div class="build-summary__divider"></div>

    <div class="build-summary__section">
      <div class="text-overline build-summary__section-label">Recurring</div>
      <div class="build-summary__lines">
        <div
          v-for="(item, idx) in lineItems"
          :key="idx"
          class="build-summary__line"
          :class="{ 'build-summary__line--baseline': item.isBaseline }"
        >
          <div class="build-summary__line-text">
            <div class="build-summary__line-label">{{ item.label }}</div>
            <div class="build-summary__line-detail">{{ item.detail }}</div>
          </div>
          <div class="build-summary__line-amount">
            <template v-if="item.isBaseline">${{ formatPrice(item.amount) }}</template>
            <template v-else-if="item.amount === 0">
              <span class="text-success">included</span>
            </template>
            <template v-else>+${{ formatPrice(item.amount) }}</template>
          </div>
        </div>
      </div>

      <div class="build-summary__subtotal">
        <span class="build-summary__subtotal-label">Subtotal</span>
        <div class="build-summary__subtotal-amount">
          <span class="build-summary__subtotal-price">${{ formatPrice(cycleSubtotal) }}</span>
          <span class="build-summary__subtotal-suffix">{{ cycleSuffix[cycle] }}</span>
        </div>
      </div>
      <div v-if="cycle !== 'monthly'" class="build-summary__effective">
        ≈ ${{ formatPrice(monthlyEffective) }}/mo effective
      </div>
    </div>

    <div v-if="baselineSetupFee > 0" class="build-summary__divider"></div>

    <div v-if="baselineSetupFee > 0" class="build-summary__section">
      <div class="text-overline build-summary__section-label">One-time</div>
      <div class="build-summary__line">
        <div class="build-summary__line-text">
          <div class="build-summary__line-label">Setup fee</div>
          <div class="build-summary__line-detail">
            Server provisioning &amp; deployment · charged on first invoice
          </div>
        </div>
        <div class="build-summary__line-amount">
          <template v-if="isSetupFeeWaived">
            <span class="build-summary__waived-amount">${{ formatPrice(baselineSetupFee) }}</span>
            <div class="text-caption text-success font-weight-bold">waived</div>
          </template>
          <template v-else>+${{ formatPrice(setupFee) }}</template>
        </div>
      </div>
      <div v-if="!isSetupFeeWaived" class="build-summary__setup-note">
        <VIcon icon="tabler-info-circle" size="12" class="me-1" />
        Non-refundable once your build starts. Switch to Semi-Annual or Annual to waive.
      </div>
    </div>

    <div class="build-summary__divider build-summary__divider--strong"></div>

    <div class="build-summary__total">
      <div class="build-summary__total-label">
        <template v-if="cycle === 'monthly'">First invoice</template>
        <template v-else>Total due today</template>
      </div>
      <div class="build-summary__total-amount">
        ${{ formatPrice(cycleTotal) }}
      </div>
      <div v-if="cycle === 'monthly' && !isSetupFeeWaived" class="build-summary__total-detail">
        Then ${{ formatPrice(cycleSubtotal) }}/mo recurring
      </div>
      <div v-else-if="cycle !== 'monthly'" class="build-summary__total-detail">
        Renews {{ cycleLabel[cycle].toLowerCase() }} at ${{ formatPrice(cycleSubtotal) }}
      </div>
    </div>

    <div class="build-summary__actions">
      <a :href="checkoutUrl" class="text-decoration-none">
        <VBtn block color="primary" size="large" rounded="lg" prepend-icon="tabler-shopping-cart">
          Order this build
          <VIcon icon="tabler-arrow-right" end />
        </VBtn>
      </a>
      <VBtn
        block
        :variant="copied ? 'flat' : 'outlined'"
        :color="copied ? 'success' : 'primary'"
        size="default"
        :prepend-icon="copied ? 'tabler-check' : 'tabler-link'"
        class="mt-2"
        @click="copyShareLink"
      >
        {{ copied ? 'Copied!' : 'Copy share link' }}
      </VBtn>
    </div>
  </aside>
</template>

<style lang="scss" scoped>
.build-summary {
  display: flex;
  flex-direction: column;
  padding: 24px;
  border-radius: 18px;
  background: rgba(var(--v-theme-surface), 0.85);
  border: 1px solid rgba(var(--v-theme-primary), 0.22);
  box-shadow: 0 12px 36px rgba(0, 0, 0, 0.25);
  backdrop-filter: blur(20px);
  -webkit-backdrop-filter: blur(20px);
  // Stickiness is owned by the parent grid cell (.detail-grid__summary) on
  // the page — keeping it here would create a doubly-sticky effect that
  // doesn't behave correctly. The card is just a plain card.
}

.build-summary__head {
  margin-bottom: 14px;
}

.build-summary__title {
  font-size: 18px;
  font-weight: 700;
  letter-spacing: -0.01em;
  color: rgba(var(--v-theme-on-surface), 0.95);
  margin-bottom: 6px;
  margin-top: 4px;
  line-height: 1.3;
}

.build-summary__cycle-row {
  display: inline-flex;
  align-items: center;
  font-size: 12px;
  color: rgba(var(--v-theme-on-surface), 0.65);
  padding: 4px 10px;
  background: rgba(var(--v-theme-on-surface), 0.05);
  border-radius: 999px;
}

.build-summary__divider {
  height: 1px;
  background: rgba(var(--v-theme-on-surface), 0.08);
  margin: 16px 0;

  &--strong {
    background: rgba(var(--v-theme-on-surface), 0.18);
    margin: 18px 0;
  }
}

.build-summary__section-label {
  display: block;
  font-size: 10px;
  letter-spacing: 0.1em;
  color: rgba(var(--v-theme-on-surface), 0.5);
  margin-bottom: 10px;
}

.build-summary__lines {
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin-bottom: 14px;
}

.build-summary__line {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 12px;
}

.build-summary__line--baseline {
  font-weight: 600;
}

.build-summary__line-text {
  flex-grow: 1;
  min-width: 0;
}

.build-summary__line-label {
  font-size: 13px;
  color: rgba(var(--v-theme-on-surface), 0.92);
  font-weight: 500;
  line-height: 1.3;
}

.build-summary__line-detail {
  font-size: 11px;
  color: rgba(var(--v-theme-on-surface), 0.55);
  margin-top: 1px;
  line-height: 1.3;
}

.build-summary__line-amount {
  font-size: 13px;
  text-align: end;
  font-variant-numeric: tabular-nums;
  flex-shrink: 0;
  color: rgba(var(--v-theme-on-surface), 0.85);
}

.build-summary__line--baseline .build-summary__line-amount {
  color: rgba(var(--v-theme-on-surface), 0.95);
  font-weight: 600;
}

.build-summary__subtotal {
  display: flex;
  align-items: baseline;
  justify-content: space-between;
  gap: 8px;
  padding-top: 10px;
  border-top: 1px dashed rgba(var(--v-theme-on-surface), 0.08);
}

.build-summary__subtotal-label {
  font-size: 13px;
  font-weight: 600;
  color: rgba(var(--v-theme-on-surface), 0.7);
}

.build-summary__subtotal-amount {
  display: flex;
  align-items: baseline;
  gap: 2px;
}

.build-summary__subtotal-price {
  font-size: 18px;
  font-weight: 700;
  font-variant-numeric: tabular-nums;
  color: rgba(var(--v-theme-on-surface), 0.95);
}

.build-summary__subtotal-suffix {
  font-size: 12px;
  color: rgba(var(--v-theme-on-surface), 0.6);
}

.build-summary__effective {
  margin-top: 4px;
  font-size: 11px;
  color: rgba(var(--v-theme-on-surface), 0.55);
  text-align: end;
}

.build-summary__waived-amount {
  text-decoration: line-through;
  color: rgba(var(--v-theme-on-surface), 0.45);
  font-size: 12px;
}

.build-summary__setup-note {
  margin-top: 8px;
  padding: 8px 10px;
  border-radius: 6px;
  background: rgba(var(--v-theme-warning), 0.08);
  border: 1px solid rgba(var(--v-theme-warning), 0.2);
  font-size: 11px;
  color: rgba(var(--v-theme-on-surface), 0.7);
  display: flex;
  align-items: flex-start;
  line-height: 1.4;

  .v-icon {
    color: rgb(var(--v-theme-warning));
    flex-shrink: 0;
    margin-top: 1px;
  }
}

.build-summary__total {
  margin-bottom: 18px;
}

.build-summary__total-label {
  font-size: 13px;
  font-weight: 600;
  color: rgba(var(--v-theme-on-surface), 0.7);
  margin-bottom: 4px;
}

.build-summary__total-amount {
  font-size: 36px;
  font-weight: 800;
  letter-spacing: -0.02em;
  line-height: 1;
  color: rgb(var(--v-theme-primary));
  font-variant-numeric: tabular-nums;
}

.build-summary__total-detail {
  margin-top: 6px;
  font-size: 12px;
  color: rgba(var(--v-theme-on-surface), 0.6);
}

.build-summary__actions {
  display: flex;
  flex-direction: column;
}
</style>
