@extends('layouts.admin')

@section('title', 'Görüşmeler')
@section('page-title', 'Görüşmeler')
@section('page-subtitle', 'Planlanan ve geçmiş görüşmeler')

@push('head')
{{-- FullCalendar v6.1.11 — CSS bu versiyonda JS bundle içinde gelir, ayrı CSS dosyası yoktur --}}
<script src='https://cdn.jsdelivr.net/npm/fullcalendar@6.1.11/index.global.min.js'
        integrity='sha384-5JIwZN3kuxX2zKsavvNmbZ3zhZZMUtu/eQiK3BbXukpSXp0Cd2ZP4OAYKx7mrPgI'
        crossorigin='anonymous'></script>
<style>
    .fc .fc-button { font-size: 0.8rem !important; padding: 0.3rem 0.7rem !important; }
    .fc .fc-button-primary { background-color: #ff7b00 !important; border-color: #ff7b00 !important; }
    .fc .fc-button-primary:hover { background-color: #e06a00 !important; border-color: #e06a00 !important; }
    .fc .fc-toolbar-title { font-size: 1.1rem !important; font-weight: 700 !important; color: #1f2937 !important; }
    .fc .fc-daygrid-event { border-radius: 4px !important; font-size: 0.75rem !important; padding: 1px 4px !important; }
    .fc .fc-timegrid-event { border-radius: 4px !important; font-size: 0.75rem !important; }
    .fc .fc-col-header-cell { background: #f9fafb !important; }
    .fc .fc-col-header-cell-cushion { font-size: 0.75rem !important; font-weight: 600 !important; color: #6b7280 !important; text-transform: uppercase !important; letter-spacing: 0.05em !important; }
    .fc .fc-daygrid-day-number { font-size: 0.8rem !important; color: #374151 !important; }
    .fc .fc-day-today { background: #fff8f0 !important; }
    .fc .fc-day-today .fc-daygrid-day-number { color: #ff7b00 !important; font-weight: 700 !important; }
    .view-btn { background: white; color: #6b7280; }
    .view-btn:hover { background: #f9fafb; }
    .active-view { background: #ff7b00 !important; color: white !important; }

    /* Context Menu (etkinlik + boş gün) */
    .ctx-menu {
        position: fixed;
        z-index: 9999;
        background: white;
        border: 1px solid #e5e7eb;
        border-radius: 8px;
        box-shadow: 0 10px 25px rgba(0,0,0,0.12);
        min-width: 160px;
        padding: 4px 0;
        display: none;
    }
    .ctx-menu a, .ctx-menu button {
        display: flex;
        align-items: center;
        gap: 8px;
        width: 100%;
        padding: 8px 14px;
        font-size: 0.8rem;
        color: #374151;
        text-decoration: none;
        background: none;
        border: none;
        cursor: pointer;
        text-align: left;
    }
    .ctx-menu a:hover, .ctx-menu button:hover { background: #f9fafb; }
    .ctx-menu .menu-divider { height: 1px; background: #f3f4f6; margin: 4px 0; }
    .ctx-menu .menu-danger { color: #dc2626; }
    .ctx-menu .menu-danger:hover { background: #fef2f2; }
    .ctx-menu .menu-completed { color: #059669; }
    .ctx-menu .menu-completed:hover { background: #ecfdf5; }
    .ctx-menu .menu-rescheduled { color: #d97706; }
    .ctx-menu .menu-rescheduled:hover { background: #fffbeb; }

    /* Filtre butonları */
    .filter-btn { cursor: pointer; user-select: none; transition: opacity 0.2s; }
    .filter-btn.inactive { opacity: 0.35; }

    /* Yeniden Planla Modal — inline style ile yönetilir, bu blok kaldırıldı */
</style>
@endpush

@section('content')
<div class="mt-4 flex gap-4" style="min-height: calc(100vh - 180px);">

    {{-- Sol: Takvim --}}
    <div class="flex-1 min-w-0">

        {{-- Üst Bar --}}
        <div class="bg-white rounded-xl shadow-sm border border-gray-100 px-4 py-3 mb-3 flex items-center justify-between">
            <div class="flex items-center gap-2">
                <div class="flex rounded-lg border border-gray-200 overflow-hidden">
                    <a href="{{ route('admin.gorusmeler.index') }}"
                       class="bg-white text-gray-600 px-3 py-2 text-sm hover:bg-gray-50 transition-colors flex items-center gap-1.5">
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 10h16M4 14h16M4 18h16"/></svg>
                        Liste
                    </a>
                    <span class="bg-primary text-white px-3 py-2 text-sm font-medium flex items-center gap-1.5 cursor-default border-l border-orange-400">
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"/></svg>
                        Takvim
                    </span>
                </div>
            </div>
            <div class="flex items-center gap-2">
                @role('super-admin')
                <button onclick="openGorusmeciModal()"
                        class="border border-gray-200 text-gray-600 px-3 py-2 rounded-lg text-sm hover:bg-gray-50 transition-colors flex items-center gap-1.5">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M18 9v3m0 0v3m0-3h3m-3 0h-3m-2-5a4 4 0 11-8 0 4 4 0 018 0zM3 20a6 6 0 0112 0v1H3v-1z"/></svg>
                    Görüşmeci Ekle
                </button>
                @endrole
                <a href="{{ route('admin.gorusmeler.create') }}"
                   class="bg-primary text-white px-4 py-2 rounded-lg text-sm font-medium hover:bg-orange-600 transition-colors flex items-center gap-1.5">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/></svg>
                    Yeni Görüşme
                </a>
            </div>
        </div>

        {{-- Takvim Kontrol Barı --}}
        <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-4 mb-4">
            <div class="flex flex-wrap items-center gap-2">
                <button onclick="calendarPrev()" class="w-8 h-8 flex items-center justify-center rounded-lg border border-gray-200 hover:bg-gray-50 transition-colors text-gray-600">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"/></svg>
                </button>

                <select id="daySelect" onchange="navigateToDayMonthYear()"
                        class="border border-gray-200 rounded-lg px-2 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-orange-400 bg-white w-16">
                    @for($d = 1; $d <= 31; $d++)
                    <option value="{{ $d }}" {{ $d == date('j') ? 'selected' : '' }}>{{ $d }}</option>
                    @endfor
                </select>

                <select id="monthSelect" onchange="navigateToDayMonthYear()"
                        class="border border-gray-200 rounded-lg px-2 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-orange-400 bg-white">
                    <option value="0">Ocak</option><option value="1">Şubat</option><option value="2">Mart</option>
                    <option value="3">Nisan</option><option value="4">Mayıs</option><option value="5">Haziran</option>
                    <option value="6">Temmuz</option><option value="7">Ağustos</option><option value="8">Eylül</option>
                    <option value="9">Ekim</option><option value="10">Kasım</option><option value="11">Aralık</option>
                </select>

                <select id="yearSelect" onchange="navigateToDayMonthYear()"
                        class="border border-gray-200 rounded-lg px-2 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-orange-400 bg-white">
                    @for($y = 2000; $y <= 2040; $y++)
                    <option value="{{ $y }}" {{ $y == date('Y') ? 'selected' : '' }}>{{ $y }}</option>
                    @endfor
                </select>

                <button onclick="calendarNext()" class="w-8 h-8 flex items-center justify-center rounded-lg border border-gray-200 hover:bg-gray-50 transition-colors text-gray-600">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/></svg>
                </button>
                <button onclick="calendarToday()" class="px-3 py-1.5 text-sm border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors text-gray-600">Bugün</button>

                <div class="flex rounded-lg border border-gray-200 overflow-hidden ml-1">
                    <button onclick="setView('dayGridMonth')" id="btn-month" class="view-btn active-view px-3 py-1.5 text-sm transition-colors">Ay</button>
                    <button onclick="setView('timeGridWeek')" id="btn-week" class="view-btn px-3 py-1.5 text-sm border-l border-gray-200 transition-colors">Hafta</button>
                    <button onclick="setView('timeGridDay')" id="btn-day" class="view-btn px-3 py-1.5 text-sm border-l border-gray-200 transition-colors">Gün</button>
                </div>
            </div>

            {{-- Renk Filtre Butonları --}}
            <div class="flex items-center gap-4 mt-3 pt-3 border-t border-gray-100 text-xs text-gray-500">
                <button id="filter-scheduled" onclick="toggleStatusFilter('scheduled')"
                        class="filter-btn flex items-center gap-1.5 hover:text-gray-700 transition-colors">
                    <span class="w-3 h-3 rounded-full bg-blue-500 inline-block"></span> Planlandı
                </button>
                <button id="filter-completed" onclick="toggleStatusFilter('completed')"
                        class="filter-btn flex items-center gap-1.5 hover:text-gray-700 transition-colors">
                    <span class="w-3 h-3 rounded-full bg-green-500 inline-block"></span> Tamamlandı
                </button>
                <button id="filter-rescheduled" onclick="toggleStatusFilter('rescheduled')"
                        class="filter-btn flex items-center gap-1.5 hover:text-gray-700 transition-colors">
                    <span class="w-3 h-3 rounded-full bg-amber-400 inline-block"></span> Yeniden Planlandı
                </button>
                <button id="filter-cancelled" onclick="toggleStatusFilter('cancelled')"
                        class="filter-btn flex items-center gap-1.5 hover:text-gray-700 transition-colors">
                    <span class="w-3 h-3 rounded-full bg-gray-400 inline-block"></span> İptal
                </button>
                @if($googleConnected)
                <button id="filter-google" onclick="toggleStatusFilter('google')"
                        class="filter-btn flex items-center gap-1.5 hover:text-gray-700 transition-colors">
                    <span class="w-3 h-3 rounded-full bg-gray-300 inline-block"></span> Google Takvim
                </button>
                <span class="inline-flex items-center gap-1 bg-green-50 text-green-700 border border-green-200 px-2 py-0.5 rounded-full font-medium ml-1">
                    <svg class="w-3 h-3" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"/></svg>
                    Google Bağlı
                </span>
                @endif
            </div>
        </div>

        {{-- Takvim --}}
        <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-4">
            <div id="calendar"></div>
        </div>
    </div>

    {{-- Sağ: Etkinlik Detay Paneli --}}
    <div id="eventPanel" class="w-72 flex-shrink-0 hidden">
        <div class="bg-white rounded-xl shadow-sm border border-gray-100 sticky top-4">
            <div class="flex items-center justify-between px-4 py-3 border-b border-gray-100">
                <h3 class="font-semibold text-gray-700 text-sm">Etkinlik Detayı</h3>
                <button onclick="closePanel()" class="text-gray-400 hover:text-gray-600 transition-colors">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg>
                </button>
            </div>
            <div class="p-4 space-y-3" id="panelContent"></div>
        </div>
    </div>

</div>

{{-- Etkinlik Sağ Tık Menüsü --}}
<div id="eventContextMenu" class="ctx-menu">
    <a id="ctxDetail" href="#">
        <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/></svg>
        Detay
    </a>
    <a id="ctxEdit" href="#">
        <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/></svg>
        Düzenle
    </a>
    <div class="menu-divider"></div>
    <button onclick="ctxUpdateStatus('completed')" class="menu-completed">
        <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
        Görüşme Yapıldı
    </button>
    <button onclick="ctxOpenReschedule()" class="menu-rescheduled">
        <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"/></svg>
        Yeniden Planla
    </button>
    <button onclick="ctxUpdateStatus('cancelled')" class="menu-danger">
        <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg>
        İptal Et
    </button>
</div>

{{-- Boş Gün Sağ Tık Menüsü --}}
<div id="dayContextMenu" class="ctx-menu">
    <a id="ctxDayAdd" href="#">
        <svg class="w-3.5 h-3.5 text-primary" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/></svg>
        Etkinlik Ekle
    </a>
    <a id="ctxDayView" href="#">
        <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"/></svg>
        Günü Görüntüle
    </a>
</div>

{{-- Yeniden Planla Modal --}}
<div id="rescheduleModal" style="display:none; position:fixed; top:0; left:0; width:100vw; height:100vh; z-index:99999; align-items:center; justify-content:center; background:rgba(0,0,0,0.45);">
    <div style="position:absolute; top:0; left:0; width:100%; height:100%;" onclick="closeRescheduleModal()"></div>
    <div style="position:relative; background:white; border-radius:1rem; box-shadow:0 20px 60px rgba(0,0,0,0.2); width:100%; max-width:24rem; margin:0 1rem; z-index:1; padding:1.5rem;">
        <div class="flex items-center justify-between mb-5">
            <h2 class="text-base font-semibold text-gray-800">Yeniden Planla</h2>
            <button onclick="closeRescheduleModal()" class="text-gray-400 hover:text-gray-600 transition-colors">
                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg>
            </button>
        </div>
        <div class="space-y-4">
            <div>
                <label class="block text-xs font-medium text-gray-600 mb-1">Yeni Tarih & Saat <span class="text-red-500">*</span></label>
                <input type="datetime-local" id="rescheduleDateTime"
                       class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-orange-400">
            </div>
            <div>
                <label class="block text-xs font-medium text-gray-600 mb-1">Süre (dakika)</label>
                <select id="rescheduleDuration"
                        class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-orange-400">
                    <option value="30">30 dakika</option>
                    <option value="45">45 dakika</option>
                    <option value="60" selected>1 saat</option>
                    <option value="90">1.5 saat</option>
                    <option value="120">2 saat</option>
                </select>
            </div>
            <p class="text-xs text-gray-400">Kaydedildiğinde durum "Yeniden Planlandı" olarak güncellenecek.</p>
        </div>
        <div class="flex gap-2 mt-5">
            <button onclick="closeRescheduleModal()"
                    class="flex-1 border border-gray-300 text-gray-600 px-4 py-2 rounded-lg text-sm hover:bg-gray-50 transition-colors">İptal</button>
            <button onclick="submitReschedule()"
                    class="flex-1 bg-primary text-white px-4 py-2 rounded-lg text-sm font-medium hover:bg-orange-600 transition-colors">Kaydet</button>
        </div>
    </div>
</div>

{{-- Hızlı Durum Güncelleme Form --}}
<form id="quickStatusForm" method="POST" style="display:none">
    @csrf
    @method('PUT')
    <input type="hidden" name="status" id="quickStatusValue">
    <input type="hidden" name="title" id="quickStatusTitle">
    <input type="hidden" name="scheduled_at" id="quickStatusScheduledAt">
    <input type="hidden" name="duration_minutes" id="quickStatusDuration">
    <input type="hidden" name="location" id="quickStatusLocation">
    <input type="hidden" name="meeting_link" id="quickStatusMeetingLink">
    <input type="hidden" name="notes" id="quickStatusNotes">
    <input type="hidden" name="interviewer_id" id="quickStatusInterviewerId">
</form>

@role('super-admin')
@include('admin.gorusmeler._gorusmeci_modal', ['allUsers' => $allUsers])
@endrole

<script nonce="{{ app('csp-nonce') }}">
let calendar;
let ctxInterviewId = null;
let ctxEventRef    = null;
const allEvents    = @json($interviews);
const baseUrl      = '{{ url("/admin/gorusmeler") }}';
const createUrl    = '{{ route("admin.gorusmeler.create") }}';

// Aktif filtreler (null = hepsi göster, Set = sadece bunlar)
const activeFilters = new Set(['scheduled', 'completed', 'rescheduled', 'cancelled', 'google']);

document.addEventListener('DOMContentLoaded', function() {
    const calendarEl = document.getElementById('calendar');

    calendar = new FullCalendar.Calendar(calendarEl, {
        initialView: 'dayGridMonth',
        locale: 'tr',
        headerToolbar: false,
        height: 'auto',
        firstDay: 1,
        events: getFilteredEvents(),

        eventClick: function(info) {
            info.jsEvent.preventDefault();
            showEventPanel(info.event);
        },

        eventDidMount: function(info) {
            info.el.style.cursor = 'pointer';
            info.el.addEventListener('contextmenu', function(e) {
                e.preventDefault();
                e.stopPropagation();
                const props = info.event.extendedProps;
                if (props.source === 'google') return;
                showEventContextMenu(e, info.event);
            });
        },

        // Boş güne sağ tık
        dayCellDidMount: function(info) {
            info.el.addEventListener('contextmenu', function(e) {
                // Etkinlik üzerinde değilse
                if (e.target.closest('.fc-event')) return;
                e.preventDefault();
                showDayContextMenu(e, info.date);
            });
        },

        datesSet: function() {
            const date = calendar.getDate();
            document.getElementById('daySelect').value   = date.getDate();
            document.getElementById('monthSelect').value = date.getMonth();
            document.getElementById('yearSelect').value  = date.getFullYear();
        },
    });

    calendar.render();

    const now = new Date();
    document.getElementById('daySelect').value   = now.getDate();
    document.getElementById('monthSelect').value = now.getMonth();
    document.getElementById('yearSelect').value  = now.getFullYear();

    // Tüm menüleri kapat
    document.addEventListener('click', function() {
        document.getElementById('eventContextMenu').style.display = 'none';
        document.getElementById('dayContextMenu').style.display   = 'none';
    });
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            document.getElementById('eventContextMenu').style.display = 'none';
            document.getElementById('dayContextMenu').style.display   = 'none';
            closeRescheduleModal();
        }
    });
});

// ─── Takvim Navigasyon ───────────────────────────────────────────────────────
function calendarPrev()  { calendar.prev(); }
function calendarNext()  { calendar.next(); }
function calendarToday() { calendar.today(); }

function navigateToDayMonthYear() {
    const day   = parseInt(document.getElementById('daySelect').value);
    const month = parseInt(document.getElementById('monthSelect').value);
    const year  = parseInt(document.getElementById('yearSelect').value);
    calendar.gotoDate(new Date(year, month, day));
}

function setView(view) {
    calendar.changeView(view);
    document.querySelectorAll('.view-btn').forEach(b => b.classList.remove('active-view'));
    const map = { dayGridMonth: 'btn-month', timeGridWeek: 'btn-week', timeGridDay: 'btn-day' };
    const btn = document.getElementById(map[view]);
    if (btn) btn.classList.add('active-view');
}

// ─── Filtre ──────────────────────────────────────────────────────────────────
function getFilteredEvents() {
    return allEvents.filter(function(ev) {
        const src    = ev.extendedProps ? ev.extendedProps.source : null;
        const status = ev.extendedProps ? ev.extendedProps.status : null;
        if (src === 'google') return activeFilters.has('google');
        return activeFilters.has(status);
    });
}

function toggleStatusFilter(status) {
    const btn = document.getElementById('filter-' + status);
    if (activeFilters.has(status)) {
        activeFilters.delete(status);
        if (btn) btn.classList.add('inactive');
    } else {
        activeFilters.add(status);
        if (btn) btn.classList.remove('inactive');
    }
    calendar.removeAllEvents();
    calendar.addEventSource(getFilteredEvents());
}

// ─── Etkinlik Sağ Tık Menüsü ─────────────────────────────────────────────────
function showEventContextMenu(e, event) {
    const interviewId = event.id.replace('db_', '');
    ctxInterviewId = interviewId;
    ctxEventRef    = event;

    document.getElementById('ctxDetail').href = baseUrl + '/' + interviewId;
    document.getElementById('ctxEdit').href   = baseUrl + '/' + interviewId + '/edit';

    positionMenu('eventContextMenu', e);
}

function ctxUpdateStatus(newStatus) {
    if (!ctxInterviewId || !ctxEventRef) return;
    document.getElementById('eventContextMenu').style.display = 'none';
    submitStatusUpdate(ctxInterviewId, newStatus, ctxEventRef);
}

function ctxOpenReschedule() {
    if (!ctxInterviewId || !ctxEventRef) return;
    document.getElementById('eventContextMenu').style.display = 'none';
    openRescheduleModal(ctxInterviewId, ctxEventRef);
}

// ─── Boş Gün Sağ Tık Menüsü ──────────────────────────────────────────────────
function showDayContextMenu(e, date) {
    const pad = n => String(n).padStart(2, '0');
    const dateStr = date.getFullYear() + '-' + pad(date.getMonth()+1) + '-' + pad(date.getDate());
    const timeStr = pad(date.getHours()) + ':' + pad(date.getMinutes());
    const dtStr   = dateStr + 'T' + (timeStr === '00:00' ? '09:00' : timeStr);

    document.getElementById('ctxDayAdd').href  = createUrl + '?date=' + encodeURIComponent(dtStr);
    document.getElementById('ctxDayView').href = '#';
    document.getElementById('ctxDayView').onclick = function(ev) {
        ev.preventDefault();
        setView('timeGridDay');
        calendar.gotoDate(date);
    };

    positionMenu('dayContextMenu', e);
}

// ─── Menü Konumlandırma ───────────────────────────────────────────────────────
function positionMenu(menuId, e) {
    // Diğer menüyü kapat
    const other = menuId === 'eventContextMenu' ? 'dayContextMenu' : 'eventContextMenu';
    document.getElementById(other).style.display = 'none';

    const menu = document.getElementById(menuId);
    menu.style.display = 'block';
    const menuW = 170, menuH = 220;
    let x = e.clientX, y = e.clientY;
    if (x + menuW > window.innerWidth)  x = x - menuW;
    if (y + menuH > window.innerHeight) y = y - menuH;
    menu.style.left = x + 'px';
    menu.style.top  = y + 'px';
}

// ─── Yeniden Planla Modal ─────────────────────────────────────────────────────
function openRescheduleModal(interviewId, event) {
    ctxInterviewId = interviewId;
    ctxEventRef    = event;

    // Mevcut tarih/saati doldur
    if (event.start) {
        const dt = event.start;
        const pad = n => String(n).padStart(2, '0');
        const localDt = dt.getFullYear() + '-' + pad(dt.getMonth()+1) + '-' + pad(dt.getDate())
                      + 'T' + pad(dt.getHours()) + ':' + pad(dt.getMinutes());
        document.getElementById('rescheduleDateTime').value = localDt;
    }

    const props = event.extendedProps || {};
    const durSel = document.getElementById('rescheduleDuration');
    const dur = props.duration || 60;
    for (let i = 0; i < durSel.options.length; i++) {
        if (parseInt(durSel.options[i].value) === dur) { durSel.selectedIndex = i; break; }
    }

    document.getElementById('rescheduleModal').style.display = 'flex';
}

function closeRescheduleModal() {
    document.getElementById('rescheduleModal').style.display = 'none';
}

function submitReschedule() {
    const newDt = document.getElementById('rescheduleDateTime').value;
    if (!newDt) { alert('Lütfen yeni tarih ve saat seçin.'); return; }
    if (!ctxInterviewId || !ctxEventRef) return;

    const newDur = document.getElementById('rescheduleDuration').value;
    const props  = ctxEventRef.extendedProps || {};
    const form   = document.getElementById('quickStatusForm');
    form.action  = baseUrl + '/' + ctxInterviewId;

    document.getElementById('quickStatusValue').value         = 'rescheduled';
    document.getElementById('quickStatusTitle').value         = ctxEventRef.title.split(' — ')[0] || ctxEventRef.title;
    document.getElementById('quickStatusScheduledAt').value   = newDt;
    document.getElementById('quickStatusDuration').value      = newDur;
    document.getElementById('quickStatusLocation').value      = props.location || '';
    document.getElementById('quickStatusMeetingLink').value   = props.meetingLink || '';
    document.getElementById('quickStatusNotes').value         = props.notes || '';
    document.getElementById('quickStatusInterviewerId').value = props.interviewerId || '';

    closeRescheduleModal();
    form.submit();
}

// ─── Etkinlik Detay Paneli ────────────────────────────────────────────────────
function showEventPanel(event) {
    const panel   = document.getElementById('eventPanel');
    const content = document.getElementById('panelContent');
    const props   = event.extendedProps;

    if (props.source === 'google') {
        if (event.url) window.open(event.url, '_blank');
        return;
    }

    const interviewId = event.id.replace('db_', '');
    const start = event.start;
    const end   = event.end;

    const statusLabels = {
        scheduled:   '<span class="bg-blue-100 text-blue-700 px-2 py-0.5 rounded-full text-xs font-medium">Planlandı</span>',
        completed:   '<span class="bg-green-100 text-green-700 px-2 py-0.5 rounded-full text-xs font-medium">Tamamlandı</span>',
        cancelled:   '<span class="bg-red-100 text-red-700 px-2 py-0.5 rounded-full text-xs font-medium">İptal</span>',
        rescheduled: '<span class="bg-amber-100 text-amber-700 px-2 py-0.5 rounded-full text-xs font-medium">Yeniden Planlandı</span>',
    };

    const formatDate = function(d) {
        if (!d) return '—';
        return d.toLocaleDateString('tr-TR', { day: '2-digit', month: 'long', year: 'numeric' })
             + ' ' + d.toLocaleTimeString('tr-TR', { hour: '2-digit', minute: '2-digit' });
    };

    const duration = (end && start) ? Math.round((end - start) / 60000) : (props.duration || '—');
    const currentStatus = props.status || 'scheduled';

    // locationHtml: meeting link veya konum için güvenli DOM nodu (XSS-safe)
    let locationNode = null;
    if (props.meetingLink) {
        const safeMeetingLink = (props.meetingLink.startsWith('https://') || props.meetingLink.startsWith('http://'))
            ? props.meetingLink : null;
        const locWrapper = document.createElement('div');
        if (safeMeetingLink) {
            const locA = document.createElement('a');
            locA.href = safeMeetingLink;
            locA.target = '_blank';
            locA.rel = 'noopener noreferrer';
            locA.className = 'text-primary hover:underline text-xs break-all';
            locA.textContent = '🔗 Online Toplantı';
            locWrapper.appendChild(locA);
        } else {
            const locSpan = document.createElement('span');
            locSpan.className = 'text-xs text-gray-400';
            locSpan.textContent = '🔗 Geçersiz link';
            locWrapper.appendChild(locSpan);
        }
        locationNode = locWrapper;
    } else if (props.location) {
        const locWrapper = document.createElement('div');
        const locSpan = document.createElement('span');
        locSpan.className = 'text-xs text-gray-600';
        locSpan.textContent = '📍 ' + props.location;
        locWrapper.appendChild(locSpan);
        locationNode = locWrapper;
    }
    // locationHtml artık kullanılmıyor — locationNode DOM nodu olarak ekleniyor
    const locationHtml = ''; // geriye dönük uyumluluk için boş bırakıldı

    const detailUrl = baseUrl + '/' + interviewId;
    const editUrl   = baseUrl + '/' + interviewId + '/edit';

    // DOM API ile güvenli panel içeriği oluştur (XSS-safe)
    content.innerHTML = '';

    // Başlık
    const titleDiv = document.createElement('div');
    const titleLabel = document.createElement('p'); titleLabel.className = 'text-xs text-gray-400 mb-0.5'; titleLabel.textContent = 'Başlık';
    const titleVal = document.createElement('p'); titleVal.className = 'font-semibold text-gray-800 text-sm leading-snug'; titleVal.textContent = event.title;
    titleDiv.appendChild(titleLabel); titleDiv.appendChild(titleVal);
    content.appendChild(titleDiv);

    // Durum
    const statusDiv = document.createElement('div');
    const statusLabel = document.createElement('p'); statusLabel.className = 'text-xs text-gray-400 mb-0.5'; statusLabel.textContent = 'Durum';
    statusDiv.appendChild(statusLabel);
    statusDiv.insertAdjacentHTML('beforeend', statusLabels[currentStatus] || statusLabels.scheduled);
    content.appendChild(statusDiv);

    // Tarih & Saat
    const dateDiv = document.createElement('div');
    const dateLabel = document.createElement('p'); dateLabel.className = 'text-xs text-gray-400 mb-0.5'; dateLabel.textContent = 'Tarih & Saat';
    const dateVal = document.createElement('p'); dateVal.className = 'text-sm text-gray-700'; dateVal.textContent = formatDate(start);
    const durVal = document.createElement('p'); durVal.className = 'text-xs text-gray-400'; durVal.textContent = duration + ' dakika';
    dateDiv.appendChild(dateLabel); dateDiv.appendChild(dateVal); dateDiv.appendChild(durVal);
    content.appendChild(dateDiv);

    // Başvuran
    if (props.applicantName) {
        const appDiv = document.createElement('div');
        const appLabel = document.createElement('p'); appLabel.className = 'text-xs text-gray-400 mb-0.5'; appLabel.textContent = 'Başvuran';
        const appVal = document.createElement('p'); appVal.className = 'text-sm text-gray-700'; appVal.textContent = props.applicantName;
        appDiv.appendChild(appLabel); appDiv.appendChild(appVal);
        content.appendChild(appDiv);
    }

    // Konum / Link (DOM nodu olarak ekleniyor — XSS-safe)
    if (locationNode) {
        content.appendChild(locationNode);
    }

    // Hızlı Durum Güncelle
    const statusUpdateDiv = document.createElement('div');
    statusUpdateDiv.className = 'pt-2 border-t border-gray-100';
    const statusUpdateLabel = document.createElement('p'); statusUpdateLabel.className = 'text-xs text-gray-400 mb-2'; statusUpdateLabel.textContent = 'Hızlı Durum Güncelle';
    const sel = document.createElement('select');
    sel.className = 'w-full border border-gray-200 rounded-lg px-2 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-orange-400';
    [['', '— Seç —'], ['scheduled', 'Planlandı'], ['completed', 'Tamamlandı'], ['cancelled', 'İptal Edildi'], ['rescheduled', 'Yeniden Planlandı']].forEach(function(pair) {
        const opt = document.createElement('option');
        opt.value = pair[0];
        opt.textContent = pair[1];
        if (pair[0] === currentStatus) opt.selected = true;
        sel.appendChild(opt);
    });
    sel.addEventListener('change', function() { quickUpdateStatus(interviewId, this, null); });
    statusUpdateDiv.appendChild(statusUpdateLabel);
    statusUpdateDiv.appendChild(sel);
    content.appendChild(statusUpdateDiv);

    // Detay / Düzenle butonları
    const btnDiv = document.createElement('div');
    btnDiv.className = 'flex gap-2 pt-1';
    const detailA = document.createElement('a'); detailA.href = detailUrl; detailA.className = 'flex-1 text-center bg-gray-100 text-gray-700 px-3 py-2 rounded-lg text-xs font-medium hover:bg-gray-200 transition-colors'; detailA.textContent = 'Detay';
    const editA = document.createElement('a'); editA.href = editUrl; editA.className = 'flex-1 text-center bg-primary text-white px-3 py-2 rounded-lg text-xs font-medium hover:bg-orange-600 transition-colors'; editA.textContent = 'Düzenle';
    btnDiv.appendChild(detailA); btnDiv.appendChild(editA);
    content.appendChild(btnDiv);

    panel.classList.remove('hidden');
}

function closePanel() {
    document.getElementById('eventPanel').classList.add('hidden');
}

function quickUpdateStatus(interviewId, selectEl, nativeEvent) {
    const newStatus = selectEl.value;
    if (!newStatus) return;
    const event = calendar.getEventById('db_' + interviewId);
    if (!event) return;

    if (newStatus === 'rescheduled') {
        selectEl.value = ''; // sıfırla
        openRescheduleModal(interviewId, event);
        return;
    }
    submitStatusUpdate(interviewId, newStatus, event);
}

// ─── Yerel Saat Formatı (UTC kaymasını önler) ─────────────────────────────────
function toLocalDateTimeString(date) {
    if (!date) return '';
    var pad = function(n) { return String(n).padStart(2, '0'); };
    return date.getFullYear() + '-' + pad(date.getMonth() + 1) + '-' + pad(date.getDate())
         + 'T' + pad(date.getHours()) + ':' + pad(date.getMinutes());
}

function submitStatusUpdate(interviewId, newStatus, event) {
    const props = event.extendedProps;
    const form  = document.getElementById('quickStatusForm');
    form.action = baseUrl + '/' + interviewId;

    document.getElementById('quickStatusValue').value         = newStatus;
    document.getElementById('quickStatusTitle').value         = event.title.split(' — ')[0] || event.title;
    document.getElementById('quickStatusScheduledAt').value   = toLocalDateTimeString(event.start);
    document.getElementById('quickStatusDuration').value      = props.duration || 60;
    document.getElementById('quickStatusLocation').value      = props.location || '';
    document.getElementById('quickStatusMeetingLink').value   = props.meetingLink || '';
    document.getElementById('quickStatusNotes').value         = props.notes || '';
    document.getElementById('quickStatusInterviewerId').value = props.interviewerId || '';

    form.submit();
}
</script>
@endsection