<template>
  <div class="space-y-4">
    <h3 class="text-xl font-semibold">{{ i18n.weekly_grid_title }}</h3>

    <div class="overflow-auto">
      <div class="grid" :style="gridTemplate">
        <!-- top-left corner -->
        <div class="p-2"></div>

        <!-- day headers -->
        <div
            v-for="(day, di) in days"
            :key="di"
            class="bookaro-weekly-grid__head"
        >
          {{ (i18n.days && i18n.days[day]) || day }}
        </div>

        <!-- time labels + cells -->
        <template v-for="(label, ri) in timeLabels">
          <!-- time label -->
          <div :key="'time-'+ri" class="bookaro-weekly-grid__time">
            {{ label }}
          </div>
          <!-- cell per day -->
          <div
              v-for="(day, di) in days"
              :key="`cell-${di}-${ri}`"
              class="bookaro-weekly-grid__cell"
              :class="{
              'is-active': grid[di][ri],
              'is-inactive': !grid[di][ri]
            }"
              @mousedown.prevent="startDraw(di, ri)"
              @mouseover.prevent="draw(di, ri)"
              @mouseup.prevent="stopDraw()"
          ></div>
        </template>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'WeeklyGrid',
  props: {
    i18n:         { type: Object, required: true },
    availability: { type: Object, required: true }
  },
  data() {
    return {
      drawing: false,
      drawValue: true,
      grid: []
    };
  },
  computed: {
    days() {
      return this.availability.weekdays
    },
    interval() {
      return this.availability.interval || 60;
    },
    rowCount() {
      return Math.floor(24 * 60 / this.interval);
    },
    timeLabels() {
      const labels = [];
      for (let i = 0; i < this.rowCount; i++) {
        const mins = i * this.interval;
        const h = Math.floor(mins / 60);
        const m = mins % 60;
        labels.push(
            `${h.toString().padStart(2,'0')}:${m.toString().padStart(2,'0')}`
        );
      }
      return labels;
    },
    gridTemplate() {
      return {
        display: 'grid',
        'grid-template-columns': `auto repeat(${this.days.length}, minmax(4rem,1fr))`,
        'grid-auto-rows': 'auto'
      };
    },

  },
  methods: {
    initGrid() {
      this.grid = this.days.map(day => {
        const arr = Array(this.rowCount).fill(false);
        (this.availability.times[day] || []).forEach(b => {
          const start = this.timeToIndex(b.from);
          const end   = this.timeToIndex(b.to);
          for (let i = start; i < end; i++) arr[i] = true;
        });
        return arr;
      });
    },
    timeToIndex(t) {
      const [h,m] = t.split(':').map(Number);
      return Math.floor((h * 60 + m) / this.interval);
    },
    indexToTime(i) {
      if (this.interval === 1440 && i === 1) {
        return '23:59';
      }
      const mins = i * this.interval;
      const h = Math.floor(mins/60), m = mins%60;
      return `${h.toString().padStart(2,'0')}:${m.toString().padStart(2,'0')}`;
    },
    startDraw(di, ri) {
      this.drawing = true;
      this.drawValue = !this.grid[di][ri];
      this.updateCell(di, ri);
    },
    draw(di, ri) {
      if (!this.drawing) return;
      this.updateCell(di, ri);
    },
    stopDraw() {
      if (!this.drawing) return;
      this.drawing = false;
      this.commitGrid();
    },
    updateCell(di, ri) {
      this.grid[di][ri] = this.drawValue;
    },
    commitGrid() {
      this.days.forEach((day, di) => {
        const runs = [];
        let inRun = false, start = 0;

        // build up runs from grid… (as you already have)
        this.grid[di].forEach((val, i) => {
          if (val && !inRun) { inRun = true; start = i; }
          if ((!val || i === this.rowCount - 1) && inRun) {
            const end = val ? i + 1 : i;
            runs.push({ from: this.indexToTime(start), to: this.indexToTime(end) });
            inRun = false;
          }
        });

        // 1) Sync the times map
        this.availability.times[day] = runs;

        // 2) Sync the weekdays array
        const hasRuns = runs.length > 0;
        const idx     = this.availability.weekdays.indexOf(day);

        if (hasRuns && idx === -1) {
          // a new day got slots — add it
          this.availability.weekdays.push(day);
        } else if (!hasRuns && idx !== -1) {
          // a day lost all slots — remove it
          this.availability.weekdays.splice(idx, 1);
        }
      });
    }

  },
  watch: {
    // re-build grid whenever the parent availability prop changes
    availability: {
      handler() {
        this.initGrid();
      },
      deep: true,
      immediate: true
    }
  },
  mounted() {
    // in case watch didn't fire, ensure grid is ready
    this.initGrid();
    document.addEventListener('mouseup', this.stopDraw);
  },
  beforeUnmount() {
    document.removeEventListener('mouseup', this.stopDraw);
  }
};
</script>

<style scoped>
.bookaro-booking-wrapper .cursor-pointer { user-select: none; }
.bookaro-weekly-grid__head {
  padding: 0.5rem;
  text-align: center;
  font-weight: 600;
  border: 1px solid var(--bookaro-dashboard-border);
  background: var(--bookaro-dashboard-surface);
}

.bookaro-weekly-grid__time {
  padding: 0.25rem 0.35rem;
  font-size: 0.7rem;
  text-align: right;
  color: var(--bookaro-dashboard-muted);
  border-right: 1px solid var(--bookaro-dashboard-border);
}

.bookaro-weekly-grid__cell {
  height: 1.5rem;
  border: 1px solid var(--bookaro-dashboard-border);
  cursor: pointer;
  user-select: none;
  transition: background-color 0.15s ease;
}

.bookaro-weekly-grid__cell.is-active {
  background: rgba(var(--bookaro-dashboard-accent-rgb), 0.35);
}

.bookaro-weekly-grid__cell.is-inactive {
  background: #f8fafc;
}
</style>

