<template>
  <section>
    <h4 class="andale_search_insights-tools-card__heading">{{ labels.title }}</h4>
    <p class="andale_search_insights-tools-card__description">{{ labels.description }}</p>

    <div class="andale_search_insights-tools-form-row andale_search_insights-tools-form-row--spaced">
      <UiButton variant="default" :disabled="loading" @click="runEstimate">
        {{ loading ? labels.running : labels.run }}
      </UiButton>
      <span v-if="error" class="andale_search_insights-tools-card__error">{{ error }}</span>
    </div>

    <div class="andale_search_insights-tools-stats andale_search_insights-tools-stats--subtle">
      <div class="andale_search_insights-tools-stats__row">
        <span>{{ labels.lastEstimateAt }}</span>
        <strong>{{ formattedEstimatedAt }}</strong>
      </div>
      <div class="andale_search_insights-tools-stats__row">
        <span>{{ labels.estimatedTotalRows }}</span>
        <strong>{{ estimate.total_estimated }}</strong>
      </div>
      <div class="andale_search_insights-tools-stats__row">
        <span>{{ labels.estimatedEvents }}</span>
        <strong>{{ estimate.events_estimated }}</strong>
      </div>
      <div class="andale_search_insights-tools-stats__row">
        <span>{{ labels.estimatedSearches }}</span>
        <strong>{{ estimate.searches_estimated }}</strong>
      </div>
      <div class="andale_search_insights-tools-stats__row">
        <span>{{ labels.estimatedSessions }}</span>
        <strong>{{ estimate.sessions_estimated }}</strong>
      </div>
      <div class="andale_search_insights-tools-stats__row">
        <span>{{ labels.wouldDeleteThisRun }}</span>
        <strong>{{ estimate.would_delete_with_cap }}</strong>
      </div>
      <div class="andale_search_insights-tools-stats__row">
        <span>{{ labels.maxRowsPerRun }}</span>
        <strong>{{ estimate.max_rows_per_run }}</strong>
      </div>
      <div class="andale_search_insights-tools-stats__row">
        <span>{{ labels.capHit }}</span>
        <strong>{{ estimate.capped ? labels.yes : labels.no }}</strong>
      </div>
    </div>
  </section>
</template>

<script>
import { computed, reactive, ref } from 'vue';
import UiButton from './ui/UiButton.vue';

export default {
  name: 'RetentionEstimateCardApp',
  components: {
    UiButton,
  },
  setup() {
    const root = document.getElementById('andale_search_insights-retention-estimate-app');
    const rawConfig = root ? root.getAttribute('data-config') : null;
    const config = rawConfig ? JSON.parse(rawConfig) : {};

    const labels = {
      ...{
        title: 'Retention Estimate (Dry Run)',
        description: 'Estimate how many rows are eligible for deletion without making changes.',
        run: 'Estimate Retention (Dry Run)',
        running: 'Estimating…',
        lastEstimateAt: 'Last Estimate At',
        estimatedTotalRows: 'Estimated Total Rows Eligible',
        estimatedEvents: 'Estimated Events',
        estimatedSearches: 'Estimated Searches',
        estimatedSessions: 'Estimated Sessions',
        wouldDeleteThisRun: 'Would Delete This Run (Cap Applied)',
        maxRowsPerRun: 'Max Rows Per Run',
        capHit: 'Estimate Cap Hit',
        yes: 'Yes',
        no: 'No',
        never: 'Never',
        error: 'Unable to run estimate.',
      },
      ...(config.labels || {}),
    };

    const estimate = reactive({
      estimated_at_gmt: '',
      events_estimated: 0,
      searches_estimated: 0,
      sessions_estimated: 0,
      total_estimated: 0,
      would_delete_with_cap: 0,
      max_rows_per_run: 0,
      capped: false,
      ...(config.estimate || {}),
    });

    const loading = ref(false);
    const error = ref('');

    const formattedEstimatedAt = computed(() => {
      if (!estimate.estimated_at_gmt) {
        return labels.never;
      }
      const maybeIso = `${String(estimate.estimated_at_gmt).replace(' ', 'T')}Z`;
      const value = new Date(maybeIso);
      if (Number.isNaN(value.getTime())) {
        return String(estimate.estimated_at_gmt);
      }
      return value.toLocaleString(undefined, { timeZoneName: 'short' });
    });

    const runEstimate = async () => {
      loading.value = true;
      error.value = '';
      try {
        const body = new URLSearchParams();
        body.append('action', 'andale_search_insights_retention_estimate');
        body.append('nonce', String(config.nonce || ''));

        const response = await fetch(String(config.ajaxUrl || ''), {
          method: 'POST',
          credentials: 'same-origin',
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
          },
          body,
        });

        const payload = await response.json();
        if (!response.ok || !payload?.success || !payload?.data) {
          throw new Error(payload?.data?.message || labels.error);
        }

        Object.assign(estimate, payload.data);
      } catch (err) {
        error.value = err?.message || labels.error;
      } finally {
        loading.value = false;
      }
    };

    return {
      labels,
      estimate,
      loading,
      error,
      formattedEstimatedAt,
      runEstimate,
    };
  },
};
</script>
