<?= $this->extend('layouts/panel') ?>
<?= $this->section('sidebar') ?>
<?= $this->include('panel/_sidebar') ?>
<?= $this->endSection() ?>

<?= $this->section('content') ?>
<h5 class="mb-3">Interviews</h5>
<div id="interviewsList"></div>
<div id="interviewsEmpty" class="li-card li-card-body text-center text-muted py-5 d-none">
    <i class="bi bi-camera-video display-4 d-block mb-2"></i>No interviews scheduled. Schedule one from the ATS pipeline.
</div>

<div class="modal fade" id="feedbackModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header"><h6 class="modal-title">Interview Feedback</h6><button class="btn-close" data-bs-dismiss="modal"></button></div>
            <div class="modal-body">
                <input type="hidden" id="fbInterviewId">
                <label class="form-label">Rating (1-5)</label>
                <select id="fbRating" class="form-select mb-2">
                    <option value="5">5 — Excellent</option>
                    <option value="4">4 — Good</option>
                    <option value="3">3 — Average</option>
                    <option value="2">2 — Below Average</option>
                    <option value="1">1 — Poor</option>
                </select>
                <label class="form-label">Feedback</label>
                <textarea id="fbText" class="form-control" rows="4"></textarea>
            </div>
            <div class="modal-footer"><button class="btn btn-li-primary" onclick="submitFeedback()">Submit</button></div>
        </div>
    </div>
</div>
<div class="modal fade" id="timelineModal" tabindex="-1">
    <div class="modal-dialog modal-lg modal-dialog-scrollable">
        <div class="modal-content">
            <div class="modal-header">
                <h6 class="modal-title">Interview Details</h6>
                <button class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <input type="hidden" id="tlInterviewId">

                <h6 class="mb-2">Add Update</h6>
                <div class="d-flex gap-2 mb-3">
                    <input type="text" id="noteInput" class="form-control form-control-sm" placeholder="Add a note about this interview...">
                    <button class="btn btn-li-primary btn-sm" onclick="submitNote()">Add</button>
                </div>

                <h6 class="mb-2">Files</h6>
                <div class="d-flex gap-2 mb-3">
                    <input type="file" id="fileInput" class="form-control form-control-sm">
                    <button class="btn btn-li-outline btn-sm" onclick="submitFile()">Upload</button>
                </div>
                <div id="filesList" class="mb-3"></div>

                <h6 class="mb-2">Timeline</h6>
                <div id="timelineList" style="max-height:300px; overflow-y:auto;"></div>
            </div>
        </div>
    </div>
</div>

<?= $this->endSection() ?>

<?= $this->section('scripts') ?>
<script>
function updateIcon(type) {
    const map = { note: 'bi-chat-left-text', status_change: 'bi-arrow-repeat', file_added: 'bi-paperclip', reminder_sent: 'bi-bell' };
    return map[type] || 'bi-dot';
}

function openTimeline(interviewId) {
    document.getElementById('tlInterviewId').value = interviewId;
    document.getElementById('noteInput').value = '';
    document.getElementById('fileInput').value = '';
    new bootstrap.Modal(document.getElementById('timelineModal')).show();
    loadTimeline(interviewId);
}

async function loadTimeline(interviewId) {
    try {
        const res = await apiFetch(`/interviews/${interviewId}/timeline`);
        const { timeline, files } = res.data;

        document.getElementById('filesList').innerHTML = files.length === 0
            ? '<p class="text-muted small mb-0">No files attached yet.</p>'
            : files.map(f => `
                <div class="d-flex justify-content-between align-items-center border-bottom py-1">
                    <span class="small"><i class="bi bi-file-earmark me-1"></i>${escapeHtml(f.original_filename)}</span>
                    <a href="${API_BASE}/interview-files/${f.id}/download" target="_blank" class="btn btn-li-ghost btn-sm"><i class="bi bi-download"></i></a>
                </div>
            `).join('');

        document.getElementById('timelineList').innerHTML = timeline.length === 0
            ? '<p class="text-muted small mb-0">No activity yet.</p>'
            : timeline.map(t => `
                <div class="border-bottom py-2">
                    <div class="small"><i class="bi ${updateIcon(t.update_type)} me-1"></i>${escapeHtml(t.content)}</div>
                    <div class="text-muted" style="font-size:11px;">${t.posted_by_name ? escapeHtml(t.posted_by_name) + ' · ' : ''}${formatDateTime(t.created_at)}</div>
                </div>
            `).join('');
    } catch (e) { showToast(e.message, true); }
}

async function submitNote() {
    const interviewId = document.getElementById('tlInterviewId').value;
    const content = document.getElementById('noteInput').value.trim();
    if (!content) return;
    try {
        await apiFetch(`/interviews/${interviewId}/notes`, { method: 'POST', body: JSON.stringify({ content }) });
        document.getElementById('noteInput').value = '';
        loadTimeline(interviewId);
    } catch (e) { showToast(e.message, true); }
}

async function submitFile() {
    const interviewId = document.getElementById('tlInterviewId').value;
    const fileInput = document.getElementById('fileInput');
    if (!fileInput.files.length) { showToast('Choose a file first.', true); return; }

    const fd = new FormData();
    fd.append('file', fileInput.files[0]);
    try {
        const res = await fetch(`${API_BASE}/interviews/${interviewId}/files`, { method: 'POST', body: fd, credentials: 'include' });
        const json = await res.json();
        if (!json.success) throw new Error(json.errors?.[0]?.message || 'Upload failed.');
        showToast('File attached.');
        fileInput.value = '';
        loadTimeline(interviewId);
    } catch (e) { showToast(e.message, true); }
}
function statusPill(s) {
    const map = { scheduled: 'blue', rescheduled: 'yellow', cancelled: 'red', completed: 'green' };
    return `<span class="li-pill li-pill-${map[s] || 'gray'}">${s}</span>`;
}

async function loadInterviews() {
    try {
        const res = await apiFetch('/interviews/agency-upcoming');
        const list = res.data.interviews || [];
        const el = document.getElementById('interviewsList');
        const empty = document.getElementById('interviewsEmpty');

        if (list.length === 0) { el.innerHTML = ''; empty.classList.remove('d-none'); return; }
        empty.classList.add('d-none');

        el.innerHTML = list.map(i => `
            <div class="li-card mb-2">
                <div class="li-card-body d-flex justify-content-between align-items-center">
                    <div>
                        <span class="fw-bold">${escapeHtml(i.candidate_name)}</span> — ${escapeHtml(i.job_title)}
                        ${statusPill(i.status)}
                        <div class="text-muted small mt-1">${i.mode.replace('_',' ')} · ${formatDateTime(i.scheduled_at)}</div>
                    </div>
                    <div class="d-flex gap-2">
                        ${i.meeting_link ? `<a href="${i.meeting_link}" target="_blank" class="btn btn-li-outline btn-sm">Join</a>` : ''}
                        <button class="btn btn-li-outline btn-sm" onclick="openTimeline(${i.id})"><i class="bi bi-clock-history me-1"></i>Details</button>
                        ${i.status !== 'completed' ? `<button class="btn btn-li-primary btn-sm" onclick="openFeedback(${i.id})">Feedback</button>` : ''}
                    </div>
                </div>
            </div>
        `).join('');
    } catch (e) { showToast(e.message, true); }
}

function openFeedback(id) {
    document.getElementById('fbInterviewId').value = id;
    document.getElementById('fbText').value = '';
    new bootstrap.Modal(document.getElementById('feedbackModal')).show();
}

async function submitFeedback() {
    const id = document.getElementById('fbInterviewId').value;
    try {
        await apiFetch(`/interviews/${id}/feedback`, {
            method: 'POST',
            body: JSON.stringify({ rating: parseInt(document.getElementById('fbRating').value), feedback: document.getElementById('fbText').value }),
        });
        bootstrap.Modal.getInstance(document.getElementById('feedbackModal')).hide();
        showToast('Feedback submitted.');
        loadInterviews();
    } catch (e) { showToast(e.message, true); }
}

loadInterviews();
</script>
<?= $this->endSection() ?>
