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

<?= $this->section('content') ?>

<div class="li-card mb-3">
    <div class="li-card-body">
        <h6 class="mb-2">Public Profile URL</h6>
        <div class="d-flex align-items-center gap-2 mb-2">
            <span class="text-muted small"><?= rtrim(base_url(), '/') ?>/profile/</span>
            <input type="text" id="usernameInput" class="form-control form-control-sm" style="max-width:220px;">
            <button class="btn btn-li-outline btn-sm" onclick="saveUsername()">Update</button>
            <a id="viewProfileLink" href="#" target="_blank" class="btn btn-li-primary btn-sm">View Public Profile</a>
        </div>
        <div id="usernameStatus" class="small text-muted"></div>
    </div>
</div>

<div class="li-card mb-3">
    <div class="li-card-body d-flex align-items-center gap-3">
        <img id="profilePhotoPreview" src="<?= esc($photoUrl ?? '') ?>" class="rounded-circle <?= $photoUrl ? '' : 'd-none' ?>" style="width:80px;height:80px;object-fit:cover;">
        <span id="profilePhotoInitial" class="avatar-circle lg <?= $photoUrl ? 'd-none' : '' ?>"><?= esc(strtoupper(substr($userName, 0, 1))) ?></span>
        <div>
            <h6 class="mb-1">Profile Photo</h6>
            <input type="file" id="photoFile" accept=".jpg,.jpeg,.png,.webp" class="form-control form-control-sm mb-2" style="max-width:280px;">
            <button class="btn btn-li-primary btn-sm" onclick="uploadPhoto()">Upload</button>
            <button class="btn btn-li-ghost btn-sm" id="removePhotoBtn" onclick="removePhoto()" style="display:none;">Remove</button>
        </div>
    </div>
</div>

<div class="li-card mb-3">
    <div class="li-card-body">
        <div class="d-flex justify-content-between align-items-center mb-2">
            <h6 class="mb-0">Profile Completion</h6>
            <span id="completionPct" class="fw-bold">0%</span>
        </div>
        <div class="progress" style="height:8px;"><div id="completionBar" class="progress-bar bg-success" style="width:0%"></div></div>
    </div>
</div>

<div class="li-card mb-3">
    <div class="li-card-header">Basics</div>
    <div class="li-card-body">
        <form id="basicsForm">
            <div class="row g-3">
                <div class="col-12">
                    <label class="form-label">Headline</label>
                    <input type="text" class="form-control" name="headline" placeholder="e.g. Senior PHP Developer | Laravel · Vue.js">
                </div>
                <div class="col-12">
                    <label class="form-label">Cover Letter / Summary</label>
                    <textarea class="form-control" name="cover_letter" rows="4"></textarea>
                </div>
                <div class="col-md-4">
                    <label class="form-label">Availability</label>
                    <select class="form-select" name="availability_status">
                        <option value="not_looking">Not looking</option>
                        <option value="open_to_work">Open to work</option>
                        <option value="actively_looking">Actively looking</option>
                        <option value="available_immediately">Available immediately</option>
                    </select>
                </div>
                <div class="col-md-4">
                    <label class="form-label">Min Salary (PKR)</label>
                    <input type="number" class="form-control" name="salary_expectation_min">
                </div>
                <div class="col-md-4">
                    <label class="form-label">Max Salary (PKR)</label>
                    <input type="number" class="form-control" name="salary_expectation_max">
                </div>
                <div class="col-12 d-flex gap-4">
                    <div class="form-check"><input class="form-check-input" type="checkbox" name="hide_email" id="hideEmail"><label class="form-check-label" for="hideEmail">Hide email from recruiters until unlocked</label></div>
                </div>
                <div class="col-12 d-flex gap-4">
                    <div class="form-check"><input class="form-check-input" type="checkbox" name="hide_mobile" id="hideMobile"><label class="form-check-label" for="hideMobile">Hide phone until unlocked</label></div>
                </div>
            </div>
            <button type="button" class="btn btn-li-primary mt-3" onclick="saveBasics()">Save</button>
        </form>
    </div>
</div>

<div class="row g-3">
    <div class="col-md-6">
        <div class="li-card mb-3">
            <div class="li-card-header d-flex justify-content-between">Experience <button class="btn btn-li-outline btn-sm" data-bs-toggle="modal" data-bs-target="#expModal">+ Add</button></div>
            <div class="li-card-body" id="expList"><p class="text-muted small">No experience added yet.</p></div>
        </div>

        <div class="li-card mb-3">
            <div class="li-card-header d-flex justify-content-between">Education <button class="btn btn-li-outline btn-sm" data-bs-toggle="modal" data-bs-target="#eduModal">+ Add</button></div>
            <div class="li-card-body" id="eduList"><p class="text-muted small">No education added yet.</p></div>
        </div>
    </div>

    <div class="col-md-6">
        <div class="li-card mb-3">
            <div class="li-card-header">Skills</div>
            <div class="li-card-body">
                <div class="d-flex gap-2 mb-2">
                    <input type="text" id="skillInput" class="form-control form-control-sm" placeholder="e.g. PHP">
                    <button class="btn btn-li-outline btn-sm" onclick="addSkill()">Add</button>
                </div>
                <div id="skillsList"></div>
            </div>
        </div>

        <div class="li-card mb-3">
            <div class="li-card-header">Resume</div>
            <div class="li-card-body">
                <input type="file" id="resumeFile" class="form-control form-control-sm mb-2" accept=".pdf,.doc,.docx">
                <button class="btn btn-li-primary btn-sm" onclick="uploadResume()">Upload</button>
                <div id="resumeList" class="mt-2"></div>
            </div>
        </div>
    </div>
</div>

<!-- Experience Modal -->
<div class="modal fade" id="expModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header"><h6 class="modal-title">Add Experience</h6><button class="btn-close" data-bs-dismiss="modal"></button></div>
            <div class="modal-body">
                <div class="mb-2"><label class="form-label">Job Title</label><input type="text" id="expTitle" class="form-control"></div>
                <div class="mb-2"><label class="form-label">Company</label><input type="text" id="expCompany" class="form-control"></div>
                <div class="row">
                    <div class="col-6"><label class="form-label">Start Date</label><input type="date" id="expStart" class="form-control"></div>
                    <div class="col-6"><label class="form-label">End Date</label><input type="date" id="expEnd" class="form-control"></div>
                </div>
                <div class="mt-2"><label class="form-label">Description</label><textarea id="expDesc" class="form-control" rows="2"></textarea></div>
            </div>
            <div class="modal-footer"><button class="btn btn-li-primary" onclick="addExperience()">Add</button></div>
        </div>
    </div>
</div>

<!-- Education Modal -->
<div class="modal fade" id="eduModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header"><h6 class="modal-title">Add Education</h6><button class="btn-close" data-bs-dismiss="modal"></button></div>
            <div class="modal-body">
                <div class="mb-2"><label class="form-label">Institution</label><input type="text" id="eduInstitution" class="form-control"></div>
                <div class="mb-2"><label class="form-label">Degree</label><input type="text" id="eduDegree" class="form-control"></div>
                <div class="mb-2"><label class="form-label">Field of Study</label><input type="text" id="eduField" class="form-control"></div>
            </div>
            <div class="modal-footer"><button class="btn btn-li-primary" onclick="addEducation()">Add</button></div>
        </div>
    </div>
</div>

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

<?= $this->section('scripts') ?>
<script>
let fullProfile = null;
<?php if ($photoUrl): ?>document.getElementById('removePhotoBtn').style.display = 'inline-block';<?php endif; ?>

async function uploadPhoto() {
    const fileInput = document.getElementById('photoFile');
    if (!fileInput.files.length) { showToast('Choose a photo first.', true); return; }
    const fd = new FormData();
    fd.append('photo', fileInput.files[0]);
    try {
        const res = await fetch(`${API_BASE}/account/photo`, { method: 'POST', body: fd, credentials: 'include' });
        const json = await res.json();
        if (!json.success) throw new Error(json.errors?.[0]?.message || 'Upload failed.');
        showToast('Profile photo updated.');
        renderPhoto(json.data.photo_url);
    } catch (e) { showToast(e.message, true); }
}

async function removePhoto() {
    try {
        await apiFetch('/account/photo', { method: 'DELETE' });
        showToast('Profile photo removed.');
        renderPhoto(null);
    } catch (e) { showToast(e.message, true); }
}

function renderPhoto(url) {
    const img = document.getElementById('profilePhotoPreview');
    const initial = document.getElementById('profilePhotoInitial');
    const removeBtn = document.getElementById('removePhotoBtn');
    if (url) {
        img.src = url + '?t=' + Date.now();
        img.classList.remove('d-none');
        initial.classList.add('d-none');
        removeBtn.style.display = 'inline-block';
    } else {
        img.classList.add('d-none');
        initial.classList.remove('d-none');
        removeBtn.style.display = 'none';
    }
}

async function loadUsername() {
    try {
        const res = await apiFetch('/account/username/status');
        document.getElementById('usernameInput').value = res.data.current_username || '';
        document.getElementById('viewProfileLink').href = "<?= rtrim(base_url(), '/') ?>/profile/" + (res.data.current_username || '');
        const lim = res.data.change_limit;
        document.getElementById('usernameStatus').textContent = `${lim.remaining} of ${lim.limit} change(s) remaining in the next ${lim.period_days} days.`;
    } catch (e) { /* non-fatal */ }
}

async function saveUsername() {
    const username = document.getElementById('usernameInput').value.trim();
    if (!username) { showToast('Enter a username.', true); return; }
    try {
        await apiFetch('/account/username', { method: 'PUT', body: JSON.stringify({ username }) });
        showToast('Username updated.');
        loadUsername();
    } catch (e) { showToast(e.message, true); }
}

loadUsername();

async function loadProfile() {
    try {
        const res = await apiFetch('/candidates/me');
        fullProfile = res.data;
        const p = fullProfile.profile;

        document.getElementById('completionPct').textContent = (p.profile_completion_pct || 0) + '%';
        document.getElementById('completionBar').style.width = (p.profile_completion_pct || 0) + '%';

        const form = document.getElementById('basicsForm');
        form.headline.value = p.headline || '';
        form.cover_letter.value = p.cover_letter || '';
        form.availability_status.value = p.availability_status || 'not_looking';
        form.salary_expectation_min.value = p.salary_expectation_min || '';
        form.salary_expectation_max.value = p.salary_expectation_max || '';
        form.hide_email.checked = !!p.hide_email;
        form.hide_mobile.checked = !!p.hide_mobile;

        renderExperiences();
        renderEducation();
        renderSkills();
        renderResumes();
    } catch (e) { showToast(e.message, true); }
}

async function saveBasics() {
    const form = document.getElementById('basicsForm');
    const fd = new FormData(form);
    try {
        await apiFetch('/candidates/me', {
            method: 'PUT',
            body: JSON.stringify({
                headline: fd.get('headline'),
                cover_letter: fd.get('cover_letter'),
                availability_status: fd.get('availability_status'),
                salary_expectation_min: fd.get('salary_expectation_min') || null,
                salary_expectation_max: fd.get('salary_expectation_max') || null,
                hide_email: form.hide_email.checked,
                hide_mobile: form.hide_mobile.checked,
            }),
        });
        showToast('Profile updated.');
        loadProfile();
    } catch (e) { showToast(e.message, true); }
}

function renderExperiences() {
    const list = fullProfile.experiences || [];
    document.getElementById('expList').innerHTML = list.length === 0 ? '<p class="text-muted small">No experience added yet.</p>' :
        list.map(e => `<div class="border-bottom py-2"><strong>${escapeHtml(e.job_title)}</strong><div class="small text-muted">${escapeHtml(e.company_name)} · ${e.start_date} — ${e.end_date || 'Present'}</div></div>`).join('');
}
function renderEducation() {
    const list = fullProfile.education || [];
    document.getElementById('eduList').innerHTML = list.length === 0 ? '<p class="text-muted small">No education added yet.</p>' :
        list.map(e => `<div class="border-bottom py-2"><strong>${escapeHtml(e.institution)}</strong><div class="small text-muted">${escapeHtml(e.degree)} ${e.field_of_study ? '· ' + escapeHtml(e.field_of_study) : ''}</div></div>`).join('');
}
function renderSkills() {
    const list = fullProfile.skills || [];
    document.getElementById('skillsList').innerHTML = list.map(s => `<span class="li-pill li-pill-blue me-1 mb-1 d-inline-block">${escapeHtml(s.name)} <a href="#" onclick="removeSkill(${s.id});return false;" class="text-danger ms-1">×</a></span>`).join('');
}
function renderResumes() {
    const list = fullProfile.resumes || [];
    document.getElementById('resumeList').innerHTML = list.map(r => `<div class="small"><i class="bi bi-file-earmark-pdf"></i> ${escapeHtml(r.original_filename)} ${r.is_primary ? '<span class="li-pill li-pill-green">Primary</span>' : ''}</div>`).join('');
}

async function addExperience() {
    try {
        await apiFetch('/candidates/me/experience', {
            method: 'POST',
            body: JSON.stringify({
                job_title: document.getElementById('expTitle').value,
                company_name: document.getElementById('expCompany').value,
                start_date: document.getElementById('expStart').value,
                end_date: document.getElementById('expEnd').value || null,
                description: document.getElementById('expDesc').value || null,
            }),
        });
        bootstrap.Modal.getInstance(document.getElementById('expModal')).hide();
        showToast('Experience added.');
        loadProfile();
    } catch (e) { showToast(e.message, true); }
}

async function addEducation() {
    try {
        await apiFetch('/candidates/me/education', {
            method: 'POST',
            body: JSON.stringify({
                institution: document.getElementById('eduInstitution').value,
                degree: document.getElementById('eduDegree').value,
                field_of_study: document.getElementById('eduField').value || null,
            }),
        });
        bootstrap.Modal.getInstance(document.getElementById('eduModal')).hide();
        showToast('Education added.');
        loadProfile();
    } catch (e) { showToast(e.message, true); }
}

async function addSkill() {
    const input = document.getElementById('skillInput');
    if (!input.value.trim()) return;
    try {
        await apiFetch('/candidates/me/skills', { method: 'POST', body: JSON.stringify({ name: input.value }) });
        input.value = '';
        loadProfile();
    } catch (e) { showToast(e.message, true); }
}
async function removeSkill(id) {
    try {
        await apiFetch(`/candidates/me/skills/${id}`, { method: 'DELETE' });
        loadProfile();
    } catch (e) { showToast(e.message, true); }
}

async function uploadResume() {
    const fileInput = document.getElementById('resumeFile');
    if (!fileInput.files.length) { showToast('Choose a file first.', true); return; }
    const fd = new FormData();
    fd.append('resume', fileInput.files[0]);
    fd.append('make_primary', '1');
    try {
        const res = await fetch(`${API_BASE}/candidates/me/resume`, { method: 'POST', body: fd, credentials: 'include' });
        const json = await res.json();
        if (!json.success) throw new Error(json.errors?.[0]?.message || 'Upload failed.');
        showToast('Resume uploaded.');
        loadProfile();
    } catch (e) { showToast(e.message, true); }
}

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