<!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: 20px; }
        .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; }
        .avatar-circle { border-radius: 12px; 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: 160px; background: linear-gradient(120deg, var(--li-blue), #38b6ff); border-radius: 8px 8px 0 0; }

        @media (max-width: 575.98px) {
            .cover-banner { height: 100px; }
            .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">
        <?php if ($agency->cover_image_path): ?>
            <div class="cover-banner" style="background: url('<?= esc(base_url($agency->cover_image_path)) ?>') center/cover;"></div>
        <?php else: ?>
            <div class="cover-banner"></div>
        <?php endif; ?>
        <div class="li-card-body pt-0">
            <div class="d-flex align-items-end" style="margin-top:-40px;">
                <?php if ($agency->logo_path): ?>
                    <img src="<?= esc(base_url($agency->logo_path)) ?>" class="border border-4 border-white rounded" 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($agency->company_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($agency->company_name) ?> <?= $agency->isVerified() ? '<i class="bi bi-patch-check-fill text-primary" title="Verified"></i>' : '' ?></h3>
                    <?php if ($agency->industry): ?><p class="text-muted mb-1"><?= esc($agency->industry) ?><?= $agency->company_size ? ' · ' . esc($agency->company_size) . ' employees' : '' ?></p><?php endif; ?>
                    <?php if ($avgRating !== null): ?>
                        <span class="li-pill li-pill-green"><i class="bi bi-star-fill"></i> <?= esc($avgRating) ?> (<?= count($reviews) ?> reviews)</span>
                    <?php endif; ?>
                </div>
                <div class="text-end">
                    <div class="text-muted small">Open positions</div>
                    <div class="fw-bold fs-5"><?= (int) $jobCount ?></div>
                </div>
            </div>

            <div class="mt-3 d-flex gap-2">
                <?php if ($viewerLoggedIn && $viewerId !== $user->id): ?>
                    <div id="connectButtonWrap"></div>
                <?php endif; ?>
                <?php if ($agency->website): ?><a href="<?= esc($agency->website) ?>" target="_blank" rel="noopener" class="btn btn-li-outline btn-sm"><i class="bi bi-globe me-1"></i>Website</a><?php endif; ?>
                <button class="btn btn-li-primary btn-sm" onclick="revealContact('email')"><i class="bi bi-envelope me-1"></i>Contact</button>
            </div>
            <div id="contactResult" class="mt-2"></div>

            <?php if (! empty($socialLinks)): ?>
                <div class="mt-2">
                    <?php foreach ($socialLinks as $platform => $url): ?>
                        <?php if ($url): ?><a href="<?= esc($url) ?>" target="_blank" rel="noopener" class="me-2 text-muted"><i class="bi bi-<?= esc($platform) ?>"></i></a><?php endif; ?>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>
    </div>

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

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

    <?php if (! empty($activeJobs)): ?>
    <div class="li-card mb-3">
        <div class="li-card-body">
            <h6 class="fw-bold">Open Positions (<?= (int) $jobCount ?>)</h6>
            <?php foreach ($activeJobs as $job): ?>
                <div class="border-bottom py-2">
                    <a href="<?= base_url('jobs/' . $job['seo_slug']) ?>" class="fw-semibold text-decoration-none"><?= esc($job['title']) ?></a>
                    <div class="text-muted small"><?= esc($job['location'] ?? 'Remote') ?> · <?= esc(str_replace('_', ' ', $job['employment_type'])) ?></div>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>

    <?php if (! empty($reviews)): ?>
    <div class="li-card mb-4">
        <div class="li-card-body">
            <h6 class="fw-bold">Reviews</h6>
            <?php foreach ($reviews as $review): ?>
                <div class="border-bottom py-2">
                    <div class="fw-semibold"><?= str_repeat('★', (int) $review['rating']) . str_repeat('☆', 5 - (int) $review['rating']) ?> <?= $review['title'] ? esc($review['title']) : '' ?></div>
                    <?php if ($review['review_text']): ?><p class="small mt-1 mb-0"><?= esc($review['review_text']) ?></p><?php endif; ?>
                </div>
            <?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> 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 (json.data.email) {
            window.location.href = `mailto:${json.data.email}`;
            resultEl.innerHTML = '<span class="text-success small">Opening your email client...</span>';
        } else {
            resultEl.innerHTML = '<span class="text-muted small">No contact email available.</span>';
        }
    } catch (e) {
        resultEl.innerHTML = '<div class="alert alert-danger py-2 small">Network error. Please try again.</div>';
    }
}
</script>
</body>
</html>
