<template>
  <div class="cst-book-min-cont-hei">
    <div v-if="loading" class="bookaro-loading-shell">
      <div class="bookaro-skeleton-card">
        <div class="bookaro-skeleton bookaro-skeleton-line is-wide"></div>
        <div class="bookaro-skeleton bookaro-skeleton-line is-medium"></div>
        <div class="bookaro-skeleton bookaro-skeleton-line is-short"></div>
      </div>
      <div class="bookaro-skeleton-card">
        <div class="bookaro-skeleton bookaro-skeleton-line is-wide"></div>
        <div class="bookaro-skeleton bookaro-skeleton-line"></div>
        <div class="bookaro-skeleton bookaro-skeleton-line"></div>
        <div class="bookaro-skeleton bookaro-skeleton-line is-medium"></div>
      </div>
    </div>

    <template v-else>
      <!-- Tab buttons -->
      <div class="bookaro-dashboard-subnav mb-6">
        <a
            v-for="tab in tabs"
            :key="tab.key"
            :href="`?tab=${tab.key}#settings`"
            @click.prevent="setTab(tab.key)"
            :class="[
            'bookaro-dashboard-subnav__item',
            currentTab === tab.key ? 'is-active' : ''
          ]"
        >
          <span class="bookaro-dashboard-subnav__icon" aria-hidden="true">
            <svg
              v-if="tab.icon === 'availability'"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="1.8"
              stroke-linecap="round"
              stroke-linejoin="round"
            >
              <circle cx="12" cy="12" r="9" />
              <path d="M12 7v5l3 3" />
            </svg>
            <svg
              v-else-if="tab.icon === 'exceptions'"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="1.8"
              stroke-linecap="round"
              stroke-linejoin="round"
            >
              <circle cx="12" cy="12" r="9" />
              <line x1="7" y1="17" x2="17" y2="7" />
            </svg>
            <svg
              v-else-if="tab.icon === 'delete_data'"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="1.8"
              stroke-linecap="round"
              stroke-linejoin="round"
            >
              <polyline points="3 6 5 6 21 6" />
              <path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6" />
              <path d="M10 11v6M14 11v6" />
              <path d="M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2" />
            </svg>
          </span>
          <span class="bookaro-dashboard-subnav__label">{{ tab.label }}</span>
        </a>
      </div>

      <!-- Tab content -->
      <div class="mt-4 bookaro-card">
        <div class="bookaro-card__body">
          <!-- Only render once “availability” is available (truthy) -->
          <component
              v-if="availability"
              :is="currentTabComponent"
              :key="currentTab"
              :i18n="i18n"
              :availability="availability"
              v-bind="tabExtraProps"
              :exception-dates="exceptionDates"
              :exception-month="exceptionMonth"
              :exception-month-days="exceptionMonthDays"
              @update:availability="$emit('update:availability', $event)"
              @update:exceptionDates="$emit('update:exceptionDates', $event)"
              @update:exceptionMonth="$emit('update:exceptionMonth', $event)"
          />

          <div v-else class="text-gray-500">
            {{ i18n.loading_settings }}
          </div>
        </div>
      </div>

      <!-- Save button / feedback -->
      <div class="bookaro-settings-actions mt-6">
        <button
            @click="$emit('save-settings')"
            :disabled="savingSettings"
            class="bookaro-btn bookaro-btn--primary"
        >
          <svg
              v-if="savingSettings"
              class="animate-spin h-5 w-5 mr-3"
              viewBox="0 0 24 24"
          >
            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4" />
            <path
                class="opacity-75"
                fill="currentColor"
                d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z"
            />
          </svg>
          {{ savingSettings ? i18n.saving_label : i18n.save_settings }}
        </button>
        <p v-if="settingsMessage" class="text-green-600">
          {{ settingsMessage }}
        </p>
      </div>
    </template>
  </div>
</template>

<script>
import AvailabilityTab    from '@bookaro-free/components/providerDashboard/settings/AvailabilityTab.vue';
import ExceptionsTab      from '@bookaro-free/components/providerDashboard/settings/ExceptionsTab.vue';
import DeleteDataTab from '@bookaro-free/components/DeleteDataTab.vue';

export default {
  name: 'SettingsLayout',
  components: {
    AvailabilityTab,
    ExceptionsTab,
    DeleteDataTab
  },
  props: {
    i18n:               { type: Object, required: true },
    loading:            { type: Boolean, default: false },
    availability:       { type: Object, default: null },
    scheduleMeta:       { type: Object, default: () => ({}) },
    exceptionDates:     { type: Array,  default: () => [] },
    exceptionMonth:     { type: Object, default: null },
    exceptionMonthDays: { type: Array,  default: () => [] },
    savingSettings:     { type: Boolean, default: false },
    settingsMessage:    { type: String, default: '' },
    // Bug 61: array of {id, service_label, status, booking_date,
    // booking_date_to, closed_dates[]} populated from the save response
    // when the provider closes a day that still has approved/pending
    // bookings on it. Forwarded into ExceptionsTab.
    exceptionConflicts: { type: Array, default: () => [] }
  },
  data() {
    return {
      currentTab: 'availability'
    };
  },
  computed: {
    // Bug 61: combine per-tab extra props in one v-bind to avoid the
    // "Duplicate attribute" compile error that fires when you put two
    // v-bind="..." expressions on the same element.
    tabExtraProps() {
      if (this.currentTab === 'availability') {
        return { scheduleMeta: this.scheduleMeta };
      }
      if (this.currentTab === 'exceptions') {
        return { exceptionConflicts: this.exceptionConflicts };
      }
      return {};
    },
    tabs() {
      const tabs = [
        { key: 'availability',    label: this.i18n.availability_tab, icon: 'availability' },
        { key: 'exceptions',      label: this.i18n.exceptions_tab, icon: 'exceptions' }
      ];
      tabs.push({ key: 'delete_data', label: this.i18n.delete_data_tab, icon: 'delete_data' });
      return tabs;
    },
    currentTabComponent() {
      return {
        availability:    'AvailabilityTab',
        exceptions:      'ExceptionsTab',
        delete_data:     'DeleteDataTab'
      }[ this.currentTab ];
    }
  },
  methods: {
    setTab(key) {
      this.currentTab = key;
      const url = new URL(window.location.href);
      url.searchParams.set('tab', key);
      window.history.replaceState(null, '', url.pathname + url.search + '#settings');

      if (key === 'exceptions') {
        this.markExceptionsViewed();
      }
    },

    markExceptionsViewed() {
      if (window.BookaroData.exceptions_viewed) return;
      fetch(window.BookaroData.ajax_url, {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
        body: new URLSearchParams({
          action: 'bookaro_viewed_exceptions',
          security: window.BookaroData.ajax_nonce
        })
      }).then(() => {
        window.BookaroData.exceptions_viewed = true;
      });
    }
  },
  mounted() {
    const params = new URLSearchParams(window.location.search);
    const tab = params.get('tab');
    if (tab && this.tabs.find(t => t.key === tab)) {
      this.setTab(tab);
    }
  }
};
</script>

<style scoped>
</style>

