<!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="profile">
    <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: 20px; }
        .li-pill { display: inline-block; padding: 2px 10px; border-radius: 12px; font-size: 12px; font-weight: 600; }
        .li-pill-green { background: #e9f7ef; color: #057642; }
        .li-pill-blue { background: var(--li-blue-light); color: var(--li-blue); }
        .li-pill-gray { background: #eef3f8; color: var(--li-text-muted); }
        .avatar-circle { border-radius: 50%; background: var(--li-blue); color: #fff; display: inline-flex; align-items: center; justify-content: center; font-weight: 700; }
        .btn-li-primary { background: var(--li-blue); border-color: var(--li-blue); color: #fff; border-radius: 24px; font-weight: 600; }
        .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; }
        .cover-banner { height: 120px; background: linear-gradient(120deg, var(--li-blue), #38b6ff); border-radius: 8px 8px 0 0; }

        @media (max-width: 575.98px) {
            .cover-banner { height: 90px; }
            .avatar-circle { width: 64px !important; height: 64px !important; font-size: 24px !important; }
            .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 navbar-light bg-white shadow-sm mb-4">
    <div class="container">
        <a class="navbar-brand fw-bold text-primary" href="<?= base_url() ?>">Job Portal</a>
        <?php if (! $viewerLoggedIn): ?>
            <div><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></div>
        <?php endif; ?>
    </div>
</nav>

<div class="container" style="max-width: 900px;">

    <div class="li-card mb-3 overflow-hidden">
        <div class="cover-banner"></div>
        <div class="li-card-body pt-0">
            <div class="d-flex align-items-end" style="margin-top:-40px;">
                <?php if ($user->profile_photo_path): ?>
                    <img src="<?= esc(base_url($user->profile_photo_path)) ?>" class="border border-4 border-white rounded-circle" style="width:88px;height:88px;object-fit:cover;">
                <?php else: ?>
                    <span class="avatar-circle border border-4 border-white" style="width:88px;height:88px;font-size:32px;"><?= esc(strtoupper(substr($user->name, 0, 1))) ?></span>
                <?php endif; ?>
            </div>
            <div class="d-flex justify-content-between align-items-start mt-2">
                <div>
                    <h3 class="mb-0"><?= esc($user->name) ?> <?= $profile->is_verified ? '<i class="bi bi-patch-check-fill text-primary" title="Verified"></i>' : '' ?></h3>
                    <?php if ($profile->headline): ?><p class="text-muted mb-1"><?= esc($profile->headline) ?></p><?php endif; ?>
                    <span class="li-pill li-pill-<?= $profile->availability_status === 'not_looking' ? 'gray' : 'green' ?>"><?= esc(str_replace('_', ' ', $profile->availability_status)) ?></span>
                </div>
                <div class="text-end">
                    <div class="text-muted small">Profile strength</div>
                    <div class="fw-bold fs-5"><?= (int) $profile->profile_completion_pct ?>%</div>
                </div>
            </div>

            <div class="mt-3 d-flex gap-2">
                <?php if ($viewerLoggedIn && $viewerId !== $user->id): ?>
                    <div id="connectButtonWrap"></div>
                <?php endif; ?>
                <button class="btn btn-li-primary btn-sm" onclick="revealContact('email')"><i class="bi bi-envelope me-1"></i>Contact via Email</button>
                <button class="btn btn-li-outline btn-sm" onclick="revealContact('phone')"><i class="bi bi-telephone me-1"></i>Reveal Phone</button>
            </div>
            <div id="contactResult" class="mt-2"></div>
        </div>
    </div>

    <?php if ($profile->about): ?>
    <div class="li-card mb-3">
        <div class="li-card-body">
            <h6 class="fw-bold">About</h6>
            <p style="white-space:pre-wrap;"><?= esc($profile->about) ?></p>
        </div>
    </div>
    <?php endif; ?>

    <?php if (! empty($skills)): ?>
    <div class="li-card mb-3">
        <div class="li-card-body">
            <h6 class="fw-bold">Skills</h6>
            <?php foreach ($skills as $skill): ?>
                <span class="li-pill li-pill-blue me-1 mb-1 d-inline-block"><?= esc($skill['name']) ?></span>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>

    <?php if (! empty($experiences)): ?>
    <div class="li-card mb-3">
        <div class="li-card-body">
            <h6 class="fw-bold">Experience</h6>
            <?php foreach ($experiences as $exp): ?>
                <div class="border-bottom py-2">
                    <div class="fw-semibold"><?= esc($exp['job_title']) ?></div>
                    <div class="text-muted small"><?= esc($exp['company_name']) ?> · <?= esc($exp['start_date']) ?> — <?= esc($exp['end_date'] ?? 'Present') ?></div>
                    <?php if (! empty($exp['description'])): ?><p class="small mt-1 mb-0"><?= esc($exp['description']) ?></p><?php endif; ?>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>

    <?php if (! empty($education)): ?>
    <div class="li-card mb-3">
        <div class="li-card-body">
            <h6 class="fw-bold">Education</h6>
            <?php foreach ($education as $edu): ?>
                <div class="border-bottom py-2">
                    <div class="fw-semibold"><?= esc($edu['institution']) ?></div>
                    <div class="text-muted small"><?= esc($edu['degree']) ?><?= $edu['field_of_study'] ? ' · ' . esc($edu['field_of_study']) : '' ?></div>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>

    <?php if (! empty($certifications)): ?>
    <div class="li-card mb-3">
        <div class="li-card-body">
            <h6 class="fw-bold">Certifications</h6>
            <?php foreach ($certifications as $cert): ?>
                <div class="border-bottom py-2">
                    <div class="fw-semibold"><?= esc($cert['title']) ?></div>
                    <?php if ($cert['issuing_org']): ?><div class="text-muted small"><?= esc($cert['issuing_org']) ?></div><?php endif; ?>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>

    <?php if (! empty($projects)): ?>
    <div class="li-card mb-3">
        <div class="li-card-body">
            <h6 class="fw-bold">Portfolio Projects</h6>
            <?php foreach ($projects as $proj): ?>
                <div class="border-bottom py-2">
                    <div class="fw-semibold"><?= esc($proj['title']) ?><?= $proj['project_url'] ? ' <a href="' . esc($proj['project_url']) . '" target="_blank" rel="noopener"><i class="bi bi-box-arrow-up-right small"></i></a>' : '' ?></div>
                    <?php if ($proj['description']): ?><p class="small mt-1 mb-0"><?= esc($proj['description']) ?></p><?php endif; ?>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>

    <?php if (! empty($languages)): ?>
    <div class="li-card mb-3">
        <div class="li-card-body">
            <h6 class="fw-bold">Languages</h6>
            <?php foreach ($languages as $lang): ?>
                <span class="li-pill li-pill-gray me-1 mb-1 d-inline-block"><?= esc($lang['language']) ?> (<?= esc($lang['proficiency']) ?>)</span>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>

    <?php if (! empty($portfolio)): ?>
    <div class="li-card mb-4">
        <div class="li-card-body">
            <h6 class="fw-bold">Links</h6>
            <?php foreach ($portfolio as $link): ?>
                <a href="<?= esc($link['url']) ?>" target="_blank" rel="noopener" class="d-block small"><i class="bi bi-link-45deg"></i> <?= esc($link['label'] ?: $link['url']) ?></a>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>

</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
const apiBase = "<?= rtrim(base_url('api/v1'), '/') ?>";

<?php if ($viewerLoggedIn && $viewerId !== $user->id): ?>
async function loadConnectState() {
    try {
        const res = await fetch(`${apiBase}/connections/status/<?= (int) $user->id ?>`, { credentials: 'include' });
        const json = await res.json();
        renderConnectButton(json.data);
    } catch (e) { /* non-fatal */ }
}

function renderConnectButton(state) {
    const wrap = document.getElementById('connectButtonWrap');
    if (!wrap) return;
    if (state.status === 'accepted') {
        wrap.innerHTML = `<button class="btn btn-li-outline btn-sm" disabled><i class="bi bi-check-circle me-1"></i>Connected</button>`;
    } else if (state.status === 'pending' && state.is_requester) {
        wrap.innerHTML = `<button class="btn btn-li-outline btn-sm" disabled><i class="bi bi-hourglass-split me-1"></i>Pending</button>`;
    } else if (state.status === 'pending' && !state.is_requester) {
        wrap.innerHTML = `<button class="btn btn-li-primary btn-sm" onclick="acceptConnect(${state.connection_id})"><i class="bi bi-check-lg me-1"></i>Accept Request</button>`;
    } else {
        wrap.innerHTML = `<button class="btn btn-li-outline btn-sm" onclick="sendConnect()"><i class="bi bi-person-plus me-1"></i>Connect</button>`;
    }
}

async function sendConnect() {
    try {
        const res = await fetch(`${apiBase}/connections`, {
            method: 'POST', credentials: 'include',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ recipient_user_id: <?= (int) $user->id ?> }),
        });
        const json = await res.json();
        if (!json.success) throw new Error(json.errors?.[0]?.message || 'Could not send request.');
        loadConnectState();
    } catch (e) { alert(e.message); }
}

async function acceptConnect(connectionId) {
    try {
        await fetch(`${apiBase}/connections/${connectionId}/accept`, { method: 'POST', credentials: 'include' });
        loadConnectState();
    } catch (e) { alert('Could not accept request.'); }
}

loadConnectState();
<?php endif; ?>

async function revealContact(type) {
    const resultEl = document.getElementById('contactResult');
    resultEl.innerHTML = '<span class="text-muted small">Loading...</span>';

    try {
        const res = await fetch(`<?= base_url('profile/' . esc($user->username, 'attr') . '/reveal-contact') ?>`, {
            method: 'POST', credentials: 'include', headers: {'Content-Type': 'application/json'},
        });
        const json = await res.json();

        if (!json.success) {
            const err = json.errors?.[0];
            if (err?.code === 'LOGIN_REQUIRED') {
                resultEl.innerHTML = `<div class="alert alert-warning py-2 small">Please <a href="<?= base_url('login') ?>">log in</a> as a Candidate or Agency to view contact details.</div>`;
            } else if (err?.code === 'DAILY_LIMIT_REACHED') {
                resultEl.innerHTML = `<div class="alert alert-danger py-2 small">${err.message}</div>`;
            } else {
                resultEl.innerHTML = `<div class="alert alert-danger py-2 small">${err?.message || 'Something went wrong.'}</div>`;
            }
            return;
        }

        if (type === 'email' && json.data.email) {
            window.location.href = `mailto:${json.data.email}`;
            resultEl.innerHTML = '<span class="text-success small">Opening your email client...</span>';
        } else if (type === 'phone' && json.data.phone) {
            window.location.href = `tel:${json.data.phone}`;
            resultEl.innerHTML = '<span class="text-success small">Opening your phone dialer...</span>';
        } else {
            resultEl.innerHTML = '<span class="text-muted small">This candidate has not shared that contact method.</span>';
        }
    } catch (e) {
        resultEl.innerHTML = '<div class="alert alert-danger py-2 small">Network error. Please try again.</div>';
    }
}
</script>
</body>
</html>
