<script setup lang="ts">
import { computed, onUnmounted, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { PARLAY_MIN_LEGS, PARLAY_MAX_LEGS } from '@thebet365/shared';
import {
  useBetSlipStore,
  type ParlaySlipError,
  type SlipItem,
  type SlipMode,
} from '../stores/betSlip';
import { useAuthStore } from '../stores/auth';
import { formatMoney, parseAmount } from '../utils/localeDisplay';
import BetSuccessOverlay from './BetSuccessOverlay.vue';
import api from '../api';
import { usePlayerProfile } from '../composables/usePlayerProfile';

const props = defineProps<{ modelValue: boolean }>();
const emit = defineEmits<{ 'update:modelValue': [boolean] }>();

const { t, locale } = useI18n();
const slip = useBetSlipStore();
const auth = useAuthStore();
const { refreshProfile } = usePlayerProfile();
const show = computed({
  get: () => props.modelValue,
  set: (v) => emit('update:modelValue', v),
});

const activeTab = ref<SlipMode>('single');
const loading = ref(false);
const balanceLoading = ref(false);
const balance = ref<number | null>(null);
const error = ref('');
const success = ref('');
const showSuccess = ref(false);
const MIN_STAKE = 5;
const MAX_STAKE_INTEGER_LENGTH = 9;
const stakeInput = ref('');
const keypadKeys = ['1', '2', '3', '4', '5', 'backspace', '6', '7', '8', '9', '0', '00'];
const ODDS_POLL_MS = 5000;

type OddsDelta = {
  oldOdds: number;
  newOdds: number;
  newVersion: string;
  suspended: boolean;
};

interface SelectionOddsRow {
  id: string;
  odds: string;
  oddsVersion: string;
  status: string;
  marketStatus: string;
  marketShowOnPlayer: boolean;
  matchStatus: string;
}

const oddsDeltas = ref<Record<string, OddsDelta>>({});
let oddsPollTimer: ReturnType<typeof setInterval> | null = null;

const activeItems = computed<SlipItem[]>(() => {
  if (activeTab.value === 'parlay') return slip.parlayItems;
  return slip.singleItem ? [slip.singleItem] : [];
});

const activeCount = computed(() => activeItems.value.length);

function effectiveOdds(item: SlipItem) {
  return oddsDeltas.value[item.selectionId]?.newOdds ?? item.odds;
}

const activeTotalOdds = computed(() =>
  activeItems.value.reduce((acc, item) => acc * effectiveOdds(item), 1),
);
const activeEstimatedReturn = computed(() => {
  if (!activeItems.value.length || !Number.isFinite(slip.stake) || slip.stake <= 0) return 0;
  if (activeTab.value === 'parlay') return slip.stake * activeTotalOdds.value;
  return slip.stake * effectiveOdds(activeItems.value[0]);
});

const hasSuspendedSelections = computed(() =>
  Object.values(oddsDeltas.value).some((delta) => delta.suspended),
);

const hasPendingOddsChanges = computed(() =>
  Object.values(oddsDeltas.value).some((delta) => !delta.suspended),
);

const oddsWarningText = computed(() => {
  if (hasSuspendedSelections.value) return t('bet.odds_suspended');
  if (hasPendingOddsChanges.value) return t('bet.odds_changed');
  return '';
});

const submitButtonLabel = computed(() => {
  if (loading.value) return t('bet.placing');
  if (hasPendingOddsChanges.value) return t('bet.accept_changes_place');
  return t('bet.place_bet_short');
});

const canSubmitWithOdds = computed(() => canSubmitActive.value && !hasSuspendedSelections.value);

const canSubmitActive = computed(() => {
  if (activeTab.value === 'parlay') {
    return slip.parlayItems.length >= PARLAY_MIN_LEGS && slip.parlayItems.length <= PARLAY_MAX_LEGS;
  }
  return Boolean(slip.singleItem) && slip.singleItem!.allowSingle !== false;
});

const singleParlayOnlyHint = computed(
  () =>
    activeTab.value === 'single' &&
    Boolean(slip.singleItem) &&
    slip.singleItem!.allowSingle === false &&
    slip.singleItem!.allowParlay !== false,
);

const balanceText = computed(() => {
  if (balanceLoading.value) return t('bet.loading');
  if (balance.value == null) return '--';
  return formatMoney(balance.value, locale.value);
});

const stakeText = computed(() => formatMoney(slip.stake, locale.value));
const estimatedReturnText = computed(() => formatMoney(activeEstimatedReturn.value, locale.value));
const totalOddsText = computed(() => activeTotalOdds.value.toFixed(4).replace(/0+$/, '').replace(/\.$/, ''));

const parlayWarning = computed(() => {
  if (activeTab.value !== 'parlay') return '';
  if (slip.lastParlayError) return parlayErrorMessage(slip.lastParlayError);
  if (slip.parlayItems.length > 0 && slip.parlayItems.length < PARLAY_MIN_LEGS) {
    return t('bet.parlay_need_more');
  }
  return '';
});

const singleInParlay = computed(() => {
  const item = slip.singleItem;
  return Boolean(item && slip.parlayItems.some((leg) => leg.selectionId === item.selectionId));
});

const showFooterParlayAction = computed(() => activeTab.value === 'single' && Boolean(slip.singleItem));

function genId() {
  return `${Date.now()}-${Math.random().toString(36).slice(2)}`;
}

function selectTab(tab: SlipMode) {
  activeTab.value = tab;
  slip.setMode(tab);
  error.value = '';
}

function closeDrawer() {
  slip.closeDrawer();
  show.value = false;
  error.value = '';
  success.value = '';
}

function onSuccessDone() {
  showSuccess.value = false;
  closeDrawer();
}

async function loadBalance() {
  if (!auth.token) {
    balance.value = null;
    return;
  }
  balanceLoading.value = true;
  try {
    const { data } = await api.get('/player/profile');
    balance.value = parseAmount(data.data?.wallet?.availableBalance);
  } catch {
    balance.value = null;
  } finally {
    balanceLoading.value = false;
  }
}

function parlayErrorMessage(reason: ParlaySlipError) {
  if (reason === 'MAX_LEGS') return t('bet.parlay_max_legs');
  if (reason === 'QUARTER_LINE') return t('bet.parlay_block_quarter');
  if (reason === 'OUTRIGHT') return t('bet.parlay_block_outright');
  if (reason === 'NOT_ALLOWED') return t('bet.parlay_block_not_allowed');
  if (reason === 'SAME_MATCH') return t('bet.slip_parlay_same_match');
  return t('bet.parlay_block_not_allowed');
}

function addCurrentToParlay() {
  if (singleInParlay.value) {
    activeTab.value = 'parlay';
    slip.setMode('parlay');
    error.value = '';
    return;
  }
  const err = slip.addSingleToParlay();
  activeTab.value = 'parlay';
  if (err) {
    error.value = parlayErrorMessage(err);
    return;
  }
  error.value = '';
}

function removeItem(id: string) {
  slip.removeItem(id);
  error.value = '';
}

function stakeAmountToInput(amount: number) {
  if (!Number.isFinite(amount) || amount <= 0) return '';
  const rounded = Math.round(amount * 100) / 100;
  return Number.isInteger(rounded)
    ? String(rounded)
    : rounded.toFixed(2).replace(/0+$/, '').replace(/\.$/, '');
}

function sanitizeStakeInput(raw: string) {
  const onlyAmountChars = raw.replace(/[^\d.]/g, '');
  const [integerRaw, ...fractionParts] = onlyAmountChars.split('.');
  const integerPart = integerRaw.replace(/^0+(?=\d)/, '').slice(0, MAX_STAKE_INTEGER_LENGTH);
  if (!fractionParts.length) return integerPart;
  const fractionPart = fractionParts.join('').slice(0, 2);
  return `${integerPart || '0'}.${fractionPart}`;
}

function commitStakeInput(raw: string) {
  const clean = sanitizeStakeInput(raw);
  stakeInput.value = clean;
  const amount = Number.parseFloat(clean);
  slip.stake = Number.isFinite(amount) ? amount : 0;
}

function syncStakeInputFromSlip() {
  stakeInput.value = stakeAmountToInput(Number(slip.stake) || 0);
}

function onStakeInput(event: Event) {
  commitStakeInput((event.target as HTMLInputElement).value);
}

function pressStakeKey(key: string) {
  if (key === 'backspace') {
    commitStakeInput(stakeInput.value.slice(0, -1));
    return;
  }
  const base = stakeInput.value === '0' ? '' : stakeInput.value;
  commitStakeInput(`${base}${key}`);
}

function clearStakeInput() {
  commitStakeInput('');
}

function setStake(amount: number, enforceMinimum = true) {
  if (!Number.isFinite(amount)) return;
  const normalized = Math.round((enforceMinimum ? Math.max(MIN_STAKE, amount) : amount) * 100) / 100;
  slip.stake = normalized;
  stakeInput.value = stakeAmountToInput(normalized);
}

function addStake(amount: number) {
  setStake((Number(slip.stake) || 0) + amount);
}

function setMaxStake() {
  if (balance.value != null && balance.value > 0) setStake(balance.value, false);
}

function stopOddsPolling() {
  if (oddsPollTimer) {
    clearInterval(oddsPollTimer);
    oddsPollTimer = null;
  }
  oddsDeltas.value = {};
}

function acceptPendingOdds() {
  for (const [selectionId, delta] of Object.entries(oddsDeltas.value)) {
    if (!delta.suspended) {
      slip.updateSelectionOdds(selectionId, delta.newOdds, delta.newVersion);
    }
  }
  oddsDeltas.value = {};
}

async function pollSelectionsOdds() {
  const items = activeItems.value;
  if (!items.length || !show.value) return;

  try {
    const ids = items.map((item) => item.selectionId).join(',');
    const { data } = await api.get('/player/selections/odds', { params: { ids } });
    const rows: SelectionOddsRow[] = data.data?.items ?? [];
    const rowMap = new Map(rows.map((row) => [row.id, row]));
    const next: Record<string, OddsDelta> = {};

    for (const item of items) {
      const row = rowMap.get(item.selectionId);
      if (!row) continue;

      const suspended =
        row.status !== 'OPEN' ||
        row.marketStatus !== 'OPEN' ||
        row.marketShowOnPlayer === false ||
        row.matchStatus !== 'PUBLISHED';
      const newOdds = parseFloat(row.odds);
      const versionChanged = row.oddsVersion !== item.oddsVersion;
      const oddsChanged = Number.isFinite(newOdds) && Math.abs(newOdds - item.odds) > 0.0001;

      if (suspended || versionChanged || oddsChanged) {
        const existing = oddsDeltas.value[item.selectionId];
        next[item.selectionId] = {
          oldOdds: existing?.oldOdds ?? item.odds,
          newOdds: Number.isFinite(newOdds) ? newOdds : item.odds,
          newVersion: row.oddsVersion,
          suspended,
        };
      }
    }

    oddsDeltas.value = next;
  } catch {
    /* silent retry on next tick */
  }
}

function startOddsPolling() {
  stopOddsPolling();
  void pollSelectionsOdds();
  oddsPollTimer = setInterval(() => {
    void pollSelectionsOdds();
  }, ODDS_POLL_MS);
}

function oddsDeltaFor(selectionId: string) {
  return oddsDeltas.value[selectionId];
}

function oddsTrendClass(delta: OddsDelta) {
  if (delta.suspended) return 'odds-suspended';
  return delta.newOdds >= delta.oldOdds ? 'odds-up' : 'odds-down';
}

async function placeBet() {
  if (!activeItems.value.length) return;
  if (!auth.token) {
    auth.showLoginPrompt();
    return;
  }
  if (slip.stake < MIN_STAKE) {
    error.value = t('bet.slip_min_error', { amount: MIN_STAKE });
    return;
  }
  if (balance.value != null && slip.stake > balance.value) {
    error.value = t('bet.outright_insufficient');
    return;
  }
  if (activeTab.value === 'parlay' && !canSubmitActive.value) {
    error.value = slip.parlayItems.length > PARLAY_MAX_LEGS
      ? t('bet.parlay_max_legs')
      : t('bet.parlay_need_more');
    return;
  }
  if (hasSuspendedSelections.value) {
    error.value = t('bet.odds_suspended');
    return;
  }
  if (hasPendingOddsChanges.value) {
    acceptPendingOdds();
  }

  loading.value = true;
  error.value = '';
  success.value = '';

  try {
    if (activeTab.value === 'parlay') {
      await api.post('/player/bets/parlay', {
        legs: slip.parlayItems.map((item) => ({
          selectionId: item.selectionId,
          oddsVersion: item.oddsVersion,
        })),
        stake: slip.stake,
        requestId: genId(),
      });
      slip.clearParlay();
    } else {
      const item = slip.singleItem;
      if (!item) return;
      await api.post('/player/bets/single', {
        selectionId: item.selectionId,
        oddsVersion: item.oddsVersion,
        stake: slip.stake,
        requestId: genId(),
      });
      slip.clearSingle();
    }
    success.value = t('bet.place_success');
    showSuccess.value = true;
    await Promise.all([loadBalance(), refreshProfile()]);
    setTimeout(() => {
      if (showSuccess.value) onSuccessDone();
    }, 2200);
  } catch (e: unknown) {
    error.value =
      (e as { response?: { data?: { error?: string } } })?.response?.data?.error ||
      t('bet.place_failed');
  } finally {
    loading.value = false;
  }
}

watch(
  () => props.modelValue,
  (open) => {
    if (!open) {
      stopOddsPolling();
      return;
    }
    activeTab.value = slip.mode;
    if (activeTab.value === 'single' && !slip.singleItem && slip.parlayItems.length) {
      activeTab.value = 'parlay';
      slip.setMode('parlay');
    }
    error.value = '';
    success.value = '';
    syncStakeInputFromSlip();
    loadBalance();
    startOddsPolling();
  },
);

watch(
  () => activeItems.value.map((item) => item.selectionId).join(','),
  () => {
    if (show.value) void pollSelectionsOdds();
  },
);

onUnmounted(() => {
  stopOddsPolling();
});

watch(
  () => slip.mode,
  (mode) => {
    if (show.value) activeTab.value = mode;
  },
);
</script>

<template>
  <div v-if="show" class="overlay" @click.self="closeDrawer">
    <div class="drawer">
      <div class="drawer-head">
        <div>
          <p class="drawer-kicker">{{ t('bet.bet_slip') }}</p>
          <h3>{{ t('bet.slip_review_title') }}</h3>
        </div>
        <button type="button" class="close-btn" :aria-label="t('bet.cancel')" @click.stop="closeDrawer">
          ✕
        </button>
      </div>

      <div class="balance-bar">
        <span>{{ t('bet.slip_balance') }}</span>
        <strong>{{ balanceText }}</strong>
        <button type="button" class="balance-refresh" :disabled="balanceLoading" @click="loadBalance">
          ↻
        </button>
      </div>

      <p v-if="oddsWarningText" class="odds-warning">{{ oddsWarningText }}</p>

      <div class="slip-tabs">
        <button
          type="button"
          class="slip-tab"
          :class="{ active: activeTab === 'single' }"
          @click="selectTab('single')"
        >
          {{ t('bet.slip_tab_single') }}
          <span v-if="slip.singleCount" class="tab-count">{{ slip.singleCount }}</span>
        </button>
        <button
          type="button"
          class="slip-tab"
          :class="{ active: activeTab === 'parlay' }"
          @click="selectTab('parlay')"
        >
          {{ t('bet.slip_tab_parlay') }}
          <span v-if="slip.parlayCount" class="tab-count">{{ slip.parlayCount }}</span>
        </button>
      </div>

      <div class="drawer-body">
        <div v-if="!activeItems.length" class="empty">
          {{ activeTab === 'parlay' ? t('bet.slip_parlay_empty_hint') : t('bet.slip_empty_hint') }}
        </div>

        <template v-else>
          <div v-if="activeTab === 'single' && slip.singleItem" class="slip-item slip-item--single">
            <div class="item-main">
              <div class="item-title">{{ slip.singleItem.matchName }}</div>
              <div v-if="slip.singleItem.marketName" class="item-market">{{ slip.singleItem.marketName }}</div>
              <div class="item-pick">{{ slip.singleItem.selectionName }}</div>
            </div>
            <div class="item-odds">
              <template v-if="oddsDeltaFor(slip.singleItem.selectionId)">
                <span
                  class="odds-change"
                  :class="oddsTrendClass(oddsDeltaFor(slip.singleItem.selectionId)!)"
                >
                  {{ oddsDeltaFor(slip.singleItem.selectionId)!.oldOdds.toFixed(2) }}
                  →
                  {{ oddsDeltaFor(slip.singleItem.selectionId)!.newOdds.toFixed(2) }}
                </span>
              </template>
              <template v-else>{{ slip.singleItem.odds.toFixed(2) }}</template>
            </div>
          </div>
          <p v-if="singleParlayOnlyHint" class="warning">{{ t('bet.slip_parlay_only_hint') }}</p>

          <template v-if="activeTab === 'parlay'">
            <p v-if="parlayWarning" class="warning">{{ parlayWarning }}</p>
            <div
              v-for="item in slip.parlayItems"
              :key="item.selectionId"
              class="slip-item"
            >
              <div class="item-main">
                <div class="item-title">{{ item.matchName }}</div>
                <div v-if="item.marketName" class="item-market">{{ item.marketName }}</div>
                <div class="item-pick">{{ item.selectionName }}</div>
              </div>
              <div class="item-side">
                <strong>
                  <template v-if="oddsDeltaFor(item.selectionId)">
                    <span
                      class="odds-change"
                      :class="oddsTrendClass(oddsDeltaFor(item.selectionId)!)"
                    >
                      {{ oddsDeltaFor(item.selectionId)!.oldOdds.toFixed(2) }}
                      →
                      {{ oddsDeltaFor(item.selectionId)!.newOdds.toFixed(2) }}
                    </span>
                  </template>
                  <template v-else>{{ item.odds.toFixed(2) }}</template>
                </strong>
                <button type="button" class="remove" @click="removeItem(item.selectionId)">
                  {{ t('bet.slip_remove') }}
                </button>
              </div>
            </div>
            <p v-if="slip.parlayItems.length" class="parlay-meta">
              {{ t('bet.slip_parlay_count', { n: slip.parlayItems.length }) }}
              · {{ t('bet.slip_parlay_odds', { odds: totalOddsText }) }}
            </p>
          </template>

          <div class="stake-area">
            <div class="stake-head">
              <span>{{ activeTab === 'parlay' ? t('bet.slip_total_stake') : t('bet.stake') }}</span>
              <strong>{{ stakeText }}</strong>
            </div>
            <div class="stake-input-row">
              <span class="currency">{{ t('bet.slip_currency') }}</span>
              <input
                :value="stakeInput"
                type="text"
                inputmode="decimal"
                autocomplete="off"
                @input="onStakeInput"
              />
              <button type="button" class="input-clear" @click="clearStakeInput">✕</button>
            </div>
            <div class="number-pad">
              <button
                v-for="key in keypadKeys"
                :key="key"
                type="button"
                class="number-key"
                :class="{ 'number-key--backspace': key === 'backspace' }"
                @click="pressStakeKey(key)"
              >
                <span v-if="key === 'backspace'" aria-hidden="true">⌫</span>
                <template v-else>{{ key }}</template>
              </button>
            </div>
            <div class="quick-stakes">
              <button type="button" @click="setStake(MIN_STAKE)">{{ t('bet.slip_min') }}</button>
              <button type="button" @click="addStake(50)">+50</button>
              <button type="button" @click="addStake(100)">+100</button>
              <button type="button" @click="setMaxStake">{{ t('bet.stake_max') }}</button>
            </div>
            <div class="return">
              <span>{{ t('bet.slip_est_return') }}</span>
              <strong>{{ estimatedReturnText }}</strong>
            </div>
          </div>
        </template>

        <p v-if="error" class="error">{{ error }}</p>
        <p v-if="success" class="success">{{ success }}</p>
      </div>

      <div class="drawer-foot" :class="{ 'drawer-foot--split': showFooterParlayAction }">
        <button
          v-if="showFooterParlayAction"
          type="button"
          class="btn-add-parlay"
          @click="addCurrentToParlay"
        >
          <span aria-hidden="true">+</span>
          {{ t('bet.slip_add_parlay') }}
        </button>
        <button
          type="button"
          class="btn-primary"
          :disabled="loading || !canSubmitWithOdds"
          @click="placeBet"
        >
          {{ submitButtonLabel }}
        </button>
      </div>
    </div>
  </div>

  <BetSuccessOverlay :show="showSuccess" @done="onSuccessDone" />
</template>

<style scoped>
.overlay {
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.75);
  z-index: 200;
  display: flex;
  align-items: flex-end;
}

.drawer {
  width: 100%;
  max-height: 88vh;
  background: #101010;
  border-radius: 16px 16px 0 0;
  border-top: 1px solid var(--border-gold-soft);
  display: flex;
  flex-direction: column;
  overflow: hidden;
  box-shadow: 0 -20px 44px rgba(0, 0, 0, 0.48);
}

.drawer-head {
  position: relative;
  z-index: 2;
  flex-shrink: 0;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 12px;
  padding: 14px 14px 10px;
  background: linear-gradient(180deg, #1d1d1d 0%, #111 100%);
  border-bottom: 1px solid rgba(255, 255, 255, 0.06);
}

.drawer-kicker {
  margin: 0 0 3px;
  font-size: 11px;
  color: var(--primary-light);
  font-weight: 800;
}

.drawer-head h3 {
  margin: 0;
  font-size: 17px;
  font-weight: 900;
  color: var(--text);
}

.close-btn {
  position: relative;
  z-index: 3;
  flex-shrink: 0;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.05);
  color: var(--text-muted);
  font-size: 18px;
  padding: 0;
  pointer-events: auto;
  touch-action: manipulation;
}

.balance-bar {
  display: grid;
  grid-template-columns: auto 1fr auto;
  align-items: center;
  gap: 8px;
  padding: 10px 14px;
  background: rgba(212, 175, 55, 0.08);
  border-bottom: 1px solid rgba(212, 175, 55, 0.18);
  color: var(--text-muted);
  font-size: 12px;
}

.balance-bar strong {
  justify-self: end;
  color: var(--primary-light);
  font-size: 16px;
  font-weight: 900;
}

.balance-refresh {
  width: 28px;
  height: 28px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.04);
  color: var(--text-muted);
  padding: 0;
}

.slip-tabs {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  padding: 8px 12px 0;
  gap: 6px;
  background: #101010;
}

.slip-tab {
  min-height: 38px;
  border-radius: 6px 6px 0 0;
  border: 1px solid var(--border);
  background: #171717;
  color: var(--text-muted);
  font-size: 13px;
  font-weight: 800;
}

.slip-tab.active {
  border-color: var(--border-gold-soft);
  background: rgba(212, 175, 55, 0.13);
  color: var(--primary-light);
}

.tab-count {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  min-width: 18px;
  height: 18px;
  margin-left: 6px;
  border-radius: 9px;
  background: var(--primary);
  color: #111;
  font-size: 11px;
  font-weight: 900;
}

.drawer-body {
  flex: 1;
  overflow-y: auto;
  padding: 12px 12px 0;
  -webkit-overflow-scrolling: touch;
}

.empty {
  text-align: center;
  color: var(--text-muted);
  padding: 26px 12px;
  font-size: 13px;
}

.slip-item {
  display: grid;
  grid-template-columns: minmax(0, 1fr) auto;
  gap: 10px;
  align-items: center;
  padding: 11px 12px;
  background: #151515;
  border: 1px solid #292929;
  border-radius: 7px;
  margin-bottom: 8px;
}

.slip-item--single {
  border-color: var(--border-gold-soft);
  background: linear-gradient(180deg, rgba(212, 175, 55, 0.12), rgba(18, 18, 18, 0.94));
}

.item-main {
  min-width: 0;
}

.item-title {
  font-size: 13px;
  font-weight: 900;
  color: var(--text);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.item-market {
  margin-top: 4px;
  font-size: 12px;
  font-weight: 800;
  color: var(--primary-light);
}

.item-pick {
  margin-top: 3px;
  font-size: 12px;
  color: var(--text-muted);
  line-height: 1.35;
}

.item-odds,
.item-side strong {
  color: var(--primary-light);
  font-size: 22px;
  font-weight: 900;
}

.item-side {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 6px;
}

.remove {
  background: none;
  color: var(--danger);
  font-size: 12px;
  font-weight: 800;
  padding: 0;
}

.btn-add-parlay {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 7px;
  width: 100%;
  min-height: 48px;
  padding: 0 14px;
  border-radius: 8px;
  background: linear-gradient(180deg, #4b370d 0%, #241905 100%);
  border: 1px solid var(--primary-light);
  color: #ffe892;
  font-size: 14px;
  font-weight: 900;
  box-shadow:
    0 0 0 1px rgba(255, 232, 146, 0.18) inset,
    0 6px 18px rgba(212, 175, 55, 0.18);
}

.btn-add-parlay span {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 18px;
  height: 18px;
  border-radius: 50%;
  background: var(--primary-light);
  color: #191100;
  font-size: 14px;
  line-height: 1;
}

.odds-warning {
  margin: 0 16px 10px;
  padding: 10px 12px;
  border-radius: 8px;
  background: rgba(244, 162, 97, 0.12);
  border: 1px solid rgba(244, 162, 97, 0.28);
  color: var(--primary-light);
  font-size: 12px;
  line-height: 1.45;
}

.odds-change {
  font-weight: 700;
}

.odds-change.odds-up {
  color: #6ee7a0;
}

.odds-change.odds-down {
  color: #ff8b8b;
}

.odds-change.odds-suspended {
  color: #ffb84d;
}

.warning,
.error {
  margin: 0 0 10px;
  padding: 10px 11px;
  border-radius: 6px;
  background: rgba(255, 77, 79, 0.12);
  border: 1px solid rgba(255, 77, 79, 0.25);
  color: #ff8b8b;
  font-size: 12px;
  line-height: 1.45;
}

.parlay-meta {
  margin: 8px 2px 10px;
  color: var(--primary-light);
  font-size: 12px;
  font-weight: 800;
}

.stake-area {
  margin: 12px 0 12px;
  padding: 12px;
  background: #151515;
  border: 1px solid #292929;
  border-radius: 8px;
}

.stake-head,
.return {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 8px;
  font-size: 12px;
  color: var(--text-muted);
}

.stake-head strong,
.return strong {
  color: var(--primary-light);
  font-size: 16px;
  font-weight: 900;
}

.stake-input-row {
  display: grid;
  grid-template-columns: auto 1fr auto;
  align-items: center;
  margin-top: 10px;
  border: 1px solid var(--border-gold-soft);
  border-radius: 6px;
  overflow: hidden;
  background: #0c0c0c;
}

.currency {
  padding: 0 10px;
  color: var(--text-muted);
  font-size: 13px;
  border-right: 1px solid #2d2d2d;
}

.stake-input-row input {
  min-width: 0;
  height: 42px;
  border: none;
  background: transparent;
  color: var(--text);
  font-size: 17px;
  font-weight: 800;
  padding: 0 10px;
  outline: none;
  text-align: right;
  -moz-appearance: textfield;
}

.stake-input-row input::-webkit-outer-spin-button,
.stake-input-row input::-webkit-inner-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

.input-clear {
  width: 38px;
  height: 42px;
  background: transparent;
  color: var(--text-muted);
  padding: 0;
  font-size: 15px;
}

.number-pad,
.quick-stakes {
  display: grid;
  gap: 4px;
  margin-top: 10px;
}

.number-pad {
  grid-template-columns: repeat(6, 1fr);
}

.quick-stakes {
  grid-template-columns: repeat(4, 1fr);
}

.number-key,
.quick-stakes button {
  min-height: 52px;
  border-radius: 5px;
  background: #f4f1f6;
  color: #221f26;
  border: 1px solid rgba(255, 255, 255, 0.16);
  font-size: 26px;
  font-weight: 500;
}

.number-key--backspace span {
  display: inline-block;
  transform: translateY(1px);
}

.quick-stakes button {
  min-height: 50px;
  background: #7b787d;
  color: var(--text);
  font-size: 20px;
  font-weight: 800;
}

.return {
  margin-top: 10px;
}

.success {
  color: var(--primary-light);
  font-size: 13px;
  margin: 0 0 8px;
}

.drawer-foot {
  flex-shrink: 0;
  display: grid;
  grid-template-columns: 1fr;
  gap: 10px;
  padding: 10px 14px calc(10px + env(safe-area-inset-bottom, 0px));
  background: rgba(14, 14, 14, 0.98);
  border-top: 1px solid var(--border-gold-soft);
  box-shadow: 0 -6px 20px rgba(0, 0, 0, 0.45);
}

.drawer-foot--split {
  grid-template-columns: minmax(0, 0.95fr) minmax(0, 1.05fr);
}

.btn-primary {
  width: 100%;
  min-height: 48px;
  border-radius: 7px;
  background: linear-gradient(180deg, var(--primary-light), var(--primary));
  color: #111;
  font-size: 16px;
  font-weight: 900;
}

.btn-primary:disabled {
  opacity: 0.45;
}
</style>
