<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title><?= esc($title) ?></title>
    <meta name="description" content="<?= esc($metaDescription) ?>">
    <meta property="og:title" content="<?= esc($title) ?>">
    <meta property="og:description" content="<?= esc($metaDescription) ?>">
    <meta property="og:type" content="website">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css">
    <script type="application/ld+json"><?= $jsonLd ?></script>
    <style>
        :root { --li-blue: #0a66c2; --li-blue-dark: #004182; --li-blue-light: #e8f0fe; --li-bg: #f4f2ee; --li-text-muted: #56687a; --li-border: #e0dfdc; }
        body { background: var(--li-bg); font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; }
        .li-card { background: #fff; border: 1px solid var(--li-border); border-radius: 8px; }
        .li-card-body { padding: 24px; }
        .li-pill { display: inline-block; padding: 2px 10px; border-radius: 12px; font-size: 12px; font-weight: 600; }
        .li-pill-blue { background: var(--li-blue-light); color: var(--li-blue); }
        .li-pill-green { background: #e9f7ef; color: #057642; }
        .li-pill-red { background: #fbeae5; color: #b74700; }
        .li-pill-gray { background: #eef3f8; color: var(--li-text-muted); }
        .job-logo { width: 72px; height: 72px; border-radius: 10px; background: var(--li-blue); color: #fff; display: flex; align-items: center; justify-content: center; font-weight: 800; font-size: 28px; flex-shrink: 0; }
        .btn-li-primary { background: var(--li-blue); border-color: var(--li-blue); color: #fff; border-radius: 24px; font-weight: 600; padding: 10px 28px; }
        .btn-li-primary:hover { background: var(--li-blue-dark); color: #fff; }
        .btn-li-outline { background: #fff; border: 1.5px solid var(--li-blue); color: var(--li-blue); border-radius: 24px; font-weight: 600; padding: 9px 24px; }
        .skill-tag { background: #eef3f8; color: var(--li-text-muted); font-size: 13px; padding: 4px 12px; border-radius: 12px; display: inline-block; margin: 2px 4px 2px 0; }
        .navbar-brand { color: var(--li-blue) !important; font-weight: 800; font-size: 22px; }

        @media (max-width: 575.98px) {
            .job-logo { width: 56px; height: 56px; font-size: 22px; }
            .d-flex.justify-content-between:not(.flex-nowrap) { flex-wrap: wrap; gap: 8px; }
            h3 { font-size: 1.3rem; }
            .container { padding-left: 14px; padding-right: 14px; }
        }
    </style>
</head>
<body>

<nav class="navbar bg-white border-bottom mb-4">
    <div class="container">
        <a class="navbar-brand" href="<?= base_url() ?>">Job Portal</a>
        <div>
            <?php if ($viewerLoggedIn): ?>
                <a href="<?= base_url('admin') ?>" class="btn btn-li-outline btn-sm">Dashboard</a>
            <?php else: ?>
                <a href="<?= base_url('login') ?>" class="btn btn-li-outline btn-sm me-2">Log In</a>
                <a href="<?= base_url('register') ?>" class="btn btn-li-primary btn-sm">Sign Up</a>
            <?php endif; ?>
        </div>
    </div>
</nav>

<div class="container" style="max-width: 900px;">
    <div class="li-card mb-3">
        <div class="li-card-body">
            <div class="d-flex gap-3">
                <?php if ($job->logo_path): ?>
                    <img src="<?= esc(base_url($job->logo_path)) ?>" class="job-logo" style="object-fit:cover;">
                <?php else: ?>
                    <div class="job-logo"><?= esc(strtoupper(substr($job->company_name ?? 'J', 0, 1))) ?></div>
                <?php endif; ?>
                <div class="flex-grow-1">
                    <h3 class="mb-1"><?= esc($job->title) ?></h3>
                    <div class="mb-2">
                        <?php if ($job->agency_username): ?>
                            <a href="<?= base_url('profile/' . $job->agency_username) ?>" class="text-decoration-none fw-semibold"><?= esc($job->company_name) ?></a>
                        <?php else: ?>
                            <span class="fw-semibold"><?= esc($job->company_name) ?></span>
                        <?php endif; ?>
                        <?php if ($job->verification_status === 'verified'): ?><i class="bi bi-patch-check-fill text-primary" title="Verified"></i><?php endif; ?>
                    </div>
                    <div class="text-muted small d-flex gap-3 flex-wrap mb-2">
                        <span><i class="bi bi-geo-alt"></i> <?= esc($job->location ?: ($job->city ?: 'Remote')) ?></span>
                        <span><i class="bi bi-briefcase"></i> <?= esc(str_replace('_', ' ', $job->employment_type)) ?></span>
                        <span><i class="bi bi-bar-chart"></i> <?= esc($job->experience_level) ?> level</span>
                        <span><i class="bi bi-people"></i> <?= (int) $job->applicant_count ?> applicant<?= $job->applicant_count == 1 ? '' : 's' ?></span>
                        <?php if ($job->salary_min || $job->salary_max): ?>
                            <span><i class="bi bi-cash"></i> <?= esc($job->salary_currency) ?> <?= number_format((float) $job->salary_min) ?><?= $job->salary_max ? ' - ' . number_format((float) $job->salary_max) : '' ?></span>
                        <?php endif; ?>
                    </div>
                    <div class="mb-2">
                        <?php if ($job->is_featured): ?><span class="li-pill li-pill-blue"><i class="bi bi-star-fill"></i> Featured</span><?php endif; ?>
                        <?php if ($job->is_urgent): ?><span class="li-pill li-pill-red"><i class="bi bi-fire"></i> Urgent Hiring</span><?php endif; ?>
                        <?php if ($job->is_remote): ?><span class="li-pill li-pill-gray"><i class="bi bi-wifi"></i> Remote</span><?php endif; ?>
                        <?php if ($job->is_hybrid): ?><span class="li-pill li-pill-gray">Hybrid</span><?php endif; ?>
                        <?php if ($job->is_visa_sponsorship): ?><span class="li-pill li-pill-green">Visa Sponsorship</span><?php endif; ?>
                        <?php if ($job->is_fresh_graduate_ok): ?><span class="li-pill li-pill-blue">Fresh Graduate Friendly</span><?php endif; ?>
                    </div>
                </div>
            </div>

            <hr>

            <div class="d-flex justify-content-between align-items-center">
                <div class="text-muted small"><i class="bi bi-eye"></i> <?= (int) $job->views_count ?> views</div>
                <div>
                    <?php if (! $viewerLoggedIn): ?>
                        <a href="<?= base_url('login') ?>?redirect=<?= urlencode(current_url()) ?>" class="btn btn-li-primary"><i class="bi bi-lightning-fill me-1"></i>Log In to Apply</a>
                    <?php elseif ($viewerIsCandidate && $alreadyApplied): ?>
                        <button class="btn btn-li-outline" disabled><i class="bi bi-check-circle me-1"></i>Already Applied</button>
                        <button class="btn btn-li-outline" onclick="openMessage()"><i class="bi bi-chat-dots me-1"></i>Message Recruiter</button>
                    <?php elseif ($viewerIsCandidate): ?>
                        <button class="btn btn-li-outline me-2" onclick="openMessage()"><i class="bi bi-chat-dots me-1"></i>Message Recruiter</button>
                        <button class="btn btn-li-primary" onclick="openApply()"><i class="bi bi-lightning-fill me-1"></i>Apply Now</button>
                    <?php else: ?>
                        <span class="text-muted small">Log in as a candidate to apply for this job.</span>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <div class="li-card mb-3">
        <div class="li-card-body">
            <h5 class="mb-3">Job Description</h5>
            <p style="white-space: pre-wrap;"><?= esc($job->description) ?></p>

            <?php if (! empty($skills)): ?>
                <h6 class="mt-4 mb-2">Required Skills</h6>
                <div><?php foreach ($skills as $skill): ?><span class="skill-tag"><?= esc($skill) ?></span><?php endforeach; ?></div>
            <?php endif; ?>

            <?php if ($job->education_requirement): ?>
                <h6 class="mt-4 mb-2">Education</h6>
                <p class="text-muted"><?= esc($job->education_requirement) ?></p>
            <?php endif; ?>

            <?php if ($job->benefits): ?>
                <h6 class="mt-4 mb-2">Benefits</h6>
                <p class="text-muted" style="white-space: pre-wrap;"><?= esc($job->benefits) ?></p>
            <?php endif; ?>
        </div>
    </div>

    <?php if ($job->agency_description): ?>
        <div class="li-card mb-3">
            <div class="li-card-body">
                <h6 class="mb-2">About <?= esc($job->company_name) ?></h6>
                <p class="text-muted"><?= esc(mb_substr($job->agency_description, 0, 300)) ?></p>
                <?php if ($job->agency_username): ?>
                    <a href="<?= base_url('profile/' . $job->agency_username) ?>" class="small">View company profile →</a>
                <?php endif; ?>
            </div>
        </div>
    <?php endif; ?>

    <?php if (! empty($similarJobs)): ?>
        <div class="li-card mb-4">
            <div class="li-card-body">
                <h6 class="mb-3">Similar Jobs</h6>
                <?php foreach ($similarJobs as $sj): ?>
                    <div class="border-bottom py-2">
                        <a href="<?= base_url('jobs/' . $sj->seo_slug) ?>" class="text-decoration-none fw-semibold"><?= esc($sj->title) ?></a>
                        <div class="text-muted small"><?= esc($sj->company_name) ?> · <?= esc($sj->location ?: 'Remote') ?></div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
    <?php endif; ?>
</div>

<?php if ($viewerIsCandidate && ! $alreadyApplied): ?>
<div class="modal fade" id="applyModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h6 class="modal-title">Apply for <?= esc($job->title) ?></h6>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <label class="form-label">Cover Note (optional)</label>
                <textarea id="coverNote" class="form-control" rows="4" placeholder="Tell them why you're a great fit..."></textarea>
                <div id="applyError" class="text-danger small mt-2"></div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                <button class="btn btn-li-primary" onclick="submitApplication()">Submit Application</button>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<?php if ($viewerIsCandidate): ?>
<div class="modal fade" id="messageModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h6 class="modal-title">Message <?= esc($job->company_name) ?></h6>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <textarea id="msgBody" class="form-control" rows="4" placeholder="Ask about the role, working hours, next steps..."></textarea>
                <div id="msgError" class="text-danger small mt-2"></div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                <button class="btn btn-li-primary" onclick="sendMessage()">Send</button>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
function openApply() {
    new bootstrap.Modal(document.getElementById('applyModal')).show();
}

function openMessage() {
    new bootstrap.Modal(document.getElementById('messageModal')).show();
}

async function sendMessage() {
    const body = document.getElementById('msgBody').value.trim();
    const errorEl = document.getElementById('msgError');
    errorEl.textContent = '';
    if (!body) { errorEl.textContent = 'Write a message first.'; return; }

    const apiBase = "<?= rtrim(base_url('api/v1'), '/') ?>";
    try {
        const convoRes = await fetch(`${apiBase}/conversations`, {
            method: 'POST', credentials: 'include',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ recipient_user_id: <?= (int) $job->posted_by_user_id ?>, job_application_id: null }),
        });
        const convoJson = await convoRes.json();
        if (!convoJson.success) throw new Error(convoJson.errors?.[0]?.message || 'Could not start conversation.');

        const msgRes = await fetch(`${apiBase}/conversations/${convoJson.data.conversation.id}/messages`, {
            method: 'POST', credentials: 'include',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ body }),
        });
        const msgJson = await msgRes.json();
        if (!msgJson.success) throw new Error(msgJson.errors?.[0]?.message || 'Message failed to send.');

        bootstrap.Modal.getInstance(document.getElementById('messageModal')).hide();
        alert('Message sent! Check Messages in your dashboard for replies.');
    } catch (e) {
        errorEl.textContent = e.message;
    }
}

async function submitApplication() {
    const coverNote = document.getElementById('coverNote').value;
    const errorEl = document.getElementById('applyError');
    errorEl.textContent = '';
    try {
        const res = await fetch("<?= rtrim(base_url('api/v1'), '/') ?>/jobs/<?= (int) $job->id ?>/apply", {
            method: 'POST',
            credentials: 'include',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ cover_note: coverNote || null }),
        });
        const json = await res.json();
        if (!json.success) throw new Error(json.errors?.[0]?.message || 'Application failed.');
        bootstrap.Modal.getInstance(document.getElementById('applyModal')).hide();
        window.location.reload();
    } catch (e) {
        errorEl.textContent = e.message;
    }
}
</script>
</body>
</html>
