<template>
  <div class="cw-dt-picker" ref="pickerRef">
    <!-- Clickable input field -->
    <div class="cw-dt-trigger" @click="togglePopover">
      <svg v-if="mode === 'time'" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" class="cw-dt-icon">
        <path stroke-linecap="round" stroke-linejoin="round" d="M12 6v6h4.5m4.5 0a9 9 0 11-18 0 9 9 0 0118 0z" />
      </svg>
      <svg v-else xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" class="cw-dt-icon">
        <path stroke-linecap="round" stroke-linejoin="round" d="M6.75 3v2.25M17.25 3v2.25M3 18.75V7.5a2.25 2.25 0 012.25-2.25h13.5A2.25 2.25 0 0121 7.5v11.25m-18 0A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75m-18 0v-7.5A2.25 2.25 0 015.25 9h13.5A2.25 2.25 0 0121 11.25v7.5m-9-6h.008v.008H12v-.008zM12 15h.008v.008H12V15zm0 2.25h.008v.008H12v-.008zM9.75 15h.008v.008H9.75V15zm0 2.25h.008v.008H9.75v-.008zM7.5 15h.008v.008H7.5V15zm0 2.25h.008v.008H7.5v-.008zm6.75-4.5h.008v.008h-.008v-.008zm0 2.25h.008v.008h-.008V15zm0 2.25h.008v.008h-.008v-.008zm2.25-4.5h.008v.008H16.5v-.008zm0 2.25h.008v.008H16.5V15z" />
      </svg>
      <span class="cw-dt-trigger-text" :class="{ 'is-placeholder': !modelValue }">
        {{ formattedValue || placeholder || (mode === 'time' ? 'Select Time' : mode === 'date' ? 'Select Date' : 'Select Date & Time') }}
      </span>
      <span v-if="modelValue" class="cw-dt-clear" @click.stop="clearValue">✕</span>
    </div>

    <!-- Datepicker popover -->
    <div v-if="isOpen" class="cw-dt-popover" :class="[popoverAlignClass, `is-placement-${placement}`]">
      
      <!-- TAB 1: Calendar View -->
      <template v-if="popoverTab === 'date'">
        <div class="cw-dt-calendar-panel">
          <!-- Calendar Header -->
          <div class="cw-dt-cal-header">
            <button type="button" class="cw-dt-nav-btn" @click.stop="prevMonth">
              <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" width="14" height="14">
                <path fill-rule="evenodd" d="M12.79 5.23a.75.75 0 01-.02 1.06L8.832 10l3.938 3.71a.75.75 0 11-1.04 1.08l-4.5-4.25a.75.75 0 010-1.08l4.5-4.25a.75.75 0 011.06.02z" clip-rule="evenodd" />
              </svg>
            </button>
            <span class="cw-dt-month-year">{{ monthNames[currentMonth] }} {{ currentYear }}</span>
            <button type="button" class="cw-dt-nav-btn" @click.stop="nextMonth">
              <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" width="14" height="14">
                <path fill-rule="evenodd" d="M7.21 14.77a.75.75 0 01.02-1.06L11.168 10 7.23 6.29a.75.75 0 111.04-1.08l4.5 4.25a.75.75 0 010 1.08l-4.5 4.25a.75.75 0 01-1.06-.02z" clip-rule="evenodd" />
              </svg>
            </button>
          </div>

          <!-- Days of week -->
          <div class="cw-dt-weekdays">
            <span v-for="d in dayLabels" :key="d" class="cw-dt-weekday">{{ d }}</span>
          </div>

          <!-- Calendar Grid -->
          <div class="cw-dt-days-grid">
            <!-- Empty days for offsetting -->
            <span v-for="empty in offsetDays" :key="'empty-' + empty" class="cw-dt-day is-empty"></span>
            
            <!-- Days of active month -->
            <button
              v-for="day in daysInMonth"
              :key="day"
              type="button"
              class="cw-dt-day"
              :class="{
                'is-selected': isSameDay(day),
                'is-today': isToday(day)
              }"
              :disabled="isDateDisabled(day)"
              @click.stop="selectDay(day)"
            >
              {{ day }}
            </button>
          </div>
        </div>

        <!-- Time Row Trigger (Transitions to Time Tab) -->
        <div v-if="mode !== 'date'" class="cw-dt-time-row" @click.stop="switchToTimeTab">
          <div class="cw-dt-time-label">
            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" style="width:14px;height:14px;color:#6b7280;">
              <path stroke-linecap="round" stroke-linejoin="round" d="M12 6v6h4.5m4.5 0a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
            <span>Time</span>
          </div>
          <div class="cw-dt-time-display-preview" @click.stop="switchToTimeTab">
            {{ pad(selectedHour) }}:{{ pad(selectedMinute) }} {{ selectedAmPm }}
          </div>
        </div>

        <!-- Footer -->
        <div class="cw-dt-footer">
          <button type="button" class="cw-dt-action-btn is-secondary" @click.stop="setToday">Current Time</button>
          <button type="button" class="cw-dt-action-btn is-primary" @click.stop="confirmSelection">OK</button>
        </div>
      </template>

      <!-- TAB 2: Material Design Time Picker View -->
      <template v-else>
        <!-- Time Header Display -->
        <div class="cw-mtp-header">
          <div class="cw-mtp-title">Select Time</div>
          <div class="cw-mtp-time-display">
            <button
              type="button"
              class="cw-mtp-digit-btn"
              :class="{ 'is-active': activeMode === 'hours' && !isKeyboardMode }"
              @click.stop="activeMode = 'hours'; isKeyboardMode = false"
            >
              {{ pad(selectedHour) }}
            </button>
            <span class="cw-mtp-colon">:</span>
            <button
              type="button"
              class="cw-mtp-digit-btn"
              :class="{ 'is-active': activeMode === 'minutes' && !isKeyboardMode }"
              @click.stop="activeMode = 'minutes'; isKeyboardMode = false"
            >
              {{ pad(selectedMinute) }}
            </button>
            <div class="cw-mtp-ampm-box">
              <button
                type="button"
                class="cw-mtp-ampm-btn"
                :class="{ 'is-active': selectedAmPm === 'AM' }"
                @click.stop="selectedAmPm = 'AM'"
              >
                AM
              </button>
              <button
                type="button"
                class="cw-mtp-ampm-btn"
                :class="{ 'is-active': selectedAmPm === 'PM' }"
                @click.stop="selectedAmPm = 'PM'"
              >
                PM
              </button>
            </div>
          </div>
        </div>

        <!-- Clock Face selection -->
        <div class="cw-mtp-clock-container" v-if="!isKeyboardMode">
          <div
            class="cw-mtp-clock-face"
            ref="clockFaceRef"
            @mousedown="handleClockMouseDown"
          >
            <!-- Center pivot dot -->
            <div class="cw-mtp-clock-center"></div>
            
            <!-- Rotating needle hand -->
            <div class="cw-mtp-clock-hand" :style="handStyle">
              <!-- Active Selection circle badge -->
              <div class="cw-mtp-clock-hand-end"></div>
            </div>

            <!-- Clock face numbers -->
            <div
              v-for="num in activeClockNumbers"
              :key="num"
              class="cw-mtp-clock-num"
              :class="{ 'is-active': isNumberActive(num) }"
              :style="getNumberStyle(num)"
            >
              {{ activeMode === 'hours' ? num : pad(num) }}
            </div>
          </div>
        </div>

        <!-- Keyboard input mode -->
        <div class="cw-mtp-keyboard-container" v-else>
          <div class="cw-mtp-keyboard-fields">
            <input
              type="text"
              class="cw-mtp-kbd-input"
              v-model="hourInput"
              @input="onHourInput"
              @blur="onHourBlur"
              maxlength="2"
            />
            <span class="cw-mtp-kbd-colon">:</span>
            <input
              type="text"
              class="cw-mtp-kbd-input"
              v-model="minuteInput"
              @input="onMinuteInput"
              @blur="onMinuteBlur"
              maxlength="2"
            />
          </div>
          <div class="cw-mtp-kbd-hint">Enter hours and minutes</div>
        </div>

        <!-- Time Footer (Keyboard toggle + OK) -->
        <div class="cw-mtp-footer">
          <button type="button" class="cw-mtp-toggle-btn" @click.stop="isKeyboardMode = !isKeyboardMode" title="Toggle input method">
            <svg v-if="!isKeyboardMode" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" style="width:20px;height:20px;">
              <path stroke-linecap="round" stroke-linejoin="round" d="M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z" />
            </svg>
            <svg v-else xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" style="width:20px;height:20px;">
              <path stroke-linecap="round" stroke-linejoin="round" d="M12 6v6h4.5m4.5 0a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
          </button>
          <button type="button" class="cw-mtp-action-btn is-primary" @click.stop="mode === 'time' ? confirmSelection() : (popoverTab = 'date')">OK</button>
        </div>
      </template>

    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, onBeforeUnmount, nextTick } from 'vue';

const props = defineProps({
    modelValue: { type: String, default: '' },
    placeholder: { type: String, default: '' },
    align: { type: String, default: 'left' },
    placement: { type: String, default: 'bottom' }, // 'top' or 'bottom'
    mode: { type: String, default: 'datetime' }, // 'datetime', 'date', 'time'
    disablePast: { type: Boolean, default: true },
    disableFuture: { type: Boolean, default: false }
});

const emit = defineEmits(['update:modelValue']);

const isOpen = ref(false);
const pickerRef = ref(null);

// Tab view state: 'date' or 'time'
const popoverTab = ref('date');

// Time Picker specific states
const isKeyboardMode = ref(false);
const activeMode = ref('hours'); // 'hours' or 'minutes'
const clockFaceRef = ref(null);

// Active navigation view state
const currentMonth = ref(new Date().getMonth());
const currentYear = ref(new Date().getFullYear());

// Selected states
const selectedDate = ref(null);
const selectedHour = ref(12);
const selectedMinute = ref(0);
const selectedAmPm = ref('PM');

// Input text inputs state
const hourInput = ref('12');
const minuteInput = ref('00');

// Reactivity lock to prevent redundant watcher loops
let ignoreStateWatch = false;

const monthNames = [
    'January', 'February', 'March', 'April', 'May', 'June',
    'July', 'August', 'September', 'October', 'November', 'December'
];
const dayLabels = ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'];

// Format selected date-time display
const formattedValue = computed(() => {
    if (!props.modelValue) return '';
    try {
        const d = new Date(props.modelValue);
        if (isNaN(d.getTime())) return props.modelValue;
        if (props.mode === 'date') {
            return d.toLocaleDateString('en-US', {
                month: 'short',
                day: 'numeric',
                year: 'numeric'
            });
        }
        if (props.mode === 'time') {
            let h = d.getHours();
            const ampm = h >= 12 ? 'PM' : 'AM';
            h = h % 12;
            h = h === 0 ? 12 : h;
            const m = String(d.getMinutes()).padStart(2, '0');
            return `${h}:${m} ${ampm}`;
        }
        return d.toLocaleString('en-US', {
            month: 'short',
            day: 'numeric',
            year: 'numeric',
            hour: 'numeric',
            minute: '2-digit',
            hour12: true
        });
    } catch {
        return props.modelValue;
    }
});

const popoverAlignClass = computed(() => `is-align-${props.align}`);

// Calendar grid calculations
const offsetDays = computed(() => {
    const firstDay = new Date(currentYear.value, currentMonth.value, 1).getDay();
    return firstDay;
});

const daysInMonth = computed(() => {
    return new Date(currentYear.value, currentMonth.value + 1, 0).getDate();
});

// Clock face configuration
const activeClockNumbers = computed(() => {
    return activeMode.value === 'hours'
        ? [12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
        : [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55];
});

// Pointer/Hand rotation style
const handStyle = computed(() => {
    const angle = activeMode.value === 'hours'
        ? selectedHour.value * 30
        : selectedMinute.value * 6;
    return {
        transform: `rotate(${angle}deg)`
    };
});

// Watch modelValue changes to sync internal state
watch(() => props.modelValue, (val) => {
    if (val) {
        const d = new Date(val);
        if (!isNaN(d.getTime())) {
            ignoreStateWatch = true;
            selectedDate.value = new Date(d.getFullYear(), d.getMonth(), d.getDate());
            currentMonth.value = d.getMonth();
            currentYear.value = d.getFullYear();
            
            let h = d.getHours();
            selectedAmPm.value = h >= 12 ? 'PM' : 'AM';
            h = h % 12;
            selectedHour.value = h === 0 ? 12 : h;
            selectedMinute.value = d.getMinutes();
            nextTick(() => { ignoreStateWatch = false; });
            return;
        }
    }
    
    // Default fallback for empty or invalid date values
    selectedDate.value = null;
    currentMonth.value = new Date().getMonth();
    currentYear.value = new Date().getFullYear();
}, { immediate: true });

// Sync keyboard inputs with selected state
watch(selectedHour, (val) => {
    hourInput.value = pad(val);
}, { immediate: true });

watch(selectedMinute, (val) => {
    minuteInput.value = pad(val);
}, { immediate: true });

// Auto-sync state changes back to parent
watch([selectedDate, selectedHour, selectedMinute, selectedAmPm], () => {
    if (ignoreStateWatch || (props.mode !== 'time' && !selectedDate.value)) return;
    applySilent();
}, { deep: true });

function togglePopover() {
    isOpen.value = !isOpen.value;
    if (isOpen.value) {
        popoverTab.value = props.mode === 'time' ? 'time' : 'date';
        activeMode.value = 'hours';
        isKeyboardMode.value = false;
    }
}

function closePopover() {
    isOpen.value = false;
}

function clearValue() {
    emit('update:modelValue', '');
    selectedDate.value = null;
    closePopover();
}

// Navigation
function prevMonth() {
    if (currentMonth.value === 0) {
        currentMonth.value = 11;
        currentYear.value--;
    } else {
        currentMonth.value--;
    }
}

function nextMonth() {
    if (currentMonth.value === 11) {
        currentMonth.value = 0;
        currentYear.value++;
    } else {
        currentMonth.value++;
    }
}

// Selection helpers
function selectDay(day) {
    if (isDateDisabled(day)) return;
    selectedDate.value = new Date(currentYear.value, currentMonth.value, day);
    if (props.mode === 'date') {
        confirmSelection();
    }
}

function isSameDay(day) {
    if (!selectedDate.value) return false;
    return selectedDate.value.getDate() === day &&
           selectedDate.value.getMonth() === currentMonth.value &&
           selectedDate.value.getFullYear() === currentYear.value;
}

function isToday(day) {
    const today = new Date();
    return today.getDate() === day &&
           today.getMonth() === currentMonth.value &&
           today.getFullYear() === currentYear.value;
}

function isDateDisabled(day) {
    const today = new Date();
    const todayDate = new Date(today.getFullYear(), today.getMonth(), today.getDate());
    const checkDate = new Date(currentYear.value, currentMonth.value, day);
    if (props.disablePast && checkDate < todayDate) return true;
    if (props.disableFuture && checkDate > todayDate) return true;
    return false;
}

function pad(num) {
    return String(num).padStart(2, '0');
}

function setToday() {
    const today = new Date();
    selectedDate.value = new Date(today.getFullYear(), today.getMonth(), today.getDate());
    currentMonth.value = today.getMonth();
    currentYear.value = today.getFullYear();
    
    let h = today.getHours();
    selectedAmPm.value = h >= 12 ? 'PM' : 'AM';
    h = h % 12;
    selectedHour.value = h === 0 ? 12 : h;
    selectedMinute.value = today.getMinutes();
}

function confirmSelection() {
    if (!selectedDate.value) {
        setToday();
    }
    closePopover();
}

// Clock Face interaction coordinates calculation
function handleClockMouseDown(e) {
    e.preventDefault();
    updateTimeFromCoords(e);
    
    const onMouseMove = (moveEvent) => {
        updateTimeFromCoords(moveEvent);
    };
    
    const onMouseUp = () => {
        document.removeEventListener('mousemove', onMouseMove);
        document.removeEventListener('mouseup', onMouseUp);
        // Switch to minutes mode automatically after releasing hours selection
        if (activeMode.value === 'hours') {
            activeMode.value = 'minutes';
        }
    };
    
    document.addEventListener('mousemove', onMouseMove);
    document.addEventListener('mouseup', onMouseUp);
}

function updateTimeFromCoords(e) {
    if (!clockFaceRef.value) return;
    const rect = clockFaceRef.value.getBoundingClientRect();
    const centerX = rect.left + rect.width / 2;
    const centerY = rect.top + rect.height / 2;
    
    const clientX = e.clientX;
    const clientY = e.clientY;
    
    const dx = clientX - centerX;
    const dy = clientY - centerY;
    
    const angleRad = Math.atan2(dy, dx);
    const angleDeg = angleRad * (180 / Math.PI);
    
    const clockDeg = (angleDeg + 90 + 360) % 360;
    
    if (activeMode.value === 'hours') {
        let hour = Math.round(clockDeg / 30);
        if (hour === 0) hour = 12;
        selectedHour.value = hour;
    } else {
        let minute = Math.round(clockDeg / 6) % 60;
        selectedMinute.value = minute;
    }
}

// Check if a number is active in dial
function isNumberActive(num) {
    if (activeMode.value === 'hours') {
        return selectedHour.value === num;
    } else {
        return selectedMinute.value === num;
    }
}

// Compute dynamic CSS position around the circle
function getNumberStyle(num) {
    const isMinutes = activeMode.value === 'minutes';
    const val = isMinutes ? num : num;
    const angle = (val * (isMinutes ? 6 : 30) - 90) * (Math.PI / 180);
    const r = 74; // perimeter radius
    const x = 100 + r * Math.cos(angle);
    const y = 100 + r * Math.sin(angle);
    return {
        left: `${x}px`,
        top: `${y}px`
    };
}

// Keyboard input helpers
function onHourInput(e) {
    let val = e.target.value.replace(/\D/g, '');
    if (val.length > 2) val = val.slice(0, 2);
    hourInput.value = val;
}

function onHourBlur() {
    let num = parseInt(hourInput.value);
    if (isNaN(num) || num < 1 || num > 12) {
        hourInput.value = pad(selectedHour.value);
    } else {
        selectedHour.value = num;
        hourInput.value = pad(num);
    }
}

function onMinuteInput(e) {
    let val = e.target.value.replace(/\D/g, '');
    if (val.length > 2) val = val.slice(0, 2);
    minuteInput.value = val;
}

function onMinuteBlur() {
    let num = parseInt(minuteInput.value);
    if (isNaN(num) || num < 0 || num > 59) {
        minuteInput.value = pad(selectedMinute.value);
    } else {
        selectedMinute.value = num;
        minuteInput.value = pad(num);
    }
}

function toggleAmPm() {
    selectedAmPm.value = selectedAmPm.value === 'AM' ? 'PM' : 'AM';
}

function switchToTimeTab() {
    popoverTab.value = 'time';
}

function applySilent() {
    const d = selectedDate.value || new Date();
    const year = d.getFullYear();
    const month = String(d.getMonth() + 1).padStart(2, '0');
    const day = String(d.getDate()).padStart(2, '0');
    
    let hours = selectedHour.value;
    if (selectedAmPm.value === 'PM' && hours < 12) hours += 12;
    if (selectedAmPm.value === 'AM' && hours === 12) hours = 0;
    const hourStr = String(hours).padStart(2, '0');
    const minuteStr = String(selectedMinute.value).padStart(2, '0');
    
    const localDateTimeStr = `${year}-${month}-${day}T${hourStr}:${minuteStr}`;
    emit('update:modelValue', localDateTimeStr);
}

// Click outside handler
function handleClickOutside(e) {
    if (pickerRef.value && !pickerRef.value.contains(e.target)) {
        closePopover();
    }
}

onMounted(() => {
    document.addEventListener('click', handleClickOutside);
});

onBeforeUnmount(() => {
    document.removeEventListener('click', handleClickOutside);
});
</script>

<style scoped>
.cw-dt-picker {
    position: relative;
    display: inline-block;
    width: 100%;
}

.cw-dt-trigger {
    display: flex;
    align-items: center;
    width: 100%;
    height: 40px;
    padding: 0 12px;
    background: var(--bg-surface);
    border: 1px solid var(--border-color);
    border-radius: 8px;
    font-size: 13px;
    color: var(--text-primary);
    cursor: pointer;
    user-select: none;
    transition: all 0.2s;
    
}

.cw-dt-trigger:hover {
    border-color: var(--text-muted);
}

.cw-dt-trigger:focus-within {
    border-color: var(--active-text);
    box-shadow: 0 0 0 3px var(--active-bg);
}

.cw-dt-icon {
    width: 18px;
    height: 18px;
    color: var(--text-muted);
    margin-right: 6px;
    flex-shrink: 0;
}

.cw-dt-trigger-text {
    flex: 1;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.cw-dt-trigger-text.is-placeholder {
    color: var(--text-muted);
}

.cw-dt-clear {
    color: var(--text-muted);
    font-size: 11px;
    padding: 4px;
    margin-right: -4px;
    border-radius: 50%;
    transition: background 0.15s, color 0.15s;
}

.cw-dt-clear:hover {
    background: var(--bg-hover-strong);
    color: var(--text-primary);
}

/* Popover styling */
.cw-dt-popover {
    position: absolute;
    z-index: 1000;
    background: var(--bg-surface);
    border: 1px solid var(--border-color);
    border-radius: 12px;
    box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.08), 0 8px 10px -6px rgba(0, 0, 0, 0.05);
    display: flex;
    flex-direction: column;
    overflow: hidden;
    user-select: none;
    width: 280px;
    animation: slideUp 0.15s cubic-bezier(0.16, 1, 0.3, 1);
}

.cw-dt-popover.is-placement-top {
    bottom: calc(100% + 6px);
    top: auto;
}

.cw-dt-popover.is-placement-bottom {
    top: calc(100% + 6px);
    bottom: auto;
}

.cw-dt-popover.is-align-left {
    left: 0;
    right: auto;
}

.cw-dt-popover.is-align-right {
    right: 0;
    left: auto;
}

@keyframes slideUp {
    from {
        opacity: 0;
        transform: translateY(4px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

/* Calendar styling */
.cw-dt-calendar-panel {
    padding: 12px;
}

.cw-dt-cal-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 8px;
}

.cw-dt-month-year {
    font-size: 13px;
    font-weight: 600;
    color: var(--text-primary);
}

.cw-dt-nav-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 24px;
    height: 24px;
    border-radius: 6px;
    border: 1px solid var(--border-color);
    background: var(--bg-surface);
    color: var(--text-secondary);
    cursor: pointer;
    transition: all 0.15s;
}

.cw-dt-nav-btn:hover {
    background: var(--bg-hover);
    color: var(--text-primary);
}

.cw-dt-weekdays {
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    margin-bottom: 4px;
    text-align: center;
}

.cw-dt-weekday {
    font-size: 10px;
    font-weight: 600;
    color: var(--text-muted);
    text-transform: uppercase;
}

.cw-dt-days-grid {
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    gap: 2px;
}

.cw-dt-day {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 28px;
    border-radius: 6px;
    border: none;
    background: transparent;
    font-size: 11.5px;
    color: var(--text-secondary);
    cursor: pointer;
    transition: all 0.15s;
}

.cw-dt-day:disabled {
    color: var(--text-muted) !important;
    background: transparent !important;
    cursor: not-allowed;
    pointer-events: none;
}

.cw-dt-day:hover:not(.is-empty) {
    background: var(--bg-hover);
    color: var(--text-primary);
}

.cw-dt-day.is-selected {
    background: var(--active-text) !important;
    color: var(--bg-surface) !important;
    font-weight: 600;
}

.cw-dt-day.is-today:not(.is-selected) {
    background: var(--active-bg);
    color: var(--active-text);
    font-weight: 600;
}

.cw-dt-day.is-empty {
    cursor: default;
    pointer-events: none;
}

/* Time Row Styling in Calendar */
.cw-dt-time-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px 12px;
    border-top: 1px solid var(--border-color);
    background: var(--bg-hover);
    cursor: pointer;
    transition: background 0.15s;
}

.cw-dt-time-row:hover {
    background: var(--bg-hover-strong);
}

.cw-dt-time-label {
    display: flex;
    align-items: center;
    gap: 6px;
    font-size: 12px;
    font-weight: 600;
    color: var(--text-secondary);
}

.cw-dt-time-display-preview {
    font-size: 12px;
    font-weight: 700;
    color: var(--active-text);
    background: var(--active-bg);
    padding: 3px 8px;
    border-radius: 6px;
}

/* Footer styling */
.cw-dt-footer {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 8px 12px;
    background: var(--bg-hover);
    border-top: 1px solid var(--border-color);
}

.cw-dt-action-btn {
    font-size: 11px;
    font-weight: 600;
    padding: 5px 10px;
    border-radius: 6px;
    cursor: pointer;
    transition: all 0.15s;
}

.cw-dt-action-btn.is-secondary {
    border: 1px solid var(--border-color);
    background: var(--bg-surface);
    color: var(--text-secondary);
}

.cw-dt-action-btn.is-secondary:hover {
    background: var(--bg-hover);
}

.cw-dt-action-btn.is-primary {
    border: 1px solid transparent;
    background: var(--active-text);
    color: var(--bg-surface);
}

.cw-dt-action-btn.is-primary:hover {
    opacity: 0.9;
}

/* ─────────────────────────────────────────────────────────────
   Material Time Picker Panel Styles
   ───────────────────────────────────────────────────────────── */
.cw-mtp-header {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 16px 16px 12px;
    background: var(--bg-surface);
    border-bottom: 1px solid var(--border-color);
}

.cw-mtp-title {
    font-size: 10px;
    font-weight: 600;
    color: var(--text-muted);
    text-transform: uppercase;
    letter-spacing: 0.05em;
    margin-bottom: 12px;
    align-self: flex-start;
}

.cw-mtp-time-display {
    display: flex;
    align-items: center;
    gap: 8px;
}

.cw-mtp-digit-btn {
    width: 64px;
    height: 56px;
    background: var(--bg-hover);
    border: none;
    border-radius: 8px;
    font-size: 36px;
    font-weight: 600;
    color: var(--text-primary);
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all 0.2s;
}

.cw-mtp-digit-btn.is-active {
    background: var(--active-bg);
    color: var(--active-text);
}

.cw-mtp-colon {
    font-size: 32px;
    font-weight: 600;
    color: var(--text-muted);
}

.cw-mtp-ampm-box {
    display: flex;
    flex-direction: column;
    border: 1px solid var(--border-color);
    border-radius: 8px;
    overflow: hidden;
    width: 44px;
    height: 56px;
}

.cw-mtp-ampm-btn {
    flex: 1;
    border: none;
    background: var(--bg-surface);
    font-size: 11px;
    font-weight: 700;
    color: var(--text-secondary);
    cursor: pointer;
    transition: all 0.2s;
    line-height: 1;
}

.cw-mtp-ampm-btn:first-child {
    border-bottom: 1px solid var(--border-color);
}

.cw-mtp-ampm-btn.is-active {
    background: var(--active-bg);
    color: var(--active-text);
}

/* Clock Container & dial styles */
.cw-mtp-clock-container {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 20px 0;
    background: var(--bg-surface);
}

.cw-mtp-clock-face {
    width: 200px;
    height: 200px;
    border-radius: 50%;
    background: var(--bg-hover);
    position: relative;
    cursor: pointer;
}

.cw-mtp-clock-center {
    width: 6px;
    height: 6px;
    background: var(--active-text);
    border-radius: 50%;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
}

.cw-mtp-clock-hand {
    position: absolute;
    left: 50%;
    bottom: 50%;
    width: 2px;
    height: 74px;
    background: var(--active-text);
    transform-origin: bottom center;
    pointer-events: none;
}

.cw-mtp-clock-hand-end {
    width: 28px;
    height: 28px;
    background: var(--active-text);
    border-radius: 50%;
    position: absolute;
    top: -14px;
    left: -13px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.cw-mtp-clock-num {
    position: absolute;
    width: 24px;
    height: 24px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 13px;
    font-weight: 500;
    color: var(--text-secondary);
    transform: translate(-50%, -50%);
    pointer-events: none;
    transition: color 0.15s;
}

.cw-mtp-clock-num.is-active {
    color: var(--bg-surface);
    font-weight: 600;
    z-index: 5;
}

/* Keyboard/manual input mode styles */
.cw-mtp-keyboard-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 24px 16px;
    background: var(--bg-surface);
    height: 240px;
}

.cw-mtp-keyboard-fields {
    display: flex;
    align-items: center;
    gap: 8px;
}

.cw-mtp-kbd-input {
    width: 72px;
    height: 64px;
    background: var(--bg-hover);
    border: 1px solid var(--border-color);
    border-radius: 8px;
    font-size: 36px;
    font-weight: 600;
    color: var(--text-primary);
    text-align: center;
    outline: none;
    transition: all 0.2s;
}

.cw-mtp-kbd-input:focus {
    border-color: var(--active-text);
    background: var(--active-bg);
    color: var(--active-text);
}

.cw-mtp-kbd-colon {
    font-size: 32px;
    font-weight: 600;
    color: var(--text-muted);
}

.cw-mtp-kbd-hint {
    font-size: 11px;
    color: var(--text-muted);
    margin-top: 12px;
}

/* MTP Footer actions */
.cw-mtp-footer {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12px 16px;
    background: var(--bg-surface);
    border-top: 1px solid var(--border-color);
}

.cw-mtp-toggle-btn {
    border: none;
    background: transparent;
    color: var(--text-secondary);
    cursor: pointer;
    padding: 6px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: background 0.15s, color 0.15s;
}

.cw-mtp-toggle-btn:hover {
    background: var(--bg-hover);
    color: var(--text-primary);
}

.cw-mtp-action-btn {
    border: none;
    background: transparent;
    font-size: 12px;
    font-weight: 700;
    color: var(--active-text);
    cursor: pointer;
    padding: 6px 12px;
    border-radius: 6px;
    transition: background 0.15s;
}

.cw-mtp-action-btn:hover {
    background: var(--active-bg);
}
</style>
