<template>
  <q-scroll-area class="loyalty-suite-wrapper">
    <q-inner-loading :showing="loading">
      <q-spinner color="primary" size="70px" />
    </q-inner-loading>

    <template v-if="!loading">
      <div v-if="error" class="loyalty-suite-api-error-message">
        <q-icon name="error_outline" color="negative" size="md" />
        <span>{{ error }}</span>
      </div>

      <template v-else>
        <div v-if="!isPro || !isWooEnabled" class="loyalty-suite-analytics__features">
          <div class="loyalty-suite-analytics__features-wrapper">
            <div class="loyalty-suite-analytics__features-header">
              <div class="loyalty-suite-analytics__features-title">
                <span v-if="!isPro" class="loyalty-suite-analytics__features-pro">PRO</span>
                <template v-if="!isPro">
                  {{ $t('analyticsRequiresPro') }}
                </template>
                <template v-else>
                  {{ $t('analyticsRequiresWooCommerce') }}
                </template>
              </div>
              <q-btn
                v-if="!isPro"
                color="positive"
                :label="$t('getPRO')"
                :href="getProLink"
                target="_blank"
              />
            </div>
            <div class="loyalty-suite-analytics__features-list">
              <div
                v-for="(feature, index) in proFeatures"
                :key="index"
                class="loyalty-suite-analytics__features-item"
              >
                <div class="loyalty-suite-analytics__features-item-wrapper">
                  <q-icon :name="feature.icon"></q-icon>
                  <div class="loyalty-suite-analytics__features-item-title">
                    {{ feature.title }}
                  </div>
                  <div class="loyalty-suite-analytics__features-item-text">
                    {{ feature.description }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div v-else class="loyalty-suite-analytics">
          <div class="loyalty-suite-analytics__title">
            <h1 class="loyalty-suite-analytics__title-text">
              {{ $t('analyticsEdit') }}
            </h1>

            <div class="loyalty-suite-analytics__period">
              <input
                id="period-input"
                type="text"
                class="loyalty-suite-analytics__period-input"
                :value="periodLabel"
                :size="Math.max(String(periodLabel).length - 1, 1)"
                readonly
                @click="openPeriodDialog"
              />
              <q-icon name="event" class="cursor-pointer" @click="openPeriodDialog" />
            </div>
          </div>

          <div class="loyalty-suite-analytics__wrapper">
            <!-- 1. Program Overview -->
            <div class="loyalty-suite-analytics__container">
              <div class="loyalty-suite-analytics__content">
                <div class="loyalty-suite-analytics__header">
                  {{ $t('analyticsOverviewTitle') }}
                </div>
                <div class="loyalty-suite-analytics__body">
                  <template v-if="changeLoading">
                    <q-spinner color="primary" size="50px" />
                  </template>
                  <template v-else>
                    <div class="loyalty-suite-analytics-block">
                      <div class="loyalty-suite-analytics-metrics">
                        <div class="loyalty-suite-analytics-metric-column">
                          <div class="loyalty-suite-analytics-metric">
                            <div class="loyalty-suite-analytics-metric__label">
                              {{ $t('analyticsTotalUsers') }}
                              <q-icon
                                name="info_outline"
                                size="18px"
                                class="loyalty-suite-form__row-hint"
                              >
                                <q-tooltip anchor="top left" self="top left">
                                  {{ $t('analyticsTotalUsersHint') }}
                                </q-tooltip>
                              </q-icon>
                            </div>
                            <div class="loyalty-suite-analytics-metric__value">
                              {{ formatNumber(data.overview?.total_users ?? 0) }}
                            </div>
                          </div>

                          <div class="loyalty-suite-analytics-metric">
                            <div class="loyalty-suite-analytics-metric__label">
                              {{ $t('analyticsTotalMembers') }}
                              <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                                <q-tooltip anchor="top left" self="top left">
                                  {{ $t('analyticsTotalMembersHint') }}
                                </q-tooltip>
                              </q-icon>
                            </div>
                            <div class="loyalty-suite-analytics-metric__value">
                              {{ formatNumber(data.overview?.total_members ?? 0) }}
                            </div>
                          </div>

                          <div class="loyalty-suite-analytics-metric">
                            <div class="loyalty-suite-analytics-metric__label">
                              {{ $t('analyticsTotalCustomers') }}
                              <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                                <q-tooltip anchor="top left" self="top left">
                                  {{ $t('analyticsTotalCustomersHint') }}
                                </q-tooltip>
                              </q-icon>
                            </div>
                            <div class="loyalty-suite-analytics-metric__value">
                              {{ formatNumber(data.overview?.total_customers ?? 0) }}
                            </div>
                          </div>
                        </div>
                        <div class="loyalty-suite-analytics-metric-column">
                          <div class="loyalty-suite-analytics-metric">
                            <div class="loyalty-suite-analytics-chart">
                              <canvas
                                ref="overviewChartRef"
                                v-show="hasOverviewData"
                              ></canvas>

                              <div
                                v-if="!hasOverviewData"
                                class="loyalty-suite-analytics-chart__placeholder"
                              >
                                {{ $t('analyticsNotEnoughData') }}
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>

                      <div class="loyalty-suite-analytics-divider"></div>

                      <div class="loyalty-suite-analytics-metrics">
                        <div class="loyalty-suite-analytics-metric">
                          <div class="loyalty-suite-analytics-metric__label">
                            {{ $t('analyticsEnrollmentRate') }}
                            <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                              <q-tooltip anchor="top left" self="top left">
                                {{ $t('analyticsEnrollmentRateHint') }}
                              </q-tooltip>
                            </q-icon>
                          </div>
                          <div class="loyalty-suite-analytics-metric__value">
                            {{ formatPercent(data.overview?.enrollment_rate ?? 0) }}
                          </div>
                        </div>

                        <div class="loyalty-suite-analytics-metric">
                          <div class="loyalty-suite-analytics-metric__label">
                            {{ $t('analyticsGamificationMembersRanks') }}
                            <q-icon
                              name="info_outline"
                              size="18px"
                              class="loyalty-suite-form__row-hint"
                            >
                              <q-tooltip anchor="top left" self="top left">
                                {{ $t('analyticsGamificationMembersRanksHint') }}
                              </q-tooltip>
                            </q-icon>
                          </div>
                          <div class="loyalty-suite-analytics-metric__value">
                            {{ formatNumber(data.gamification?.members?.ranks ?? 0) }}
                          </div>
                        </div>

                        <div class="loyalty-suite-analytics-metric">
                          <div class="loyalty-suite-analytics-metric__label">
                            {{ $t('analyticsGamificationMembersAchievements') }}
                            <q-icon
                              name="info_outline"
                              size="18px"
                              class="loyalty-suite-form__row-hint"
                            >
                              <q-tooltip anchor="top left" self="top left">
                                {{ $t('analyticsGamificationMembersAchievementsHint') }}
                              </q-tooltip>
                            </q-icon>
                          </div>
                          <div class="loyalty-suite-analytics-metric__value">
                            {{ formatNumber(data.gamification?.members?.achievements ?? 0) }}
                          </div>
                        </div>

                        <div class="loyalty-suite-analytics-metric">
                          <div class="loyalty-suite-analytics-metric__label">
                            {{ $t('analyticsGamificationMembersChallenges') }}
                            <q-icon
                              name="info_outline"
                              size="18px"
                              class="loyalty-suite-form__row-hint"
                            >
                              <q-tooltip anchor="top left" self="top left">
                                {{ $t('analyticsGamificationMembersChallengesHint') }}
                              </q-tooltip>
                            </q-icon>
                          </div>
                          <div class="loyalty-suite-analytics-metric__value">
                            {{ formatNumber(data.gamification?.members?.challenges ?? 0) }}
                          </div>
                        </div>
                      </div>

                      <div class="loyalty-suite-analytics-divider"></div>

                      <div class="loyalty-suite-analytics-metrics">
                        <div class="loyalty-suite-analytics-metric">
                          <div class="loyalty-suite-analytics-metric__label">
                            {{ $t('analyticsGamificationEventsRanks') }}
                            <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                              <q-tooltip anchor="top left" self="top left">
                                {{ $t('analyticsGamificationEventsRanksHint') }}
                              </q-tooltip>
                            </q-icon>
                          </div>
                          <div class="loyalty-suite-analytics-metric__value">
                            {{ formatNumber(data.gamification?.events?.ranks ?? 0) }}
                          </div>
                        </div>

                        <div class="loyalty-suite-analytics-metric">
                          <div class="loyalty-suite-analytics-metric__label">
                            {{ $t('analyticsGamificationEventsAchievements') }}
                            <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                              <q-tooltip anchor="top left" self="top left">
                                {{ $t('analyticsGamificationEventsAchievementsHint') }}
                              </q-tooltip>
                            </q-icon>
                          </div>
                          <div class="loyalty-suite-analytics-metric__value">
                            {{ formatNumber(data.gamification?.events?.achievements ?? 0) }}
                          </div>
                        </div>

                        <div class="loyalty-suite-analytics-metric">
                          <div class="loyalty-suite-analytics-metric__label">
                            {{ $t('analyticsGamificationEventsChallenges') }}
                            <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                              <q-tooltip anchor="top left" self="top left">
                                {{ $t('analyticsGamificationEventsChallengesHint') }}
                              </q-tooltip>
                            </q-icon>
                          </div>
                          <div class="loyalty-suite-analytics-metric__value">
                            {{ formatNumber(data.gamification?.events?.challenges ?? 0) }}
                          </div>
                        </div>
                      </div>
                    </div>
                  </template>
                </div>
              </div>
            </div>

            <!-- 2. Members vs Non-Members Performance -->
            <div class="loyalty-suite-analytics__container">
              <div class="loyalty-suite-analytics__content">
                <div class="loyalty-suite-analytics__header">
                  {{ $t('analyticsMembersVsNonMembersTitle') }}
                </div>
                <div class="loyalty-suite-analytics__body">
                  <template v-if="changeLoading">
                    <q-spinner color="primary" size="50px" />
                  </template>
                  <template v-else>
                    <div class="loyalty-suite-analytics-block">
                      <div class="loyalty-suite-analytics-metrics">

                        <div class="loyalty-suite-analytics-metric-column">
                          <div class="loyalty-suite-analytics-metric">
                            <div class="loyalty-suite-analytics-metric__label">
                              {{ $t('analyticsTotalRevenue') }}
                              <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                                <q-tooltip anchor="top left" self="top left">
                                  {{ $t('analyticsTotalRevenueHint') }}
                                </q-tooltip>
                              </q-icon>
                            </div>
                            <div class="loyalty-suite-analytics-metric__value">
                              {{ formatCurrency(Number(data.overview?.revenue?.total ?? 0), currency, false) }}
                            </div>
                          </div>

                          <div class="loyalty-suite-analytics-metric">
                            <div class="loyalty-suite-analytics-metric__label">
                              {{ $t('analyticsMembersRevenue') }}
                              <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                                <q-tooltip anchor="top left" self="top left">
                                  {{ $t('analyticsMembersRevenueHint') }}
                                </q-tooltip>
                              </q-icon>
                            </div>
                            <div class="loyalty-suite-analytics-metric__value">
                              {{ formatCurrency(Number(data.overview?.members?.revenue ?? 0), currency, false) }}
                            </div>
                          </div>

                          <div class="loyalty-suite-analytics-metric">
                            <div class="loyalty-suite-analytics-metric__label">
                              {{ $t('analyticsNonMembersRevenue') }}
                              <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                                <q-tooltip anchor="top left" self="top left">
                                  {{ $t('analyticsNonMembersRevenueHint') }}
                                </q-tooltip>
                              </q-icon>
                            </div>
                            <div class="loyalty-suite-analytics-metric__value">
                              {{ formatCurrency(Number(data.overview?.nonmembers?.revenue ?? 0), currency, false) }}
                            </div>
                          </div>

                        </div>
                        <div class="loyalty-suite-analytics-metric-column">
                          <div class="loyalty-suite-analytics-metric">
                            <div class="loyalty-suite-analytics-chart">
                              <canvas
                                ref="membersChartRef"
                                v-show="hasMembersData"
                              ></canvas>

                              <div
                                v-if="!hasMembersData"
                                class="loyalty-suite-analytics-chart__placeholder"
                              >
                                {{ $t('analyticsNotEnoughData') }}
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>

                      <div class="loyalty-suite-analytics-divider"></div>

                      <div class="loyalty-suite-analytics-two-columns">
                        <div class="loyalty-suite-analytics-column">
                          <div class="loyalty-suite-analytics-column__title">
                            {{ $t('analyticsMembersLabel') }}
                          </div>

                          <div class="loyalty-suite-analytics-metrics">

                            <div class="loyalty-suite-analytics-metric">
                              <div class="loyalty-suite-analytics-metric__label">
                                {{ $t('analyticsMembersOrders') }}
                                <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                                  <q-tooltip anchor="top left" self="top left">
                                    {{ $t('analyticsMembersOrdersHint') }}
                                  </q-tooltip>
                                </q-icon>
                              </div>
                              <div class="loyalty-suite-analytics-metric__value">
                                {{ formatNumber(data.overview?.members?.orders ?? 0) }}
                              </div>
                            </div>

                            <div class="loyalty-suite-analytics-metric">
                              <div class="loyalty-suite-analytics-metric__label">
                                {{ $t('analyticsMembersAOV') }}
                                <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                                  <q-tooltip anchor="top left" self="top left">
                                    {{ $t('analyticsMembersAOVHint') }}
                                  </q-tooltip>
                                </q-icon>
                              </div>
                              <div class="loyalty-suite-analytics-metric__value">
                                {{ formatCurrency(Number(data.overview?.members?.aov ?? 0), currency, false) }}
                              </div>
                            </div>

                            <div class="loyalty-suite-analytics-metric">
                              <div class="loyalty-suite-analytics-metric__label">
                                {{ $t('analyticsMembersFrequency') }}
                                <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                                  <q-tooltip anchor="top left" self="top left">
                                    {{ $t('analyticsMembersFrequencyHint') }}
                                  </q-tooltip>
                                </q-icon>
                              </div>
                              <div class="loyalty-suite-analytics-metric__value">
                                {{ formatNumber(data.overview?.members?.frequency ?? 0, 2) }}
                              </div>
                            </div>

                            <div class="loyalty-suite-analytics-metric">
                              <div class="loyalty-suite-analytics-metric__label">
                                {{ $t('analyticsMembersRevenuePerMember') }}
                                <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                                  <q-tooltip anchor="top left" self="top left">
                                    {{ $t('analyticsMembersRevenuePerMemberHint') }}
                                  </q-tooltip>
                                </q-icon>
                              </div>
                              <div class="loyalty-suite-analytics-metric__value">
                                {{ formatCurrency(Number(data.overview?.members?.revenue_per_member ?? 0), currency, false) }}
                              </div>
                            </div>

                            <div class="loyalty-suite-analytics-metric">
                              <div class="loyalty-suite-analytics-metric__label">
                                {{ $t('analyticsMembersRevenueShare') }}
                                <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                                  <q-tooltip anchor="top left" self="top left">
                                    {{ $t('analyticsMembersRevenueShareHint') }}
                                  </q-tooltip>
                                </q-icon>
                              </div>
                              <div class="loyalty-suite-analytics-metric__value">
                                {{ formatPercent(data.overview?.revenue?.share_members ?? 0) }}
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>

                      <div class="loyalty-suite-analytics-divider"></div>

                      <div class="loyalty-suite-analytics-two-columns">
                        <div class="loyalty-suite-analytics-column">
                          <div class="loyalty-suite-analytics-column__title">
                            {{ $t('analyticsNonMembersLabel') }}
                          </div>
                          <div class="loyalty-suite-analytics-metrics">

                            <div class="loyalty-suite-analytics-metric">
                              <div class="loyalty-suite-analytics-metric__label">
                                {{ $t('analyticsNonMembersOrders') }}
                                <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                                  <q-tooltip anchor="top left" self="top left">
                                    {{ $t('analyticsNonMembersOrdersHint') }}
                                  </q-tooltip>
                                </q-icon>
                              </div>
                              <div class="loyalty-suite-analytics-metric__value">
                                {{ formatNumber(data.overview?.nonmembers?.orders ?? 0) }}
                              </div>
                            </div>

                            <div class="loyalty-suite-analytics-metric">
                              <div class="loyalty-suite-analytics-metric__label">
                                {{ $t('analyticsNonMembersAOV') }}
                                <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                                  <q-tooltip anchor="top left" self="top left">
                                    {{ $t('analyticsNonMembersAOVHint') }}
                                  </q-tooltip>
                                </q-icon>
                              </div>
                              <div class="loyalty-suite-analytics-metric__value">
                                {{ formatCurrency(Number(data.overview?.nonmembers?.aov ?? 0), currency, false) }}
                              </div>
                            </div>

                            <div class="loyalty-suite-analytics-metric">
                              <div class="loyalty-suite-analytics-metric__label">
                                {{ $t('analyticsNonMembersFrequency') }}
                                <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                                  <q-tooltip anchor="top left" self="top left">
                                    {{ $t('analyticsNonMembersFrequencyHint') }}
                                  </q-tooltip>
                                </q-icon>
                              </div>
                              <div class="loyalty-suite-analytics-metric__value">
                                {{ formatNumber(data.overview?.nonmembers?.frequency ?? 0, 2) }}
                              </div>
                            </div>

                            <!-- New: revenue per non-member -->
                            <div class="loyalty-suite-analytics-metric">
                              <div class="loyalty-suite-analytics-metric__label">
                                {{ $t('analyticsNonMembersRevenuePerNonMember') }}
                                <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                                  <q-tooltip anchor="top left" self="top left">
                                    {{ $t('analyticsNonMembersRevenuePerNonMemberHint') }}
                                  </q-tooltip>
                                </q-icon>
                              </div>
                              <div class="loyalty-suite-analytics-metric__value">
                                {{ formatCurrency(Number(data.overview?.nonmembers?.revenue_per_nonmember ?? 0), currency, false) }}
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </template>
                </div>
              </div>
            </div>

            <!-- 3. Points & Balances -->
            <div class="loyalty-suite-analytics__container">
              <div class="loyalty-suite-analytics__content">
                <div class="loyalty-suite-analytics__header">
                  {{ $t('analyticsPointsTitle') }}
                </div>
                <div class="loyalty-suite-analytics__body">
                  <template v-if="changeLoading">
                    <q-spinner color="primary" size="50px" />
                  </template>
                  <template v-else>
                    <div class="loyalty-suite-analytics-block">

                      <div class="loyalty-suite-analytics-metrics">
                        <div class="loyalty-suite-analytics-metric-column">

                          <div class="loyalty-suite-analytics-metric">
                            <div class="loyalty-suite-analytics-metric__label">
                              {{ $t('analyticsPointsIssued') }}
                              <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                                <q-tooltip anchor="top left" self="top left">
                                  {{ $t('analyticsPointsIssuedHint') }}
                                </q-tooltip>
                              </q-icon>
                            </div>
                            <div class="loyalty-suite-analytics-metric__value">
                              {{ formatNumber(data.points?.points?.issued ?? 0) }}
                            </div>
                          </div>

                          <div class="loyalty-suite-analytics-metric">
                            <div class="loyalty-suite-analytics-metric__label">
                              {{ $t('analyticsPointsRedeemed') }}
                              <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                                <q-tooltip anchor="top left" self="top left">
                                  {{ $t('analyticsPointsRedeemedHint') }}
                                </q-tooltip>
                              </q-icon>
                            </div>
                            <div class="loyalty-suite-analytics-metric__value">
                              {{ formatNumber(data.points?.points?.redeemed ?? 0) }}
                            </div>
                          </div>

                          <div class="loyalty-suite-analytics-metric">
                            <div class="loyalty-suite-analytics-metric__label">
                              {{ $t('analyticsPointsTotalBalance') }}
                              <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                                <q-tooltip anchor="top left" self="top left">
                                  {{ $t('analyticsPointsTotalBalanceHint') }}
                                </q-tooltip>
                              </q-icon>
                            </div>
                            <div class="loyalty-suite-analytics-metric__value">
                              {{ formatNumber(data.points?.balances?.total_balance ?? 0) }}
                            </div>
                          </div>

                        </div>
                        <div class="loyalty-suite-analytics-metric-column">
                          <div class="loyalty-suite-analytics-chart loyalty-suite-analytics-chart--points">
                            <canvas
                              ref="pointsChartRef"
                              v-show="hasPointsData"
                            ></canvas>

                            <div
                              v-if="!hasPointsData"
                              class="loyalty-suite-analytics-chart__placeholder"
                            >
                              {{ $t('analyticsNotEnoughData') }}
                            </div>
                          </div>
                        </div>
                      </div>

                      <div class="loyalty-suite-analytics-divider"></div>

                      <div class="loyalty-suite-analytics-metrics">
                        <div class="loyalty-suite-analytics-metric">
                          <div class="loyalty-suite-analytics-metric__label">
                            {{ $t('analyticsPointsIssuedValue') }}
                            <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                              <q-tooltip anchor="top left" self="top left">
                                {{ $t('analyticsPointsIssuedValueHint') }}
                              </q-tooltip>
                            </q-icon>
                          </div>
                          <div class="loyalty-suite-analytics-metric__value">
                            {{ formatCurrency(Number(data.points?.monetary?.totals?.issued_value ?? 0), currency, false) }}
                          </div>
                        </div>

                        <div class="loyalty-suite-analytics-metric">
                          <div class="loyalty-suite-analytics-metric__label">
                            {{ $t('analyticsPointsRedeemedValue') }}
                            <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                              <q-tooltip anchor="top left" self="top left">
                                {{ $t('analyticsPointsRedeemedValueHint') }}
                              </q-tooltip>
                            </q-icon>
                          </div>
                          <div class="loyalty-suite-analytics-metric__value">
                            {{ formatCurrency(Number(data.points?.monetary?.totals?.redeemed_value ?? 0), currency, false) }}
                          </div>
                        </div>

                        <div class="loyalty-suite-analytics-metric">
                          <div class="loyalty-suite-analytics-metric__label">
                            {{ $t('analyticsPointsBalanceValue') }}
                            <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                              <q-tooltip anchor="top left" self="top left">
                                {{ $t('analyticsPointsBalanceValueHint') }}
                              </q-tooltip>
                            </q-icon>
                          </div>
                          <div class="loyalty-suite-analytics-metric__value">
                            {{ formatCurrency(Number(data.points?.monetary?.totals?.balance_value ?? 0), currency, false) }}
                          </div>
                        </div>
                      </div>

                      <div class="loyalty-suite-analytics-divider"></div>

                      <div class="loyalty-suite-analytics-metrics">
                        <div class="loyalty-suite-analytics-metric">
                          <div class="loyalty-suite-analytics-metric__label">
                            {{ $t('analyticsPointsRedemptionRate') }}
                            <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                              <q-tooltip anchor="top left" self="top left">
                                {{ $t('analyticsPointsRedemptionRateHint') }}
                              </q-tooltip>
                            </q-icon>
                          </div>
                          <div class="loyalty-suite-analytics-metric__value">
                            {{ formatPercent(data.points?.points?.redemption_rate ?? 0) }}
                          </div>
                        </div>

                        <div class="loyalty-suite-analytics-metric">
                          <div class="loyalty-suite-analytics-metric__label">
                            {{ $t('analyticsPointsBreakageRate') }}
                            <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                              <q-tooltip anchor="top left" self="top left">
                                {{ $t('analyticsPointsBreakageRateHint') }}
                              </q-tooltip>
                            </q-icon>
                          </div>
                          <div class="loyalty-suite-analytics-metric__value">
                            {{ formatPercent(data.points?.points?.breakage_rate ?? 0) }}
                          </div>
                        </div>
                      </div>
                    </div>
                  </template>
                </div>
              </div>
            </div>

            <!-- 4. Rewards Performance -->
            <div class="loyalty-suite-analytics__container">
              <div class="loyalty-suite-analytics__content">
                <div class="loyalty-suite-analytics__header">
                  {{ $t('analyticsRewardsTitle') }}
                </div>
                <div class="loyalty-suite-analytics__body">
                  <template v-if="changeLoading">
                    <q-spinner color="primary" size="50px" />
                  </template>
                  <template v-else>
                    <div class="loyalty-suite-analytics-block">
                      <div class="loyalty-suite-analytics-metrics">

                        <div class="loyalty-suite-analytics-metric-column">
                          <div class="loyalty-suite-analytics-metric">
                            <div class="loyalty-suite-analytics-metric__label">
                              {{ $t('analyticsRewardsIssued') }}
                              <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                                <q-tooltip anchor="top left" self="top left">
                                  {{ $t('analyticsRewardsIssuedHint') }}
                                </q-tooltip>
                              </q-icon>
                            </div>
                            <div class="loyalty-suite-analytics-metric__value">
                              {{ formatNumber(data.rewards?.totals?.issued ?? 0) }}
                            </div>
                          </div>

                          <div class="loyalty-suite-analytics-metric">
                            <div class="loyalty-suite-analytics-metric__label">
                              {{ $t('analyticsRewardsUsed') }}
                              <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                                <q-tooltip anchor="top left" self="top left">
                                  {{ $t('analyticsRewardsUsedHint') }}
                                </q-tooltip>
                              </q-icon>
                            </div>
                            <div class="loyalty-suite-analytics-metric__value">
                              {{ formatNumber(data.rewards?.totals?.used ?? 0) }}
                            </div>
                          </div>

                          <div class="loyalty-suite-analytics-metric">
                            <div class="loyalty-suite-analytics-metric__label">
                              {{ $t('analyticsRewardsExpired') }}
                              <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                                <q-tooltip anchor="top left" self="top left">
                                  {{ $t('analyticsRewardsExpiredHint') }}
                                </q-tooltip>
                              </q-icon>
                            </div>
                            <div class="loyalty-suite-analytics-metric__value">
                              {{ formatNumber(data.rewards?.totals?.expired ?? 0) }}
                            </div>
                          </div>
                        </div>

                        <div class="loyalty-suite-analytics-metric-column">
                          <div class="loyalty-suite-analytics-metric">
                            <div class="loyalty-suite-analytics-chart">
                              <canvas
                                ref="rewardsChartRef"
                                v-show="hasRewardsData"
                              ></canvas>

                              <div
                                v-if="!hasRewardsData"
                                class="loyalty-suite-analytics-chart__placeholder"
                              >
                                {{ $t('analyticsNotEnoughData') }}
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>

                      <div class="loyalty-suite-analytics-divider"></div>

                      <div class="loyalty-suite-analytics-metrics">
                        <div class="loyalty-suite-analytics-metric">
                          <div class="loyalty-suite-analytics-metric__label">
                            {{ $t('analyticsRewardsRedemptionRate') }}
                            <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                              <q-tooltip anchor="top left" self="top left">
                                {{ $t('analyticsRewardsRedemptionRateHint') }}
                              </q-tooltip>
                            </q-icon>
                          </div>
                          <div class="loyalty-suite-analytics-metric__value">
                            {{ formatPercent(data.rewards?.totals?.redemption_rate ?? 0) }}
                          </div>
                        </div>

                        <div class="loyalty-suite-analytics-metric">
                          <div class="loyalty-suite-analytics-metric__label">
                            {{ $t('analyticsRewardsBreakageRate') }}
                            <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                              <q-tooltip anchor="top left" self="top left">
                                {{ $t('analyticsRewardsBreakageRateHint') }}
                              </q-tooltip>
                            </q-icon>
                          </div>
                          <div class="loyalty-suite-analytics-metric__value">
                            {{ formatPercent(data.rewards?.totals?.breakage_rate ?? 0) }}
                          </div>
                        </div>
                      </div>
                    </div>
                  </template>
                </div>
              </div>
            </div>

            <!-- 5. Top Performing Ranks, Achievements & Challenges -->
            <div class="loyalty-suite-analytics__container loyalty-suite-analytics__container--table">
              <div class="loyalty-suite-analytics__content">
                <div class="loyalty-suite-analytics__header">
                  {{ $t('analyticsUpliftTitle') }}
                  <q-icon name="info_outline" size="18px" class="loyalty-suite-form__row-hint">
                    <q-tooltip anchor="top left" self="top left">
                      {{ $t('analyticsUpliftHint') }}
                    </q-tooltip>
                  </q-icon>
                </div>
                <div class="loyalty-suite-analytics__body">
                  <template v-if="changeLoading">
                    <q-spinner color="primary" size="50px" />
                  </template>
                  <template v-else>
                    <div class="loyalty-suite-analytics-block loyalty-suite-analytics-block--full">
                      <template v-if="(data.uplift?.entities ?? []).length === 0">
                        <div class="loyalty-suite-analytics-empty">
                          {{ $t('analyticsUpliftEmpty') }}
                        </div>
                      </template>
                      <template v-else>
                        <table class="loyalty-suite-analytics-table">
                          <thead>
                            <tr>
                              <th>
                                {{ $t('analyticsUpliftType') }}
                              </th>
                              <th>{{ $t('analyticsUpliftName') }}</th>
                              <th>{{ $t('analyticsUpliftRevenue') }}</th>
                              <th>{{ $t('analyticsUpliftCustomers') }}</th>
                              <th>{{ $t('analyticsUpliftRevenuePerCustomer') }}</th>
                            </tr>
                          </thead>
                          <tbody>
                            <tr
                              v-for="entity in data.uplift.entities"
                              :key="entity.type + '-' + entity.entity_id"
                            >
                              <td>
                                {{ formatUpliftType(entity.type) }}
                              </td>
                              <td>
                                {{ entity.name || '—' }}
                              </td>
                              <td>
                                {{ formatCurrency(Number(entity.revenue ?? 0), currency, false) }}
                              </td>
                              <td>
                                {{ formatNumber(entity.customers ?? 0) }}
                              </td>
                              <td>
                                {{ formatCurrency(Number(entity.revenue_per_customer ?? 0), currency, false) }}
                              </td>
                            </tr>
                          </tbody>
                        </table>
                      </template>
                    </div>
                  </template>
                </div>
              </div>
            </div>
          </div>

          <q-dialog v-model="periodDialog" class="loyalty-suite-analytics__period-dialog">
            <div class="loyalty-suite-analytics__period-dialog-container">
              <div class="loyalty-suite-analytics__period-dialog-content">
                <div class="loyalty-suite-analytics__period-dialog-presets">
                  <span @click="applyPreset('this_month')">
                    {{ $t('analyticsThisMonth') }}
                  </span>
                  <span @click="applyPreset('last_month')">
                    {{ $t('analyticsLastMonth') }}
                  </span>
                  <span @click="applyPreset('this_year')">
                    {{ $t('analyticsThisYear') }}
                  </span>
                  <span @click="applyPreset('last_year')">
                    {{ $t('analyticsLastYear') }}
                  </span>
                  <span @click="setAllTime">
                    {{ $t('allTime') }}
                  </span>
                </div>
                <q-date
                  v-model="tempRange"
                  range
                  :mask="dateMask"
                  :locale="datePickerLocale"
                  :first-day-of-week="wpStartOfWeek"
                />
              </div>
              <div class="loyalty-suite-analytics__period-dialog-actions">
                <q-btn
                  color="negative"
                  :label="$t('cancel')"
                  v-close-popup
                />
                <q-btn
                  color="primary"
                  :label="$t('submit')"
                  @click="applyPeriod"
                />
              </div>
            </div>
          </q-dialog>
        </div>
      </template>
    </template>
  </q-scroll-area>
</template>

<script lang="ts">
import {
  defineComponent,
  ref,
  onBeforeMount,
  computed,
  watch,
  nextTick,
  onBeforeUnmount,
} from 'vue';
import { useI18n } from 'vue-i18n';
import { Chart } from 'chart.js/auto';
import { formatCurrency } from '../utils/formatters';

type PeriodPreset = 'this_year' | 'last_year' | 'this_month' | 'last_month';
type DateRangeModel = { from?: string | null; to?: string | null } | string | null;

export default defineComponent({
  setup() {
    const { t } = useI18n();
    const loading = ref(true);
    const changeLoading = ref(false);
    const error = ref<string | null>(null);
    const apiRoutes = window.loyalty_suite_admin_data.apiRoutes;
    const isWooEnabled = window.loyalty_suite_admin_data.isWooEnabled;
    const nonce = window.loyalty_suite_admin_data.nonce;
    const isPro = window.loyalty_suite_admin_data.isPro;
    const currency = ref<any>({ symbol: '$' });
    const data = ref<any>({});
    const getProLink = window.loyalty_suite_admin_data.getProLink;

    const dateMask = 'YYYY-MM-DD';

    const proFeatures = [
      {
        icon: 'insights',
        title: t('analyticsOverviewTitle'),
        description: t('proAnalyticsOverviewDescription'),
      },
      {
        icon: 'group',
        title: t('analyticsMembersVsNonMembersTitle'),
        description: t('proAnalyticsMembersVsNonMembersDescription'),
      },
      {
        icon: 'leaderboard',
        title: t('analyticsPointsTitle'),
        description: t('proAnalyticsPointsDescription'),
      },
      {
        icon: 'account_balance_wallet',
        title: t('analyticsPointsBalanceValue'),
        description: t('proAnalyticsPointsMonetaryDescription'),
      },
      {
        icon: 'card_giftcard',
        title: t('analyticsRewardsTitle'),
        description: t('proAnalyticsRewardsDescription'),
      },
      {
        icon: 'trending_up',
        title: t('analyticsUpliftTitle'),
        description: t('proAnalyticsUpliftDescription'),
      },
    ];

    const wpDateFormat = ref<string>(window.loyalty_suite_admin_data?.dateFormat || 'Y-m-d');
    const wpStartOfWeek = window.loyalty_suite_admin_data?.startOfWeek ?? 1;

    const datePickerLocale = {
      days: [
        t('Sunday'),
        t('Monday'),
        t('Tuesday'),
        t('Wednesday'),
        t('Thursday'),
        t('Friday'),
        t('Saturday'),
      ],
      daysShort: [
        t('Sun'),
        t('Mon'),
        t('Tue'),
        t('Wed'),
        t('Thu'),
        t('Fri'),
        t('Sat'),
      ],
      months: [
        t('January'),
        t('February'),
        t('March'),
        t('April'),
        t('May'),
        t('June'),
        t('July'),
        t('August'),
        t('September'),
        t('October'),
        t('November'),
        t('December'),
      ],
      monthsShort: [
        t('Jan'),
        t('Feb'),
        t('Mar'),
        t('Apr'),
        t('MayShort'),
        t('Jun'),
        t('Jul'),
        t('Aug'),
        t('Sep'),
        t('Oct'),
        t('Nov'),
        t('Dec'),
      ],
    };

    const periodRange = ref<{ from: string; to: string } | null>(null);
    const tempRange = ref<DateRangeModel>(null);
    const periodDialog = ref(false);

    const normalizeRange = (val: any): { from: string; to: string } | null => {
      if (!val) return null;

      if (typeof val === 'string') {
        return { from: val, to: val };
      }

      const from = val.from || val.to;
      const to = val.to || val.from;

      if (!from) return null;

      return { from, to: to || from };
    };

    const formatDateLabel = (dateStr: string): string => {
      if (!dateStr) return '';

      const parts = dateStr.split('-');
      if (parts.length !== 3) return dateStr;

      const year = Number(parts[0]);
      const monthIndex = Number(parts[1]) - 1;
      const day = Number(parts[2]);

      if (!year || monthIndex < 0 || monthIndex > 11 || !day) {
        return dateStr;
      }

      const monthName = datePickerLocale.months[monthIndex] ?? '';
      const monthShort = datePickerLocale.monthsShort[monthIndex] ?? '';

      switch (wpDateFormat.value) {
        case 'F j, Y':
          return `${monthName} ${day}, ${year}`;
        case 'Y-m-d':
          return `${year}-${String(monthIndex + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
        case 'm/d/Y':
          return `${String(monthIndex + 1).padStart(2, '0')}/${String(day).padStart(2, '0')}/${year}`;
        case 'd/m/Y':
          return `${String(day).padStart(2, '0')}/${String(monthIndex + 1).padStart(2, '0')}/${year}`;
        case 'Y/m/d':
          return `${year}/${String(monthIndex + 1).padStart(2, '0')}/${String(day).padStart(2, '0')}`;
        case 'd.m.Y':
          return `${String(day).padStart(2, '0')}.${String(monthIndex + 1).padStart(2, '0')}.${year}`;
        case 'j. F Y':
          return `${day}. ${monthName} ${year}`;
        case 'j F Y':
          return `${day} ${monthName} ${year}`;
        default:
          return `${year}-${String(monthIndex + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
      }
    };

    const periodLabel = computed(() => {
      if (!periodRange.value) {
        return t('allTime');
      }

      const { from, to } = periodRange.value;
      if (!from || !to) {
        return t('allTime');
      }

      const fromLabel = formatDateLabel(from);
      const toLabel = formatDateLabel(to);

      if (from === to) {
        return fromLabel || t('allTime');
      }

      return `${fromLabel} – ${toLabel}`;
    });

    const openPeriodDialog = () => {
      if (periodRange.value) {
        const { from, to } = periodRange.value;

        if (from && to && from === to) {
          tempRange.value = from;
        } else {
          tempRange.value = { from, to };
        }
      } else {
        tempRange.value = null;
      }

      periodDialog.value = true;
    };

    const setAllTime = async () => {
      periodDialog.value = false;
      periodRange.value = null;
      await fetchData();
    };

    const formatDateApi = (date: Date): string => {
      const y = date.getFullYear();
      const m = String(date.getMonth() + 1).padStart(2, '0');
      const d = String(date.getDate()).padStart(2, '0');
      return `${y}-${m}-${d}`;
    };

    const applyPreset = async (preset: PeriodPreset) => {
      const now = new Date();
      const year = now.getFullYear();
      const month = now.getMonth();

      let start: Date;
      let end: Date;

      switch (preset) {
        case 'this_year':
          start = new Date(year, 0, 1);
          end = new Date(year, 11, 31);
          break;

        case 'last_year':
          start = new Date(year - 1, 0, 1);
          end = new Date(year - 1, 11, 31);
          break;

        case 'this_month':
          start = new Date(year, month, 1);
          end = new Date(year, month + 1, 0);
          break;

        case 'last_month': {
          const lastMonthDate = new Date(year, month - 1, 1);
          const y = lastMonthDate.getFullYear();
          const m = lastMonthDate.getMonth();
          start = new Date(y, m, 1);
          end = new Date(y, m + 1, 0);
          break;
        }
      }

      const fromStr = formatDateApi(start);
      const toStr = formatDateApi(end);

      periodRange.value = { from: fromStr, to: toStr };
      tempRange.value = { from: fromStr, to: toStr };

      periodDialog.value = false;

      await fetchData(fromStr, toStr);
    };

    const applyPeriod = async () => {
      const normalized = normalizeRange(tempRange.value);

      if (!normalized) {
        return;
      }

      const { from, to } = normalized;

      periodDialog.value = false;
      periodRange.value = { from, to };

      await fetchData(from, to);
    };

    const formatNumber = (value: number, decimals?: number): string => {
      if (!Number.isFinite(value)) {
        return '0';
      }

      if (typeof decimals === 'number') {
        return value.toFixed(decimals);
      }

      const rounded = Number(value.toFixed(2));
      return String(rounded);
    };

    const formatPercent = (value: number, decimals?: number): string => {
      if (!Number.isFinite(value)) {
        return '0%';
      }

      const percent = value * 100;

      if (typeof decimals === 'number') {
        return `${percent.toFixed(decimals)}%`;
      }

      const rounded = Number(percent.toFixed(2));
      return `${rounded}%`;
    };

    const formatUpliftType = (type: string): string => {
      if (type === 'rank') {
        return t('analyticsUpliftTypeRank');
      }
      if (type === 'achievement') {
        return t('analyticsUpliftTypeAchievement');
      }
      if (type === 'challenge') {
        return t('analyticsUpliftTypeChallenge');
      }

      return type;
    };

    const fetchCurrency = async () => {
      try {
        const response = await fetch(apiRoutes.admin.currency, {
          method: 'GET',
          headers: {
            'X-WP-Nonce': nonce,
            'Content-Type': 'application/json',
          },
        });

        if (!response.ok) {
          throw new Error(response.status.toString());
        }

        const responseData = await response.json();
        currency.value = responseData;
      } catch (err: any) {
        error.value = err.message === '401' ? '401' : err.message || t('couldNotFetchData');
        console.error('API Error:', error.value);
      }
    };

    const buildApiUrl = (base: string, params: Record<string, string | undefined>) => {
      try {
        const url = new URL(base, window.location.origin);
        Object.entries(params).forEach(([key, value]) => {
          if (value) {
            url.searchParams.set(key, value);
          }
        });
        return url.toString();
      } catch {
        return base;
      }
    };

    const fetchData = async (startDate?: string, endDate?: string) => {
      if (!isPro || !isWooEnabled) {
        return;
      }

      changeLoading.value = true;

      try {
        const requestUrl = buildApiUrl(apiRoutes.admin.analytics, {
          start_date: startDate,
          end_date: endDate,
        });

        const response = await fetch(requestUrl, {
          method: 'GET',
          headers: {
            'X-WP-Nonce': nonce,
            'Content-Type': 'application/json',
          },
        });

        const responseData = await response.json().catch(() => null);

        if (!response.ok) {
          error.value = responseData?.error || t('couldNotFetchData');
          return;
        }

        data.value = {
          ...responseData,
        };
      } catch (err) {
        error.value = err instanceof Error ? err.message : t('couldNotFetchData');
        console.error('API Error:', error.value);
      } finally {
        changeLoading.value = false;
      }
    };

    /**
     * CHART.JS PART
     */
    const overviewChartRef = ref<HTMLCanvasElement | null>(null);
    const membersChartRef = ref<HTMLCanvasElement | null>(null);
    const pointsChartRef = ref<HTMLCanvasElement | null>(null);
    const rewardsChartRef = ref<HTMLCanvasElement | null>(null);

    const overviewChart = ref<Chart | null>(null);
    const membersChart = ref<Chart | null>(null);
    const pointsChart = ref<Chart | null>(null);
    const rewardsChart = ref<Chart | null>(null);

    const hasOverviewData = ref(true);
    const hasMembersData = ref(true);
    const hasPointsData = ref(true);
    const hasRewardsData = ref(true);

    const createOrUpdatePieChart = (
      chartRef: { value: Chart | null },
      canvas: HTMLCanvasElement | null,
      labels: string[],
      values: number[],
      title: string,
      valueFormatter?: (value: number) => string
    ) => {
      if (!canvas) return;
      const ctx = canvas.getContext('2d');
      if (!ctx) return;

      if (chartRef.value) {
        chartRef.value.destroy();
        chartRef.value = null;
      }

      const dataSum = values.reduce(
        (sum, v) => sum + (Number.isFinite(v) ? v : 0),
        0
      );
      const safeValues = values.map((v) => (Number.isFinite(v) ? v : 0));

      const baseColors = [
        'rgba(99, 102, 241, 1)',
        'rgba(242, 192, 55, 1)',
        'rgba(33, 186, 69, 1)',
        'rgba(148, 163, 184, 1)',
      ];

      const backgroundColors = safeValues.map(
        (_val, idx) => baseColors[idx % baseColors.length]
      );

      const chartData = {
        labels,
        datasets: [
          {
            label: title,
            data: safeValues,
            backgroundColor: backgroundColors,
            borderColor: backgroundColors,
            borderWidth: 1,
          },
        ],
      };

      const tooltipOptions = {
        callbacks: {
          label: (context: any) => {
            const label = context.label || '';
            const rawValue = Number(context.parsed) || 0;

            const formattedValue = valueFormatter
              ? valueFormatter(rawValue)
              : rawValue.toFixed(2);

            const percent =
              dataSum > 0 ? ((rawValue / dataSum) * 100).toFixed(2) : '0.00';

            return `${label}: ${formattedValue} (${percent}%)`;
          },
        },
      };

      chartRef.value = new Chart(ctx, {
        type: 'pie',
        data: chartData as any,
        options: {
          responsive: true,
          maintainAspectRatio: false,
          plugins: {
            legend: {
              display: false,
            },
            tooltip: tooltipOptions,
          },
        },
      });
    };

    const createOrUpdateOverviewChart = () => {
      const totalMembers = Number(data.value?.overview?.total_members ?? 0);
      const totalUsers = Number(data.value?.overview?.total_users ?? 0);
      const nonMembers = Math.max(totalUsers - totalMembers, 0);

      const sum = totalMembers + nonMembers;

      hasOverviewData.value = totalUsers > 0 && sum > 0;

      if (!hasOverviewData.value) {
        if (overviewChart.value) {
          overviewChart.value.destroy();
          overviewChart.value = null;
        }
        return;
      }

      createOrUpdatePieChart(
        overviewChart,
        overviewChartRef.value,
        [t('analyticsMembersLabel'), t('analyticsNonMembersLabel')],
        [totalMembers, nonMembers],
        t('analyticsOverviewTitle'),
        (value: number) => formatNumber(value, 0)
      );
    };

    const createOrUpdateMembersChart = () => {
      const membersRevenue = Number(data.value?.overview?.members?.revenue ?? 0);
      const nonMembersRevenue = Number(data.value?.overview?.nonmembers?.revenue ?? 0);

      const sum = membersRevenue + nonMembersRevenue;
      hasMembersData.value = sum > 0;

      if (!hasMembersData.value) {
        if (membersChart.value) {
          membersChart.value.destroy();
          membersChart.value = null;
        }
        return;
      }

      createOrUpdatePieChart(
        membersChart,
        membersChartRef.value,
        [
          t('analyticsMembersRevenue'),
          t('analyticsNonMembersRevenue'),
        ],
        [membersRevenue, nonMembersRevenue],
        t('analyticsMembersVsNonMembersTitle'),
        (value: number) => formatCurrency(value, currency.value, false)
      );
    };

    const createOrUpdatePointsChart = () => {
      const issued = Number(data.value?.points?.points?.issued ?? 0);
      const redeemedRaw = Number(data.value?.points?.points?.redeemed ?? 0);

      if (issued <= 0) {
        hasPointsData.value = false;
        if (pointsChart.value) {
          pointsChart.value.destroy();
          pointsChart.value = null;
        }
        return;
      }

      const redeemed = Math.max(redeemedRaw, 0);
      const unredeemed = Math.max(issued - redeemed, 0);

      hasPointsData.value = redeemed > 0 || unredeemed > 0;

      if (!hasPointsData.value) {
        if (pointsChart.value) {
          pointsChart.value.destroy();
          pointsChart.value = null;
        }
        return;
      }

      createOrUpdatePieChart(
        pointsChart,
        pointsChartRef.value,
        [
          t('analyticsPointsUnredeemed'),
          t('analyticsPointsRedeemed'),
        ],
        [unredeemed, redeemed],
        t('analyticsPointsTitle'),
        (value: number) => formatNumber(value, 2)
      );
    };

    const createOrUpdateRewardsChart = () => {
      const issued = Number(data.value?.rewards?.totals?.issued ?? 0);
      const usedRaw = Number(data.value?.rewards?.totals?.used ?? 0);
      const expiredRaw = Number(data.value?.rewards?.totals?.expired ?? 0);

      if (issued <= 0) {
        hasRewardsData.value = false;
        if (rewardsChart.value) {
          rewardsChart.value.destroy();
          rewardsChart.value = null;
        }
        return;
      }

      const used = Math.max(usedRaw, 0);
      const expired = Math.max(expiredRaw, 0);
      let unused = issued - used - expired;
      if (unused < 0) {
        unused = 0;
      }

      hasRewardsData.value = used > 0 || expired > 0 || unused > 0;

      if (!hasRewardsData.value) {
        if (rewardsChart.value) {
          rewardsChart.value.destroy();
          rewardsChart.value = null;
        }
        return;
      }

      createOrUpdatePieChart(
        rewardsChart,
        rewardsChartRef.value,
        [
          t('analyticsRewardsActive'),
          t('analyticsRewardsUsed'),
          t('analyticsRewardsExpired'),
        ],
        [unused, used, expired],
        t('analyticsRewardsTitle')
      );
    };

    const updateAllCharts = () => {
      if (!isPro || !isWooEnabled) return;
      createOrUpdateOverviewChart();
      createOrUpdateMembersChart();
      createOrUpdatePointsChart();
      createOrUpdateRewardsChart();
    };

    watch(
      data,
      () => {
        nextTick(() => {
          updateAllCharts();
        });
      },
      { deep: true }
    );

    onBeforeMount(async () => {
      try {
        if (isPro && isWooEnabled) {
          await Promise.all([fetchData(), fetchCurrency()]);
        }
      } catch (err) {
        console.error('Api error:', err);
      } finally {
        loading.value = false;
        nextTick(() => {
          updateAllCharts();
        });
      }
    });

    onBeforeUnmount(() => {
      [overviewChart, membersChart, pointsChart, rewardsChart].forEach((chartRef) => {
        if (chartRef.value) {
          chartRef.value.destroy();
        }
      });
    });

    return {
      changeLoading,
      loading,
      error,
      data,
      isWooEnabled,
      isPro,
      currency,
      formatNumber,
      formatCurrency,
      formatPercent,
      formatUpliftType,
      periodDialog,
      periodLabel,
      openPeriodDialog,
      setAllTime,
      applyPeriod,
      tempRange,
      datePickerLocale,
      wpStartOfWeek,
      applyPreset,
      getProLink,
      proFeatures,
      overviewChartRef,
      membersChartRef,
      pointsChartRef,
      rewardsChartRef,
      hasRewardsData,
      hasPointsData,
      hasMembersData,
      hasOverviewData,
      dateMask,
    };
  },
});
</script>

<style lang="scss" scoped>
.loyalty-suite-analytics {
  display: flex;
  width: 100%;
  flex-direction: column;

  &__title {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 700px;
    margin-bottom: 25px;

    &-text {
      display: flex;
      font-size: 22px;
    }
  }

  &__period {
    display: flex;
    margin-left: auto;
    position: relative;
    i {
      position: absolute;
      right: 20px;
      top: 50%;
      transform: translateY(-50%);
      color: #0000008a;
      font-size: 24px;
      width: 12px;
    }
  }

  &__period-input {
    display: flex;
    width: auto;
    height: 40px;
    align-items: center;
    padding: 0 24px 0 12px;
    border: 1px solid $border;
    border-radius: 4px;
    background: $white;
    transition: 0.3s;
    cursor: pointer;
    &:hover,
    &:focus {
      outline: none;
      box-shadow: none;
      border-color: $primary;
    }
  }

  &__period-dialog {
    &-container {
      display: flex;
      flex-direction: column;
      background: $white;
      border: 1px solid $border;
      border-radius: 4px;
      padding: 20px 25px;
      box-shadow: $shadow-size $shadow;
    }
    &-content {
      display: flex;
      width: 100%;
      :deep(.q-date) {
        box-shadow: none;
        width: 250px;
        min-width: 250px;
        .q-date__view {
          width: 250px;
          height: auto;
          min-height: auto;
          padding: 0;
        }
        .q-date__calendar-days-container {
          height: 100%;
          min-height: auto;
        }
        .q-btn--dense.q-btn--round {
          width: 30px;
          height: 30px;
        }
      }
    }
    &-presets {
      display: flex;
      width: 100%;
      flex-direction: column;
      margin-right: 30px;
      margin-top: 8px;
      span {
        display: block;
        width: 100%;
        cursor: pointer;
        margin-bottom: 15px;
        transition: 0.3s;
        &:hover {
          color: $primary;
        }
      }
    }
    &-actions {
      display: flex;
      width: 100%;
      justify-content: flex-end;
      margin-top: 20px;
      .q-btn {
        &:first-child {
          margin-right: 10px;
        }
      }
    }
  }

  &__wrapper {
    display: flex;
    flex-direction: column;
    width: 100%;
  }

  &__container {
    display: flex;
    width: 100%;
    max-width: 700px;
    margin: 0 0 20px 0;
    &--table {
      max-width: 1000px;
      .loyalty-suite-analytics__header {
        border-bottom: none;
        padding: 15px 25px 0 25px;
        margin-bottom: -15px;
      }
      .loyalty-suite-analytics__body {
        padding: 25px;
      }
    }
  }

  &__content {
    display: flex;
    flex-direction: column;
    width: 100%;
    background: $white;
    box-shadow: $shadow-size $shadow;
    border-radius: 5px;
  }

  &__header {
    display: flex;
    width: 100%;
    align-items: center;
    padding: 15px 20px;
    font-size: 14px;
    font-weight: 600;
    border-top-left-radius: 5px;
    border-top-right-radius: 5px;
    border-bottom: 1px solid $border;
    .loyalty-suite-form__row-hint {
      margin-left: 5px;
    }
  }

  &__body {
    display: flex;
    width: 100%;
    min-height: 100px;
    justify-content: center;
    align-items: center;
    padding: 10px;
    border-bottom-left-radius: 5px;
    border-bottom-right-radius: 5px;
  }

  &__features {
    display: flex;
    width: 100%;
    padding: 10px;

    &-wrapper {
      display: flex;
      flex-direction: column;
      width: 100%;
      background: $white;
      box-shadow: $shadow-size $shadow;
      border-radius: 5px;
      padding: 25px 25px 15px 25px;
    }

    &-pro {
      display: inline-flex;
      align-items: center;
      justify-content: center;
      padding: 7px 12px;
      background: $primary;
      border-radius: 3px;
      font-size: 16px;
      text-transform: uppercase;
      color: $white;
      margin-right: 10px;
    }

    &-header {
      display: flex;
      align-items: center;
      width: 100%;
      margin-bottom: 15px;
      .q-btn {
        flex-shrink: 0;
        padding: 4px 20px;
        margin: 0 0 0 auto;
      }
    }

    &-title {
      display: flex;
      font-size: 18px;
      align-items: center;
      margin-right: 20px;
    }

    &-list {
      display: flex;
      width: calc(100% + 20px);
      flex-wrap: wrap;
      margin: 0 -10px;
    }

    &-item {
      display: flex;
      width: 25%;
      padding: 10px;
      align-items: flex-start;

      &-wrapper {
        display: flex;
        width: 100%;
        height: 100%;
        flex-direction: column;
        align-items: center;
        border: 1px solid $border;
        padding: 15px;
        border-radius: 5px;
      }

      .q-icon {
        color: $warning;
        font-size: 48px;
        margin-bottom: 15px;
      }

      &-title {
        display: flex;
        width: 100%;
        justify-content: center;
        text-align: center;
        font-size: 14px;
        font-weight: 500;
        margin-bottom: 15px;
      }

      &-text {
        display: flex;
        width: 100%;
        font-size: 12px;
        justify-content: center;
        text-align: center;
      }
    }
  }
}

.loyalty-suite-api-error-message {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 16px;
  background: rgba(244, 67, 54, 0.06);
  border-radius: 4px;
  margin-bottom: 16px;
  color: $negative;
  font-size: 14px;
}

.loyalty-suite-analytics-block {
  width: 100%;
  display: flex;
  flex-direction: column;

  &--full {
    width: 100%;
  }
}

.loyalty-suite-analytics-metrics {
  display: flex;
  flex-wrap: wrap;

  &--single-row {
    margin-top: 5px;
  }
}

.loyalty-suite-analytics-metric {
  display: flex;
  width: 50%;
  flex-direction: column;
  padding: 10px;
  margin-bottom: 10px;

  &__label {
    display: flex;
    align-items: center;
    font-size: 14px;
    margin-bottom: 10px;
    .loyalty-suite-form__row-hint {
      margin-left: 5px;
    }
  }

  &-column {
    display: flex;
    flex-direction: column;
    width: 50%;
    .loyalty-suite-analytics-metric {
      width: 100%;
    }
  }

  &__value {
    font-size: 15px;
    font-weight: 600;
  }
}

.loyalty-suite-analytics-two-columns {
  display: flex;
  flex-wrap: wrap;
}

.loyalty-suite-analytics-column {
  display: flex;
  width: 100%;
  flex-direction: column;
  margin-top: 10px;

  &__title {
    font-size: 14px;
    font-weight: 600;
    color: $primary;
    margin-bottom: 15px;
    padding: 0 10px;
  }
}

.loyalty-suite-analytics-divider {
  width: calc(100% + 20px);
  height: 1px;
  background: $border;
  margin: 5px 0 15px -10px;
}

.loyalty-suite-analytics-section-title {
  font-size: 14px;
  font-weight: 600;
  color: $primary;
  padding: 15px 10px;
}

.loyalty-suite-analytics-empty {
  font-size: 14px;
}

.loyalty-suite-analytics-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 8px;
  font-size: 14px;

  th,
  td {
    padding: 10px 12px;
    text-align: left;
    border: 1px solid $border;
  }

  th {
    font-weight: 500;
    background: $primary;
    color: $white;
    .loyalty-suite-form__row-hint {
      margin-left: 5px;
      display: inline-block;
      color: $white;
    }
  }
}

.loyalty-suite-analytics-chart {
  width: 100%;
  min-height: 190px;
  margin-top: 5px;
  &.loyalty-suite-analytics-chart--points {
    margin-top: 14px;
  }

  canvas {
    width: 100% !important;
    height: 190px !important;
    display: block;
  }
}

.loyalty-suite-analytics-chart__placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 220px;
  font-size: 13px;
  color: $dark;
  text-align: center;
  padding: 0 10px;
}
</style>
