<template>
  <div class="space-y-6">
    <div>
      <h3 class="text-xl font-semibold">{{ i18n.availability_title }}</h3>
      <p class="text-sm text-gray-600 mb-4">{{ i18n.availability_description }}</p>
    </div>

    <div
      v-if="showStarterNotice"
      class="rounded-lg border border-sky-200 bg-sky-50 p-3"
    >
      <h4 class="text-sm font-semibold text-sky-900">
        {{ i18n.availability_starter_title || i18n.availability_title }}
      </h4>
      <p class="mt-1 text-sm text-sky-800">
        {{ i18n.availability_starter_description || i18n.availability_description }}
      </p>
    </div>

    <div
      v-if="!hasConfiguredAvailability"
      class="rounded-lg border border-amber-200 bg-amber-50 p-3"
    >
      <h4 class="text-sm font-semibold text-amber-900">
        {{ i18n.empty_no_availability_title || i18n.setup_step_timeslots_title || i18n.availability_title }}
      </h4>
      <p class="mt-1 text-sm text-amber-800">
        {{ i18n.empty_no_availability_desc || i18n.setup_step_timeslots_desc || i18n.availability_description }}
      </p>
      <div class="mt-2 flex flex-wrap gap-2">
        <button
          type="button"
          @click="applyTemplate('weekdays')"
          class="bookaro-btn bookaro-btn--outline bookaro-btn--sm"
        >
          {{ i18n.empty_action_apply_template || i18n.availability_template_weekdays }}
        </button>
        <button
          type="button"
          @click="applyTemplate('everyday')"
          class="bookaro-btn bookaro-btn--outline bookaro-btn--sm"
        >
          {{ i18n.availability_template_everyday }}
        </button>
      </div>
    </div>

    <div
      v-if="showGuidancePanel"
      class="rounded-lg border border-emerald-200 bg-emerald-50 p-3"
    >
      <h4 class="text-sm font-semibold text-emerald-900">
        {{ guidanceTitle }}
      </h4>
      <p class="mt-1 text-sm text-emerald-800">
        {{ guidanceDescription }}
      </p>
      <ul class="bookaro-guidance-list mt-2">
        <li
          v-for="(item, index) in guidanceItems"
          :key="`availability-guidance-${index}`"
          class="text-sm text-emerald-900"
        >
          {{ item }}
        </li>
      </ul>
    </div>

    <div class="bookaro-settings-grid">
      <div class="bookaro-settings-section">
        <div class="bookaro-settings-section__title">{{ i18n.availability_quick_actions }}</div>
        <div class="bookaro-settings-section__desc">{{ i18n.availability_quick_actions_desc }}</div>
        <div class="flex flex-wrap gap-2">
          <button
            type="button"
            @click="applyTemplate('weekdays')"
            class="bookaro-btn bookaro-btn--outline bookaro-btn--sm"
          >
            {{ i18n.availability_template_weekdays }}
          </button>
          <button
            type="button"
            @click="applyTemplate('everyday')"
            class="bookaro-btn bookaro-btn--outline bookaro-btn--sm"
          >
            {{ i18n.availability_template_everyday }}
          </button>
          <button
            type="button"
            @click="clearSchedule"
            class="bookaro-btn bookaro-btn--ghost bookaro-btn--sm"
          >
            {{ i18n.availability_clear_schedule }}
          </button>
        </div>

        <div class="mt-4">
          <label class="block text-sm font-medium mb-2">{{ i18n.interval_label }}</label>
          <p class="bookaro-settings-help">{{ i18n.interval_help }}</p>
          <div class="inline-flex flex-wrap gap-2">
            <button
              v-for="interval in intervals"
              :key="interval"
              type="button"
              @click="setInterval(interval)"
              :class="localAvailability.interval === interval ? 'bookaro-btn bookaro-btn--primary bookaro-btn--sm' : 'bookaro-btn bookaro-btn--outline bookaro-btn--sm'"
            >
              {{ interval === 1440 ? i18n.day_label : interval + i18n.minute_short }}
            </button>
          </div>
        </div>

        <div class="mt-4">
          <label class="block text-sm font-medium mb-2">{{ i18n.slots_per_interval_label }}</label>
          <p class="bookaro-settings-help">{{ i18n.slots_per_interval_help }}</p>
          <div class="flex flex-wrap items-center gap-3">
            <button
              type="button"
              @click="adjustSlots(-1)"
              class="bookaro-btn bookaro-btn--outline bookaro-btn--sm"
              :aria-label="i18n.decrease"
            >
              -
            </button>
            <input
              v-model.number="localAvailability.slots"
              type="number"
              min="1"
              step="1"
              class="bookaro-input w-24 text-center"
              @input="normalizeSlots"
              @change="normalizeSlots"
            />
            <button
              type="button"
              @click="adjustSlots(1)"
              class="bookaro-btn bookaro-btn--outline bookaro-btn--sm"
              :aria-label="i18n.increase"
            >
              +
            </button>
          </div>
          <p class="bookaro-settings-help mt-2">{{ bufferSummaryText }}</p>
          <p
            v-if="showOverlapWarning"
            class="bookaro-settings-help text-amber-700 mt-1"
          >
            {{ i18n.slots_per_interval_overlap_warning || 'Overlapping bookings are enabled for each start time. Keep this only if your team can fulfill concurrent bookings.' }}
          </p>
        </div>
      </div>

      <div class="bookaro-settings-section">
        <div class="bookaro-settings-section__title">{{ i18n.weekday_label }}</div>
        <div class="bookaro-settings-section__desc">{{ i18n.weekday_help }}</div>
        <div class="grid grid-cols-7 gap-4">
          <label
            v-for="day in weekdayOrder"
            :key="day"
            class="flex flex-col items-center"
          >
            <div class="relative">
              <input
                type="checkbox"
                :checked="isWeekdayEnabled(day)"
                @change="toggleWeekday(day, $event.target.checked)"
                class="sr-only"
              />
              <div
                class="w-12 h-6 bg-gray-300 rounded-full transition"
                :class="{ 'settings_color_accent': isWeekdayEnabled(day) }"
              ></div>
              <div
                class="dot absolute top-1/2 transform -translate-y-1/2 left-1 w-4 h-4 bg-white rounded-full shadow transition"
                :class="{ 'translate-x-6': isWeekdayEnabled(day) }"
              ></div>
            </div>
            <span class="mt-2 text-sm">{{ i18n.days?.[day] }}</span>
          </label>
        </div>
      </div>
    </div>

    <div class="bookaro-settings-section">
      <div class="bookaro-settings-section__title">
        {{ i18n.time_blocks_label }}
      </div>
      <div class="bookaro-settings-section__desc">
        {{ isDayInterval ? i18n.day_interval_message : i18n.time_blocks_help }}
      </div>

      <div v-if="isDayInterval" class="text-sm text-gray-600">
        {{ i18n.day_interval_followup || i18n.day_interval_message }}
      </div>

      <div v-else class="grid grid-cols-1 md:grid-cols-2 gap-6">
        <div
          v-for="day in displayWeekdays"
          :key="day"
          class="bookaro-card bookaro-card__body flex flex-col"
        >
          <h4 class="font-semibold text-base mb-2">
            {{ i18n.days?.[day] }}
          </h4>
          <p class="text-xs text-gray-500 mb-4">
            {{ i18n.time_blocks_day_help }}
          </p>

          <div class="bookaro-time-blocks">
            <div v-if="!(localAvailability.times?.[day] || []).length" class="bookaro-time-blocks__empty">
              {{ i18n.time_blocks_empty_day }}
            </div>

            <div class="bookaro-time-blocks__list">
              <div
                v-for="(block, idx) in localAvailability.times[day]"
                :key="idx"
                class="bookaro-time-pill"
                :class="{ 'is-active': isEditing(day, idx) }"
                @click="startEdit(day, idx)"
              >
                <span>{{ block.from }} - {{ block.to }}</span>
                <button
                  class="bookaro-time-pill__remove"
                  :aria-label="i18n.remove_block"
                  @click.stop="removeBlock(day, idx)"
                >
                  &times;
                </button>
              </div>
            </div>

            <div
              v-if="editing.day === day"
              class="bookaro-time-editor"
            >
              <label class="sr-only">{{ i18n.from_label }}</label>
              <input
                ref="timeFromInput"
                v-model="editing.from"
                type="time"
                :step="timeStepSeconds"
                class="bookaro-input"
                :placeholder="i18n.from_label"
              />
              <span class="text-gray-500">-</span>
              <label class="sr-only">{{ i18n.to_label }}</label>
              <input
                v-model="editing.to"
                type="time"
                :step="timeStepSeconds"
                class="bookaro-input"
                :placeholder="i18n.to_label"
              />
              <div class="bookaro-time-editor__actions">
                <button
                  type="button"
                  class="bookaro-btn bookaro-btn--primary bookaro-btn--sm"
                  @click="saveEdit"
                >
                  {{ i18n.save }}
                </button>
                <button
                  type="button"
                  class="bookaro-btn bookaro-btn--outline bookaro-btn--sm"
                  @click="cancelEdit"
                >
                  {{ i18n.cancel }}
                </button>
                <button
                  v-if="!editing.isNew"
                  type="button"
                  class="bookaro-btn bookaro-btn--ghost bookaro-btn--sm text-red-600"
                  @click="removeBlock(day, editing.idx)"
                >
                  {{ i18n.delete }}
                </button>
              </div>
              <p v-if="editError" class="bookaro-time-editor__error">
                {{ editError }}
              </p>
            </div>
          </div>

          <button
            type="button"
            @click="startAdd(day)"
            class="bookaro-btn bookaro-btn--ghost bookaro-btn--sm text-sm mt-auto"
          >
            + {{ i18n.add_time_block }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
// Module-level constant so cloneAvailability() (called from data() before
// Vue has wired up computed properties) can reference the weekday order
// without crashing with "Cannot read properties of undefined (reading
// 'includes')". Bug 13.
const WEEKDAY_ORDER = Object.freeze(['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']);

export default {
  name: 'AvailabilityTab',
  emits: ['update:availability'],
  props: {
    i18n: {
      type: Object,
      required: true
    },
    availability: {
      type: Object,
      required: true
    },
    scheduleMeta: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      localAvailability: this.cloneAvailability(this.availability),
      editing: {
        day: null,
        idx: null,
        from: '',
        to: '',
        isNew: false
      },
      editError: ''
    };
  },
  computed: {
    weekdayOrder() {
      return WEEKDAY_ORDER;
    },
    intervals() {
      return [15, 30, 45, 60, 1440];
    },
    isDayInterval() {
      return Number(this.localAvailability.interval) === 1440;
    },
    hasConfiguredAvailability() {
      const weekdays = Array.isArray(this.localAvailability.weekdays)
        ? this.localAvailability.weekdays
        : [];
      if (!weekdays.length) {
        return false;
      }
      if (this.isDayInterval) {
        return true;
      }
      return weekdays.some((day) => {
        const blocks = this.localAvailability?.times?.[day];
        return Array.isArray(blocks) && blocks.length > 0;
      });
    },
    displayWeekdays() {
      return this.weekdayOrder.filter((day) => this.localAvailability.weekdays.includes(day));
    },
    showStarterNotice() {
      return !!this.scheduleMeta?.using_default_template;
    },
    showGuidancePanel() {
      return this.showStarterNotice || !this.hasConfiguredAvailability;
    },
    guidanceTitle() {
      return this.scheduleMeta?.guidance?.title
        || this.i18n.availability_first_run_title
        || 'First-run checklist';
    },
    guidanceDescription() {
      return this.scheduleMeta?.guidance?.description
        || this.i18n.availability_first_run_desc
        || 'Use this checklist to avoid missing capacity, buffer, or timeslot setup details.';
    },
    guidanceItems() {
      const fromMeta = Array.isArray(this.scheduleMeta?.guidance?.items)
        ? this.scheduleMeta.guidance.items.filter((item) => typeof item === 'string' && item.trim() !== '')
        : [];
      if (fromMeta.length) {
        return fromMeta;
      }

      const slots = this.normalizeSlotValue(this.localAvailability?.slots);
      const items = [
        this.i18n.availability_guidance_step_review
          || 'Start with your real working days and first time blocks, then save once.',
        slots > 1
          ? (this.i18n.availability_guidance_step_capacity_overlap || `Capacity is ${slots} bookings per start time. Keep this only if you intentionally accept overlapping bookings.`)
          : (this.i18n.availability_guidance_step_capacity_single || 'Capacity is 1 booking per start time. Keep this default until you intentionally accept overlapping bookings.'),
        this.bufferSummaryText,
        this.i18n.availability_guidance_step_test
          || 'After saving, run one test booking and confirm slots match your expected availability.',
      ];

      return items.filter((item) => typeof item === 'string' && item.trim() !== '');
    },
    bufferSummaryText() {
      if (typeof this.scheduleMeta?.buffer_summary === 'string' && this.scheduleMeta.buffer_summary.trim() !== '') {
        return this.scheduleMeta.buffer_summary;
      }

      const before = Number(this.scheduleMeta?.buffer_before_minutes || 0);
      const after = Number(this.scheduleMeta?.buffer_after_minutes || 0);
      if (before > 0 || after > 0) {
        return this.i18n.availability_buffer_status_on
          || `Global booking buffers are active (${before} minutes before, ${after} minutes after).`;
      }

      return this.i18n.availability_buffer_status_off
        || 'Global booking buffers are currently off (0 minutes before / after).';
    },
    showOverlapWarning() {
      return this.normalizeSlotValue(this.localAvailability?.slots) > 1;
    },
    timeStepSeconds() {
      const minutes = Number(this.localAvailability.interval || 60);
      return Math.max(60, Math.min(minutes, 60) * 60);
    }
  },
  watch: {
    availability: {
      handler(val) {
        this.localAvailability = this.cloneAvailability(val);
        if (this.editing.day && !this.localAvailability.weekdays.includes(this.editing.day)) {
          this.cancelEdit();
        }
      },
      deep: true
    }
  },
  methods: {
    isEditing(day, idx) {
      return this.editing.day === day && this.editing.idx === idx;
    },
    isWeekdayEnabled(day) {
      return this.localAvailability.weekdays.includes(day);
    },
    emitAvailability() {
      this.$emit('update:availability', this.cloneAvailability(this.localAvailability));
    },
    applyTemplate(template = 'weekdays') {
      const weekdays = template === 'everyday'
        ? [...this.weekdayOrder]
        : ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'];
      const times = this.createEmptyTimes();
      weekdays.forEach((day) => {
        times[day] = [this.getStarterBlock(30)];
      });

      this.localAvailability = {
        weekdays,
        interval: 30,
        slots: this.normalizeSlotValue(this.localAvailability.slots),
        times
      };
      this.cancelEdit();
      this.emitAvailability();
    },
    clearSchedule() {
      this.localAvailability = {
        weekdays: [],
        interval: Number(this.localAvailability.interval || 30),
        slots: this.normalizeSlotValue(this.localAvailability.slots),
        times: this.createEmptyTimes()
      };
      this.cancelEdit();
      this.emitAvailability();
    },
    setInterval(interval) {
      const nextInterval = Number(interval || 30);
      if (this.localAvailability.interval === nextInterval) {
        return;
      }

      this.localAvailability.interval = nextInterval;
      if (nextInterval === 1440) {
        this.displayWeekdays.forEach((day) => {
          this.localAvailability.times[day] = [this.getStarterBlock(nextInterval)];
        });
        this.cancelEdit();
      }

      this.emitAvailability();
    },
    toggleWeekday(day, enabled) {
      const weekdays = new Set(this.localAvailability.weekdays || []);
      if (enabled) {
        weekdays.add(day);
        if (!(this.localAvailability.times?.[day] || []).length) {
          this.localAvailability.times[day] = [this.getStarterBlock(this.localAvailability.interval)];
        }
      } else {
        weekdays.delete(day);
        this.localAvailability.times[day] = [];
        if (this.editing.day === day) {
          this.cancelEdit();
        }
      }

      this.localAvailability.weekdays = this.sortWeekdays([...weekdays]);
      if (this.isDayInterval && enabled) {
        this.localAvailability.times[day] = [this.getStarterBlock(1440)];
      }
      this.emitAvailability();
    },
    adjustSlots(delta) {
      const current = this.normalizeSlotValue(this.localAvailability.slots);
      this.localAvailability.slots = Math.max(1, current + delta);
      this.emitAvailability();
    },
    normalizeSlots() {
      this.localAvailability.slots = this.normalizeSlotValue(this.localAvailability.slots);
      this.emitAvailability();
    },
    startEdit(day, idx) {
      const block = (this.localAvailability.times?.[day] || [])[idx];
      if (!block) {
        return;
      }
      this.editing = {
        day,
        idx,
        from: block.from,
        to: block.to,
        isNew: false
      };
      this.editError = '';
      this.$nextTick(() => {
        const ref = this.$refs.timeFromInput;
        if (Array.isArray(ref) && ref[0]?.focus) {
          ref[0].focus();
        } else if (ref?.focus) {
          ref.focus();
        }
      });
    },
    startAdd(day) {
      const blocks = this.localAvailability.times?.[day] || [];
      let block = this.getStarterBlock(this.localAvailability.interval);
      if (blocks.length) {
        const last = blocks[blocks.length - 1];
        if (last?.to) {
          const from = last.to;
          const minutes = this.timeToMinutes(from) + Number(this.localAvailability.interval || 60);
          block = {
            from,
            to: this.minutesToTime(minutes)
          };
        }
      }

      this.editing = {
        day,
        idx: null,
        from: block.from,
        to: block.to,
        isNew: true
      };
      this.editError = '';
      this.$nextTick(() => {
        const ref = this.$refs.timeFromInput;
        if (Array.isArray(ref) && ref[0]?.focus) {
          ref[0].focus();
        } else if (ref?.focus) {
          ref.focus();
        }
      });
    },
    saveEdit() {
      const { day, idx, from, to, isNew } = this.editing;
      if (!day) {
        return;
      }
      const fromMin = this.timeToMinutes(from);
      const toMin = this.timeToMinutes(to);
      if (!Number.isFinite(fromMin) || !Number.isFinite(toMin) || fromMin >= toMin) {
        this.editError = this.i18n.time_range_invalid;
        return;
      }

      // Audit #189: warn if the new/edited block overlaps an existing
      // block on the same weekday. The backend tolerates overlaps
      // (slots dedupe at read time) but a provider with [09:00-12:00]
      // and [11:00-13:00] sees duplicate 11:00 slots in the picker and
      // gets confusing capacity math. Catching the overlap here gives
      // immediate UX feedback instead of letting it slip through.
      const existing = Array.isArray(this.localAvailability.times[day])
          ? this.localAvailability.times[day]
          : [];
      for (let i = 0; i < existing.length; i += 1) {
        if (!isNew && i === idx) {
          continue; // editing this block — skip itself
        }
        const other = existing[i];
        const otherFrom = this.timeToMinutes(other.from);
        const otherTo = this.timeToMinutes(other.to);
        if (!Number.isFinite(otherFrom) || !Number.isFinite(otherTo)) {
          continue;
        }
        if (fromMin < otherTo && otherFrom < toMin) {
          this.editError = this.i18n.time_range_overlap
              || 'This block overlaps another block on the same day.';
          return;
        }
      }

      if (!this.localAvailability.times[day]) {
        this.localAvailability.times[day] = [];
      }

      if (isNew) {
        this.localAvailability.times[day].push({ from, to });
      } else if (idx !== null && this.localAvailability.times[day][idx]) {
        this.localAvailability.times[day][idx] = { from, to };
      }

      if (!this.localAvailability.weekdays.includes(day)) {
        this.localAvailability.weekdays = this.sortWeekdays([
          ...this.localAvailability.weekdays,
          day
        ]);
      }
      this.sortDayBlocks(day);
      this.emitAvailability();
      this.cancelEdit();
    },
    cancelEdit() {
      this.editing = { day: null, idx: null, from: '', to: '', isNew: false };
      this.editError = '';
    },
    removeBlock(day, idx) {
      if (idx === null || typeof idx === 'undefined') {
        return;
      }
      if (!this.localAvailability.times?.[day]) {
        return;
      }

      this.localAvailability.times[day].splice(idx, 1);
      if (this.editing.day === day && this.editing.idx === idx) {
        this.cancelEdit();
      }
      if (!this.localAvailability.times[day].length) {
        this.localAvailability.weekdays = this.localAvailability.weekdays.filter((weekday) => weekday !== day);
      }
      this.emitAvailability();
    },
    getStarterBlock(interval) {
      if (Number(interval) === 1440) {
        return { from: '00:00', to: '23:59' };
      }
      return { from: '09:00', to: '17:00' };
    },
    createEmptyTimes() {
      return {
        Sun: [],
        Mon: [],
        Tue: [],
        Wed: [],
        Thu: [],
        Fri: [],
        Sat: []
      };
    },
    sortWeekdays(days) {
      // Use module-level constant (not this.weekdayOrder) so cloneAvailability
      // can call this from inside data() before computeds are wired up.
      return WEEKDAY_ORDER.filter((day) => days.includes(day));
    },
    sortDayBlocks(day) {
      if (!Array.isArray(this.localAvailability.times?.[day])) {
        return;
      }
      this.localAvailability.times[day] = [...this.localAvailability.times[day]].sort((a, b) => {
        return this.timeToMinutes(a.from) - this.timeToMinutes(b.from);
      });
    },
    normalizeSlotValue(value) {
      let next = Number(value || 1);
      if (!Number.isFinite(next) || next < 1) {
        next = 1;
      }
      return Math.floor(next);
    },
    timeToMinutes(value) {
      if (!value || typeof value !== 'string') {
        return NaN;
      }
      const parts = value.split(':').map(Number);
      if (parts.length < 2) {
        return NaN;
      }
      const [hours, minutes] = parts;
      if (!Number.isFinite(hours) || !Number.isFinite(minutes)) {
        return NaN;
      }
      return (hours * 60) + minutes;
    },
    minutesToTime(totalMinutes) {
      const mins = Math.max(0, Math.min(totalMinutes, 23 * 60 + 59));
      const hours = Math.floor(mins / 60);
      const minutes = mins % 60;
      return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`;
    },
    normalizeDisplayTime(value) {
      if (typeof value !== 'string') {
        return '';
      }
      const trimmed = value.trim();
      if (!trimmed) {
        return '';
      }
      return trimmed.length >= 5 ? trimmed.slice(0, 5) : trimmed;
    },
    cloneAvailability(source) {
      const empty = {
        weekdays: [],
        interval: 30,
        slots: 1,
        times: this.createEmptyTimes()
      };

      if (!source || typeof source !== 'object') {
        return empty;
      }

      const clone = {
        weekdays: Array.isArray(source.weekdays)
          ? this.sortWeekdays(source.weekdays.filter((day) => WEEKDAY_ORDER.includes(day)))
          : [],
        interval: Number(source.interval || 30),
        slots: this.normalizeSlotValue(source.slots),
        times: this.createEmptyTimes()
      };

      if (!Number.isFinite(clone.interval) || clone.interval < 1) {
        clone.interval = 30;
      }

      Object.entries(source.times || {}).forEach(([day, blocks]) => {
        if (!Object.prototype.hasOwnProperty.call(clone.times, day) || !Array.isArray(blocks)) {
          return;
        }
        clone.times[day] = blocks
          .filter((block) => block && typeof block === 'object')
          .map((block) => ({
            from: this.normalizeDisplayTime(block.from),
            to: this.normalizeDisplayTime(block.to)
          }))
          .filter((block) => block.from && block.to);
      });

      return clone;
    }
  }
};
</script>

<style scoped>
.settings_color_accent {
  background: var(--bookaro-dashboard-accent);
}

.bookaro-settings-help {
  margin-bottom: 0.75rem;
  color: var(--bookaro-dashboard-muted);
  font-size: 0.85rem;
  line-height: 1.45;
}

.bookaro-time-blocks {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
}

.bookaro-time-blocks__list {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
}

.bookaro-time-blocks__empty {
  padding: 0.75rem;
  border: 1px dashed var(--bookaro-dashboard-border);
  border-radius: 0.75rem;
  color: var(--bookaro-dashboard-muted);
  font-size: 0.85rem;
  background: rgba(255, 255, 255, 0.5);
}

.bookaro-guidance-list {
  margin: 0;
  padding-left: 1.1rem;
}

.bookaro-guidance-list li + li {
  margin-top: 0.25rem;
}

.bookaro-time-pill {
  display: inline-flex;
  align-items: center;
  gap: 0.4rem;
  padding: 0.35rem 0.6rem;
  border-radius: 999px;
  border: 1px solid var(--bookaro-dashboard-border);
  background: var(--bookaro-dashboard-surface);
  color: var(--bookaro-dashboard-text);
  font-size: 0.85rem;
  cursor: pointer;
  transition: border-color 0.2s ease, background 0.2s ease;
}

.bookaro-time-pill.is-active {
  border-color: var(--bookaro-dashboard-accent);
  box-shadow: 0 0 0 2px rgba(var(--bookaro-dashboard-accent-rgb), 0.15);
}

.bookaro-time-pill__remove {
  border: none;
  background: transparent;
  color: var(--bookaro-dashboard-muted);
  cursor: pointer;
  font-size: 0.95rem;
  line-height: 1;
}

.bookaro-time-editor {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 0.5rem;
  padding: 0.65rem;
  border: 1px solid var(--bookaro-dashboard-border);
  border-radius: 0.75rem;
  background: var(--bookaro-dashboard-surface);
}

.bookaro-time-editor__actions {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.bookaro-time-editor__error {
  width: 100%;
  color: #dc2626;
  font-size: 0.8rem;
}
</style>
