// Vue Clocking Component - Fixed Template Errors - Cache Bust v2.0
const template = html`
  <div class="clocking-component">
    <div v-if="!loading">
      <!-- Status Display -->
      <div style="margin-bottom: 15px; text-align: center;">
        <small>
          <span v-if="!isClockedIn && !islunch" style="color: white;">
            <i class="fa fa-circle" style="color: #8b4444;"></i> Clocked Out
          </span>
          <span v-if="islunch" style="color: white;">
            <i class="fa fa-circle" style="color: rgb(184, 134, 11);"></i> On Lunch
          </span>
          <span v-if="isClockedIn && !islunch" style="color: white;">
            <i class="fa fa-circle" style="color: #2c7d7d;"></i> Clocked In
          </span>
        </small>
      </div>

      <!-- Notification Messages - Fixed to prevent content blocking -->
      <messenger
        v-if="islunch && showNotification"
        title="You are on lunch."
        type="warning"
        :actions='[{ text: "Clock In from Lunch", click: this.clockInlunch }]'
        style=""
        @close="dismissNotification"
      ></messenger>
      <messenger
        v-if="!isClockedIn && !islunch && showNotification"
        title="You are clocked out"
        type="error"
        :actions='[{ text: "Clock In", click: this.clockIn }]'
        style=""
        @close="dismissNotification"
      ></messenger>
      <messenger
        v-if="isClockedIn && !islunch && showNotification"
        title="You are clocked in"
        type="success"
        :actions='[{ text: "Clock Out", click: this.clockOut }]'
        style=""
        @close="dismissNotification"
      ></messenger>

      <!-- Action Buttons -->
      <div style="display: flex; gap: 4px; justify-content: center; flex-wrap: wrap; margin-top: 15px; margin-bottom: 15px;">
        <!-- Clock In Button (when clocked out) -->
        <button 
          v-if="!isClockedIn && !islunch"
          @click="clockIn()"
          class="btn"
          style="background: #2c7d7d; border: #2c7d7d; padding: 10px 20px; border-radius: 4px; color: white; font-size: 14px; display: flex; align-items: center; gap: 8px; width: 160px; justify-content: center; margin-bottom: 4px; transition: all 0.3s ease;"
          onmouseover="this.style.background='#245e5e'"
          onmouseout="this.style.background='#2c7d7d'"
        >
          <i class="fa fa-play"></i>
          Clock In
        </button>

        <!-- Clock In from Lunch Button (when at lunch) -->
        <button 
          v-if="islunch"
          @click="clockInlunch()"
          class="btn"
          style="background: #2c7d7d; border: #2c7d7d; padding: 10px 20px; border-radius: 4px; color: white; font-size: 14px; display: flex; align-items: center; gap: 8px; width: 160px; justify-content: center; margin-bottom: 4px; transition: all 0.3s ease;"
          onmouseover="this.style.background='#245e5e'"
          onmouseout="this.style.background='#2c7d7d'"
        >
          <i class="fa fa-play"></i>
          Back from Lunch
        </button>

        <!-- Clock Out Button (when clocked in and not at lunch) -->
        <button
          v-if="isClockedIn && !islunch"
          @click="clockOut()"
          class="btn"
          style="background: #8b4444; border: #8b4444; padding: 10px 20px; border-radius: 4px; color: white; font-size: 14px; display: flex; align-items: center; gap: 8px; width: 160px; justify-content: center; margin-bottom: 4px; transition: all 0.3s ease;"
          onmouseover="this.style.background='#6d3333'"
          onmouseout="this.style.background='#8b4444'"
        >
          <i class="fa fa-stop"></i>
          Clock Out
        </button>

        <!-- Clock Out for Lunch Button (when clocked in) -->
        <button 
          v-if="isClockedIn && !islunch && !hasHadLunchToday"
          @click="clockOutLunch()"
          class="btn"
          style="background: #b8860b; border: #b8860b; padding: 10px 20px; border-radius: 4px; color: white; font-size: 14px; display: flex; align-items: center; gap: 8px; width: 160px; justify-content: center; margin-bottom: 4px; transition: all 0.3s ease;"
          onmouseover="this.style.background='#9a7009'"
          onmouseout="this.style.background='#b8860b'"
        >
          <i class="fa fa-cutlery"></i>
          Go to Lunch
        </button>

        <!-- Lunch Done Button (when user has already had lunch today) -->
        <button 
          v-if="isClockedIn && !islunch && hasHadLunchToday"
          class="btn"
          style="background: #888; border: #888; padding: 10px 20px; border-radius: 4px; color: white; font-size: 14px; display: flex; align-items: center; gap: 8px; width: 160px; justify-content: center; margin-bottom: 4px; cursor: not-allowed; opacity: 0.7;"
          disabled
        >
          <i class="fa fa-check"></i>
          Lunch Done
        </button>
      </div>
    </div>

    <!-- Loading State -->
    <div v-else style="text-align: center; padding: 20px;">
      <i class="fa fa-spinner fa-spin"></i>
      <small style="margin-left: 8px;">Loading...</small>
    </div>
  </div>
`;

import messenger from "./messenger.js";
import csrfMixin from "../mixins/csrf-mixin.js";

export default {
  mixins: [csrfMixin],
  data: function () {
    return {
      isClockedIn: false,
      islunch: false,
      loading: true,
      showNotification: true,
      hasHadLunchToday: false
    };
  },
  mounted() {
    this.load();
  },
  methods: {
    async load() {
      const response = await fetch("/api/v1/hr/time-log/?lastRecord=true", {

      });

      const json = await response.json();

      if (!json) {
        return;
      }

      this.isClockedIn = json.type == "in";
      this.islunch = json.lunch == 1;

      // Check if user has had lunch today
      await this.checkLunchStatus();

      this.loading = false;

      // Check if notification was dismissed recently
      const dismissedUntil = this.getNotificationDismissalTime();
      const now = Date.now();

      // Show notification when clocked out or at lunch, hide when clocked in or dismissed recently
      this.showNotification = (!this.isClockedIn || this.islunch) && (now > dismissedUntil);
    },
    getNotificationDismissalTime() {
      try {
        const dismissedUntil = localStorage.getItem('clockingNotificationDismissedUntil');
        return dismissedUntil ? parseInt(dismissedUntil, 10) : 0;
      } catch (error) {
        console.log('[Vue Clocking] Error reading dismissal time from localStorage:', error);
        return 0;
      }
    },
    dismissNotification() {
      // Hide notification for 1 hour (3600000 milliseconds)
      const dismissedUntil = Date.now() + 3600000;
      try {
        localStorage.setItem('clockingNotificationDismissedUntil', dismissedUntil.toString());
        console.log('[Vue Clocking] Notification dismissed until:', new Date(dismissedUntil).toLocaleString());
      } catch (error) {
        console.log('[Vue Clocking] Error saving dismissal time to localStorage:', error);
      }
      this.showNotification = false;
    },
    async checkLunchStatus() {
      try {
        // Don't check if user is currently at lunch - they haven't "finished" lunch yet
        if (this.islunch) {
          console.log('[Vue Clocking] User is currently at lunch - not checking lunch completion status');
          this.hasHadLunchToday = false;
          return;
        }

        console.log('[Vue Clocking] Checking if user has completed lunch today...');

        // Use dedicated lunch status endpoint (same logic as server-side validation)
        const response = await fetch('/api/v1/hr/lunch-status', {
          headers: { "Accept": "application/json" }
        });

        if (response.ok) {
          const data = await response.json();
          this.hasHadLunchToday = data.hasHadLunchToday;
          console.log('[Vue Clocking] Has had lunch today:', data.hasHadLunchToday);
        } else {
          console.log('[Vue Clocking] Failed to fetch lunch status:', response.status);
          this.hasHadLunchToday = false;
        }

      } catch (error) {
        console.log('[Vue Clocking] Could not check lunch status:', error);
        this.hasHadLunchToday = false;
      }
    },
    async clockOut() {
      const response = await this.post("out");
      if (!response.ok) {
        return;
      }
      this.isClockedIn = false;
      this.islunch = false;
      // Clear any dismissal and show notification when clocking out
      this.clearNotificationDismissal();
      this.showNotification = true;
    },
    async clockOutLunch() {
      const response = await this.post("out", true);
      if (!response.ok) {
        return;
      }
      this.isClockedIn = true; // Still clocked in, just at lunch
      this.islunch = true;
      this.hasHadLunchToday = true; // Mark that user has had lunch today
      // Clear any dismissal and show notification when going to lunch
      this.clearNotificationDismissal();
      this.showNotification = true;
    },
    async clockIn() {
      const response = await this.post("in");
      if (!response.ok) {
        return;
      }
      this.isClockedIn = true;
      this.islunch = false;
      // Clear any dismissal and hide notification when clocking in
      this.clearNotificationDismissal();
      this.showNotification = false;
    },
    async clockInlunch() {
      const response = await this.post("in", true);
      if (!response.ok) {
        return;
      }
      this.isClockedIn = true;
      this.islunch = false;
      // Clear any dismissal and hide notification when coming back from lunch
      this.clearNotificationDismissal();
      this.showNotification = false;

      // Update lunch status after coming back from lunch
      await this.checkLunchStatus();
    },
    clearNotificationDismissal() {
      try {
        localStorage.removeItem('clockingNotificationDismissedUntil');
        console.log('[Vue Clocking] Notification dismissal cleared');
      } catch (error) {
        console.log('[Vue Clocking] Error clearing dismissal time from localStorage:', error);
      }
    },
    async post(type, lunch) {
      console.log('[Vue Clocking] Request data:', { type: type, lunch });

      // Use the global CSRF manager for automatic token handling and retry logic
      const response = await this.$csrf.post("/api/v1/hr/time-log", { type: type, lunch });

      console.log('[Vue Clocking] Response status:', response.status);
      console.log('[Vue Clocking] Response ok:', response.ok);

      return response;
    }
  },
  components: {
    messenger
  },

  template
};
