<template>
  <div
    id="bookaro-owner-dashboard"
    class="vue-wrapper flex bookaro-scope bookaro-owner-dashboard bookaro-dashboard-shell"
    :class="{ 'bookaro-dashboard--compact': isCompact }"
  >
    <!-- Main Content -->
    <main class="flex-1 relative overflow-x-auto bookaro-dashboard-main">
      <!-- Mobile header -->
      <header class="bookaro-dashboard-header md:hidden">
        <h2 class="text-xl font-semibold text-gray-900">
          {{
            currentView === 'bookings'
              ? (i18n.bookings_tab)
              : currentView === 'calendar'
                ? (i18n.calendar_tab)
              : (i18n.settings_tab)
          }}
        </h2>
      </header>

      <DashboardNav
        :items="navItems"
        :active-key="currentView"
        @select="switchTo"
      />

      <section v-if="showSetupCards" class="bookaro-dashboard-page">
        <div class="bookaro-card bookaro-card__body bookaro-setup-panel">
          <div class="bookaro-setup-panel__header">
            <div>
              <h3 class="text-lg font-semibold text-gray-900">
                {{ i18n.setup_owner_title }}
              </h3>
              <p class="text-sm text-gray-600">
                {{ i18n.setup_owner_desc }}
              </p>
            </div>
            <div class="bookaro-setup-panel__actions">
              <div class="bookaro-setup-progress">
                <span class="bookaro-setup-progress__label">
                  {{ setupCompletedCount }}/{{ setupCards.length }} {{ i18n.setup_progress_label }}
                </span>
                <div class="bookaro-setup-progress__bar">
                  <span
                    class="bookaro-setup-progress__fill"
                    :style="{ width: setupProgressPercent + '%' }"
                  ></span>
                </div>
              </div>
              <button
                type="button"
                class="bookaro-btn bookaro-btn--ghost text-xs"
                @click="dismissSetup"
              >
                {{ i18n.dismiss }}
              </button>
            </div>
          </div>

          <div class="bookaro-setup-steps">
            <div
              v-for="(card, index) in setupCards"
              :key="card.id"
              :class="['bookaro-setup-step', card.complete ? 'is-complete' : '']"
            >
              <div class="bookaro-setup-step__header">
                <div
                  :class="['bookaro-setup-step__badge', card.complete ? 'is-complete' : '']"
                >
                  <span v-if="card.complete" aria-hidden="true">&#10003;</span>
                  <span v-else>{{ index + 1 }}</span>
                </div>
                <div class="flex-1">
                  <p class="text-sm font-semibold text-gray-900 bookaro-setup-step__title">{{ card.title }}</p>
                  <p class="text-xs text-gray-600 bookaro-setup-step__desc">{{ card.description }}</p>
                </div>
              </div>
              <div v-if="!card.complete" class="bookaro-setup-step__action">
                <button
                  v-if="card.tab"
                  type="button"
                  class="bookaro-btn bookaro-btn--primary text-xs"
                  @click="handleSetupAction(card)"
                >
                  {{ card.actionLabel }}
                </button>
                <a
                  v-else-if="card.url"
                  class="bookaro-btn bookaro-btn--primary text-xs"
                  :href="card.url"
                >
                  {{ card.actionLabel }}
                </a>
              </div>
            </div>
          </div>
        </div>
      </section>

      <!-- Error and Details Modals -->
      <ErrorModal
          :show="showErrorModal"
          :message="errorMessage"
          @close="showErrorModal = false"
      />
      <DetailsModal
          :show="showDetailsModal"
          :booking="detailsBooking"
          :loading="detailsLoading"
          @close="showDetailsModal = false"
          :i18n="i18n"
      />

      <!-- Tabbed Views -->
      <div v-if="currentView === 'bookings'" class="bookaro-dashboard-page">
        <OwnerBookingsView
            :i18n="i18n"
            @open-error="showError"
            @open-details="viewBooking"
            @nav-counts="handleNavCounts"
        />
      </div>

      <div v-else-if="currentView === 'calendar'" class="bookaro-dashboard-page">
        <OwnerCalendarView
            :i18n="i18n"
            @open-error="showError"
            @open-details="viewBooking"
            @nav-counts="handleNavCounts"
        />
      </div>

      <div v-else-if="currentView === 'settings'" class="bookaro-dashboard-page">
        <OwnerSettingsView :i18n="i18n" />
      </div>
    </main>
  </div>
</template>

<script>
import OwnerBookingsView  from './pages/OwnerBookingsView.vue';
import OwnerCalendarView  from './pages/OwnerCalendarView.vue';
import OwnerSettingsView  from '@bookaro-owner-settings';
import DashboardNav      from './components/dashboard/DashboardNav.vue';
import ErrorModal        from '@bookaro-free/components/modals/ErrorModal.vue';
import DetailsModal      from '@bookaro-free/components/modals/DetailsModal.vue';

export default {
  name: 'OwnerDashboard',
  components: {
    OwnerBookingsView,
    OwnerCalendarView,
    OwnerSettingsView,
    DashboardNav,
    ErrorModal,
    DetailsModal
  },
  data() {
    return {
      currentView: 'bookings',
      navCounts: {
        bookings: { pending: 0 }
      },
      showErrorModal: false,
      errorMessage: '',
      showDetailsModal: false,
      detailsBooking: null,
      detailsLoading: false,
      setupDismissed: false
    };
  },
  computed: {
    i18n() {
      return window.BookaroData?.i18n || {};
    },
    isCompact() {
      return (window.BookaroData?.dashboard_density || '') === 'compact';
    },
    setupData() {
      return window.BookaroData?.setup || null;
    },
    setupBrowseUrl() {
      return this.setupData?.browse_url || '';
    },
    setupCards() {
      const setupNoticeEnabled = window.BookaroData?.setup_notice_enabled;
      if (setupNoticeEnabled === false) {
        return [];
      }
      const injectedSteps = window.BookaroData?.setup_steps;
      if (Array.isArray(injectedSteps)) {
        return injectedSteps.map(step => this.normalizeSetupStep(step));
      }
      const setup = this.setupData;
      if (!setup) {
        return [];
      }
      return [
        {
          id: 'first_booking',
          title: this.i18n.setup_owner_title,
          description: this.i18n.setup_owner_desc,
          complete: !!setup.has_bookings,
          actionLabel: this.i18n.setup_action_browse,
          url: this.setupBrowseUrl
        }
      ].map(card => this.normalizeSetupStep(card));
    },
    setupCompletedCount() {
      return this.setupCards.filter(card => card.complete).length;
    },
    setupProgressPercent() {
      if (!this.setupCards.length) {
        return 0;
      }
      return Math.round((this.setupCompletedCount / this.setupCards.length) * 100);
    },
    setupHasIncomplete() {
      return this.setupCards.some(card => !card.complete);
    },
    showSetupCards() {
      return this.setupHasIncomplete && !this.setupDismissed;
    },
    navItems() {
      return [
        {
          key: 'bookings',
          label: this.i18n.bookings_tab,
          icon: 'bookings',
          count: this.navCounts?.bookings?.pending || 0,
          countLabel: this.i18n.pending
        },
        {
          key: 'calendar',
          label: this.i18n.calendar_tab,
          icon: 'calendar'
        },
        {
          key: 'settings',
          label: this.i18n.settings_tab,
          icon: 'settings'
        }
      ];
    },
  },
  methods: {
    switchTo(tab) {
      this.currentView = tab;
      window.location.hash = `#${tab}`;
    },
    updateFromHash() {
      const hash = window.location.hash.replace('#', '');
      if (['bookings', 'calendar', 'settings'].includes(hash)) {
        this.currentView = hash;
      }
    },
    showError(msg) {
      this.errorMessage = msg;
      this.showErrorModal = true;
    },
    viewBooking(booking) {
      this.detailsBooking = booking;
      this.showDetailsModal = true;
    },
    handleNavCounts(payload) {
      if (!payload || typeof payload !== 'object') {
        return;
      }
      const next = { ...this.navCounts };
      if (payload.bookings) {
        next.bookings = { ...(next.bookings || {}), ...(payload.bookings || {}) };
      }
      this.navCounts = next;
    },
    setupStorageKey() {
      const userId = window.BookaroData?.user_id || 0;
      return `bookaro_setup_owner_dismissed_${userId}`;
    },
    loadSetupDismissed() {
      const key = this.setupStorageKey();
      if (!key) {
        return;
      }
      try {
        this.setupDismissed = window.localStorage && window.localStorage.getItem(key) === '1';
      } catch (e) {
        this.setupDismissed = false;
      }
    },
    dismissSetup() {
      const key = this.setupStorageKey();
      this.setupDismissed = true;
      if (!key) {
        return;
      }
      try {
        window.localStorage.setItem(key, '1');
      } catch (e) {
        // Ignore storage errors.
      }
    },
    normalizeSetupStep(step) {
      if (!step || typeof step !== 'object') {
        return step;
      }
      const normalized = { ...step };
      if (!normalized.tab && typeof normalized.url === 'string') {
        const mapped = this.resolveSetupTabFromUrl(normalized.url);
        if (mapped) {
          normalized.tab = mapped.tab;
          if (mapped.settingsTab) {
            normalized.settingsTab = mapped.settingsTab;
          }
        }
      }
      return normalized;
    },
    resolveSetupTabFromUrl(url) {
      if (!url || typeof url !== 'string') {
        return null;
      }
      try {
        const parsed = new URL(url, window.location.origin);
        const tab = parsed.searchParams.get('tab');
        if (!tab) {
          return null;
        }
        return { tab: 'settings', settingsTab: tab };
      } catch (e) {
        return null;
      }
    },
    handleSetupAction(card) {
      if (!card || typeof card !== 'object') {
        return;
      }
      if (card.tab) {
        if (card.tab === 'settings' && card.settingsTab) {
          this.setSettingsTabParam(card.settingsTab);
        }
        this.switchTo(card.tab);
        return;
      }
      if (card.url) {
        window.location.href = card.url;
      }
    },
    setSettingsTabParam(tab) {
      try {
        const url = new URL(window.location.href);
        url.searchParams.set('tab', tab);
        window.history.replaceState(null, '', url.pathname + url.search);
      } catch (e) {
        // Ignore URL update errors.
      }
    }
  },
  mounted() {
    this.updateFromHash();
    this.loadSetupDismissed();
    window.addEventListener('hashchange', this.updateFromHash);
  },
  beforeUnmount() {
    window.removeEventListener('hashchange', this.updateFromHash);
  }
};
</script>

<style scoped>
.cst-book-min-cont-hei {
  min-height: 50vh;
}

.bk-cnt {
  background: #ffffff;
  border-top-right-radius: 10px;
  border-bottom-right-radius: 10px;
}

.bk-sidebar {
  background: #ffffff;
  border-top-left-radius: 10px;
  border-bottom-left-radius: 10px;
  z-index:9991;
  height:100%;
}

@media (max-width:768px) {
  .bk-tab-cnt {
    display: none;
  }
}

.bk-tab-cnt a:focus,
.bk-tab-cnt a.text-blue-600{
  background: var(--bookaro-dashboard-accent);
  color: #fff;
}

.bk-tab-cnt a {
  padding-top: 10px;
}

.bk-nv-tb:hover {
  font-weight: bold;
}
.bk-nv-tb {
  flex: 1;
  font-size: 13px;
  text-align: center;
  font-weight: bold;
  border-top-left-radius: 5px;
  border-top-right-radius: 5px;
}

aside > ul > li a {
  padding: 0 20px;
  color: #242429;
  font-weight: 600;
  line-height: 18px;
}
</style>

