<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>EcoBot — <%= careerStrategy.leadName || slug %></title>
    <link href="https://fonts.googleapis.com/css2?family=Ubuntu:wght@300;400;500;700&display=swap" rel="stylesheet">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <link rel="stylesheet" href="/admin/css/style.css">
    <script>
        const CURRENT_PROFILE = <%- JSON.stringify(careerStrategy) %>;
        const ANTHROPIC_KEY = '<%= anthropicKey %>';
        const SLUG = '<%= slug %>';
        const BASE = '/admin';
    </script>
    <style>
        body { display: block; background: #f4f6f4; min-height: 100vh; }

        /* ── Header ── */
        .portal-header {
            background: white; box-shadow: 0 2px 8px rgba(0,0,0,0.08);
            padding: 0 30px; display: flex; align-items: center;
            justify-content: space-between; height: 60px;
            position: sticky; top: 0; z-index: 100;
        }
        .portal-header .logo-text { font-size: 20px; font-weight: 700; color: #28a745; }
        .header-actions { display: flex; align-items: center; gap: 8px; }
        .btn-header {
            display: inline-flex; align-items: center; gap: 5px;
            background: none; border: 1px solid #ddd; color: #555;
            padding: 6px 12px; border-radius: 5px; font-size: 13px;
            cursor: pointer; font-family: 'Ubuntu', sans-serif; text-decoration: none;
            transition: all 0.15s;
        }
        .btn-header:hover { border-color: #28a745; color: #28a745; }
        .btn-header.green { background: #28a745; color: white; border-color: #28a745; }
        .btn-header.green:hover { background: #218838; }
        .btn-logout-hdr {
            display: inline-flex; align-items: center; gap: 5px;
            background: #dc3545; color: white; border: none;
            padding: 6px 12px; border-radius: 5px; font-size: 13px;
            cursor: pointer; font-family: 'Ubuntu', sans-serif; text-decoration: none;
            transition: background 0.15s;
        }
        .btn-logout-hdr:hover { background: #c82333; }

        /* ── Banner ── */
        .welcome-banner {
            background: linear-gradient(135deg, #28a745, #20c997);
            padding: 28px 30px; display: flex; align-items: center;
            gap: 20px; color: white;
        }
        .welcome-avatar {
            width: 56px; height: 56px; border-radius: 50%;
            background: rgba(255,255,255,0.25);
            display: flex; align-items: center; justify-content: center;
            font-size: 22px; font-weight: 700; flex-shrink: 0;
        }
        .welcome-text h2 { font-size: 20px; margin: 0 0 4px; }
        .welcome-text p  { font-size: 13px; margin: 0; opacity: 0.85; }

        /* ── Tab bar ── */
        .portal-body { max-width: 960px; margin: 0 auto; padding: 0 20px 80px; }
        .tab-bar {
            background: white; display: flex; gap: 0;
            border-bottom: 2px solid #e8f5e9; margin-bottom: 24px;
            position: sticky; top: 60px; z-index: 90;
            box-shadow: 0 2px 6px rgba(0,0,0,0.05);
            overflow-x: auto; scrollbar-width: none; -ms-overflow-style: none;
        }
        .tab-bar::-webkit-scrollbar { display: none; }
        .tab-btn {
            padding: 14px 20px; font-size: 13px; font-weight: 600; color: #888;
            background: none; border: none; border-bottom: 3px solid transparent;
            margin-bottom: -2px; cursor: pointer; transition: all 0.15s;
            display: flex; align-items: center; gap: 6px;
            font-family: 'Ubuntu', sans-serif; white-space: nowrap;
        }
        .tab-btn:hover  { color: #28a745; background: #f9fdf9; }
        .tab-btn.active { background: #28a745 !important; color: white !important; border-bottom-color: #28a745; }
        .tab-pane { display: none; }
        .tab-pane.active { display: block; }

        /* ── Cards ── */
        .card {
            background: white; border-radius: 10px; padding: 24px 28px;
            margin-bottom: 20px; box-shadow: 0 1px 6px rgba(0,0,0,0.06);
        }
        .card-title {
            font-size: 15px; font-weight: 600; color: #28a745;
            margin: 0 0 18px; display: flex; align-items: center; gap: 8px;
            border-bottom: 1px solid #f0f0f0; padding-bottom: 12px;
        }

        /* ── Info grid ── */
        .info-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; }
        @media (max-width: 600px) { .info-grid { grid-template-columns: 1fr; } }
        .info-item label {
            font-size: 11px; font-weight: 600; color: #aaa;
            text-transform: uppercase; letter-spacing: 0.5px;
            display: block; margin-bottom: 3px;
        }
        .info-item p { font-size: 14px; color: #333; margin: 0; line-height: 1.5; }

        /* ── Tags ── */
        .tag-list { display: flex; flex-wrap: wrap; gap: 6px; }
        .tag {
            display: inline-flex; align-items: center; gap: 4px;
            background: #e8f5e9; color: #2e7d32;
            font-size: 12px; padding: 4px 10px; border-radius: 14px; font-weight: 500;
        }
        .tag-grey { background: #f5f5f5; color: #555; font-size: 12px; padding: 4px 11px; border-radius: 14px; font-weight: 500; }
        .tag-blue { background: #e3f2fd; color: #1565c0; font-size: 12px; padding: 4px 11px; border-radius: 14px; font-weight: 500; }

        /* ── Segment cards ── */
        .segment-card {
            border: 1px solid #e8f5e9; border-radius: 8px;
            padding: 18px 20px; margin-bottom: 14px;
        }
        .segment-card:last-child { margin-bottom: 0; }
        .segment-num {
            display: inline-block; width: 22px; height: 22px; border-radius: 50%;
            background: #28a745; color: white; font-size: 11px; font-weight: 700;
            text-align: center; line-height: 22px; margin-right: 8px;
        }
        .segment-label { font-size: 14px; font-weight: 600; color: #222; margin: 0 0 14px; }
        .segment-section { margin-bottom: 10px; }
        .segment-section-title {
            font-size: 10px; font-weight: 700; color: #bbb;
            text-transform: uppercase; letter-spacing: 0.8px; margin-bottom: 5px;
        }
        .segment-narrative { font-size: 13px; color: #444; line-height: 1.7; margin-top: 10px; padding-top: 10px; border-top: 1px solid #f5f5f5; }

        /* ── Dossier ── */
        .dossier-section-title { font-size: 11px; font-weight: 700; color: #aaa; text-transform: uppercase; letter-spacing: 1px; margin: 0 0 12px; padding-bottom: 6px; border-bottom: 1px solid #f0f0f0; }
        .exp-entry { margin-bottom: 16px; }
        .exp-entry:last-child { margin-bottom: 0; }
        .exp-title   { font-size: 14px; font-weight: 600; color: #222; margin: 0 0 2px; }
        .exp-company { font-size: 13px; color: #555; margin: 0 0 2px; }
        .exp-dates   { font-size: 12px; color: #aaa; margin: 0 0 6px; }
        .exp-highlights { padding-left: 16px; margin: 0; }
        .exp-highlights li { font-size: 13px; color: #444; line-height: 1.7; }
        .lang-row { display: flex; justify-content: space-between; align-items: center; padding: 8px 0; border-bottom: 1px solid #f5f5f5; font-size: 14px; }
        .lang-row:last-child { border-bottom: none; }

        /* ── Job tracking ── */
        .job-table { width: 100%; border-collapse: collapse; font-size: 13px; }
        .job-table th { text-align: left; font-size: 11px; font-weight: 600; color: #aaa; text-transform: uppercase; letter-spacing: 0.5px; padding: 0 12px 10px 0; border-bottom: 1px solid #eee; }
        .job-table td { padding: 10px 12px 10px 0; border-bottom: 1px solid #f5f5f5; color: #444; vertical-align: top; }
        .job-table tbody tr { cursor: pointer; transition: background 0.15s; }
        .job-table tbody tr:hover { background: #f9fdf9; }
        .jt-th { cursor:pointer; user-select:none; white-space:nowrap; }
        .jt-th:hover { color:#28a745 !important; }
        .jt-sort-icon { font-size:9px; color:#ccc; margin-left:2px; vertical-align:middle; }
        .job-status { display: inline-block; padding: 2px 8px; border-radius: 3px; font-size: 11px; font-weight: 600; white-space: nowrap; }
        /* declined */
        .status-dec-not-interested  { background: #fce4ec; color: #c62828; }
        .status-dec-doesnt-qualify  { background: #fce4ec; color: #ad1457; }
        .status-dec-applied-before  { background: #fff3e0; color: #e65100; }
        .status-dec-position-closed { background: #fce4ec; color: #b71c1c; }
        .status-dec-no-answer       { background: #f3e5f5; color: #6a1b9a; }
        /* in progress */
        .status-under-analysis  { background: #f5f5f5; color: #757575; }
        .status-approved        { background: #e8eaf6; color: #3949ab; }
        .status-in-preparation  { background: #e3f2fd; color: #1565c0; }
        .status-cv-in-drive     { background: #e0f2f1; color: #00695c; }
        .status-login-needed    { background: #fff8e1; color: #f57f17; }
        .status-applied         { background: #dbeafe; color: #1d4ed8; }
        .status-interview       { background: #fff7ed; color: #c2410c; }
        .status-offer-received  { background: #e8f5e9; color: #388e3c; }
        .status-offer-accepted  { background: #c8e6c9; color: #1b5e20; }
        /* legacy fallbacks */
        .status-proposed  { background: #f5f5f5; color: #757575; }
        .status-rejected  { background: #fce4ec; color: #c62828; }

        /* ── Job Modal ── */
        .jm-overlay { position:fixed; inset:0; background:rgba(0,0,0,0.45); z-index:1000; display:flex; align-items:flex-start; justify-content:center; padding:24px 16px; overflow-y:auto; opacity:0; transition:opacity 0.22s ease; }
        .jm-overlay.is-open { opacity:1; }
        .jm-panel { background:#fff; border-radius:10px; width:100%; max-width:560px; box-shadow:0 8px 40px rgba(0,0,0,0.18); display:flex; flex-direction:column; margin:auto; transform:translateY(20px) scale(0.98); opacity:0; transition:transform 0.28s cubic-bezier(0.34,1.4,0.64,1),opacity 0.22s ease; }
        .jm-overlay.is-open .jm-panel { transform:translateY(0) scale(1); opacity:1; }
        .jm-header { padding:20px 24px 16px; border-bottom:1px solid #eee; display:flex; justify-content:space-between; align-items:flex-start; gap:12px; }
        .jm-title { font-size:15px; font-weight:700; color:#222; line-height:1.4; }
        .jm-subtitle { font-size:12px; color:#888; margin-top:3px; }
        .jm-close { border:none; background:none; font-size:18px; color:#aaa; cursor:pointer; padding:0; line-height:1; flex-shrink:0; }
        .jm-close:hover { color:#333; }
        .jm-body { padding:20px 24px; display:flex; flex-direction:column; gap:16px; }
        .jm-row { display:grid; grid-template-columns:1fr 1fr; gap:12px; }
        .jm-field label { display:block; font-size:11px; font-weight:600; color:#aaa; text-transform:uppercase; letter-spacing:0.5px; margin-bottom:5px; }
        .jm-field select, .jm-field input[type=date], .jm-field input[type=text], .jm-field textarea {
            width:100%; box-sizing:border-box; border:1px solid #ddd; border-radius:5px;
            padding:7px 10px; font-size:13px; color:#333; font-family:inherit;
            transition:border-color 0.15s;
        }
        .jm-field select:focus, .jm-field input:focus, .jm-field textarea:focus { outline:none; border-color:#28a745; }
        .jm-field textarea { resize:vertical; min-height:72px; }
        .jm-desc { font-size:12px; color:#555; line-height:1.6; white-space:pre-wrap; background:#f9f9f9; border:1px solid #eee; border-radius:5px; padding:10px; margin-top:6px; }
        .jm-details-toggle { display:flex; align-items:center; gap:6px; width:100%; background:none; border:none; border-top:1px solid #eee; padding:10px 0 4px; cursor:pointer; font-size:12px; color:#666; font-weight:600; text-align:left; }
        .jm-details-toggle:hover { color:#28a745; }
        .jm-details-toggle .jm-toggle-arrow { display:inline-block; transition:transform 0.25s; font-size:10px; }
        .jm-details-toggle.open .jm-toggle-arrow { transform:rotate(90deg); }
        .jm-details-body { max-height:0; overflow:hidden; transition:max-height 0.3s ease; }
        .jm-details-body.open { max-height:600px; }
        .jm-detail-row { display:flex; gap:6px; font-size:12px; color:#555; margin-bottom:6px; align-items:flex-start; }
        .jm-detail-row label { font-weight:600; color:#888; min-width:76px; flex-shrink:0; }
        .jm-detail-row a { color:#28a745; word-break:break-all; }
        .jm-ai-reason { font-size:12px; color:#555; background:#f0faf2; border:1px solid #c3e6cb; border-radius:5px; padding:8px 10px; margin-top:4px; }
        .jm-gen-btn { display:inline-flex; align-items:center; gap:5px; flex:1; justify-content:center; background:#f0faf2; color:#28a745; border:1px solid #c3e6cb; border-radius:5px; padding:7px 12px; font-size:12px; font-weight:600; cursor:pointer; font-family:inherit; transition:all 0.15s; }
        .jm-gen-btn:hover, .jm-gen-btn.active { background:#28a745; color:#fff; border-color:#28a745; }
        .jm-gen-btn:disabled { opacity:.55; cursor:default; }
        .outreach-card { border:1px solid #e0e0e0; border-radius:7px; padding:10px 13px; margin-bottom:8px; font-size:13px; }
        .outreach-card-head { display:flex; align-items:baseline; gap:8px; flex-wrap:wrap; margin-bottom:4px; }
        .outreach-card-name { font-weight:700; color:#222; }
        .outreach-card-score { font-size:10px; font-weight:700; background:#e8f5e9; color:#28a745; border-radius:10px; padding:2px 7px; }
        .outreach-card-title { font-size:12px; color:#555; }
        .outreach-card-loc { font-size:11px; color:#aaa; }
        .outreach-card-msg { font-size:12px; color:#444; background:#f9f9f9; border:1px solid #eee; border-radius:5px; padding:7px 10px; margin-top:6px; line-height:1.5; }
        .outreach-card-link { font-size:11px; color:#28a745; text-decoration:none; }
        .outreach-card-link:hover { text-decoration:underline; }
        /* ── A4 CV/CL modal ── */
        #cv-a4-modal { position:fixed; inset:0; z-index:2000; flex-direction:column; background:#c8c8c8; opacity:0; transition:opacity 0.2s ease; }
        #cv-a4-modal.is-open { opacity:1; }
        #cva-toolbar { display:flex; align-items:center; gap:8px; background:#1e1e1e; padding:10px 16px; flex-shrink:0; }
        #cva-instruction-bar { display:flex; align-items:center; gap:8px; background:#2d2d2d; padding:8px 16px; flex-shrink:0; }
        #cva-instruction { flex:1; background:#1e1e1e; color:#ddd; border:1px solid #444; border-radius:5px; padding:7px 10px; font-size:12px; font-family:inherit; resize:none; height:38px; line-height:1.4; }
        #cva-instruction:focus { outline:none; border-color:#28a745; }
        #cva-page-area { flex:1; overflow-y:auto; background:#c8c8c8; padding:30px 20px; display:flex; justify-content:center; align-items:flex-start; }
        #cva-paper { width:210mm; min-height:297mm; background:white; padding:20mm 22mm; box-shadow:0 4px 20px rgba(0,0,0,0.2); font-family:Arial,sans-serif; font-size:11pt; line-height:1.6; color:#222; outline:none; box-sizing:border-box; }
        #cva-loading { display:flex; flex-direction:column; align-items:center; justify-content:center; gap:12px; width:210mm; min-height:200px; }
        .jm-footer { padding:16px 24px; border-top:1px solid #eee; display:flex; justify-content:flex-end; gap:10px; }
        .jm-btn { padding:8px 20px; border-radius:5px; font-size:13px; font-weight:600; cursor:pointer; border:none; }
        .jm-btn-cancel { background:#f0f0f0; color:#555; }
        .jm-btn-cancel:hover { background:#e0e0e0; }
        .jm-btn-save { background:#28a745; color:#fff; }
        .jm-btn-save:hover { background:#218838; }

        /* ── Editable fields ── */
        .editable-field {
            cursor: pointer; padding: 8px; border-radius: 4px;
            transition: background-color 0.2s; outline: none;
            font-size: 14px; color: #333; line-height: 1.6;
        }
        .editable-field:hover { background-color: rgba(40, 167, 69, 0.08); }
        .editable-field:focus, .editable-field.editing {
            background-color: #fff; border: 2px solid #28a745; outline: none;
        }
        .tag-input-container {
            display: flex; flex-wrap: wrap; gap: 8px; padding: 8px;
            border: 1px solid #c3e6cb; border-radius: 6px; min-height: 40px;
            cursor: text; background: #fff; align-items: center;
        }
        .tag-input-container:focus-within { border-color: #28a745; box-shadow: 0 0 0 2px rgba(40,167,69,0.12); }
        .tag-input-container .tag { background: #90EE90; color: #2d6a2d; border: 1px solid #7CCD7C; }
        .tag-input-container .tag .remove-tag { cursor: pointer; font-size: 15px; font-weight: bold; margin-left: 2px; opacity: 0.6; }
        .tag-input-container .tag .remove-tag:hover { color: #c0392b; opacity: 1; }
        .tag-input { border: none; outline: none; font-size: 13px; flex: 1; min-width: 120px; background: transparent; color: #333; padding: 2px 4px; font-family: 'Ubuntu', sans-serif; }

        /* ── Save bar ── */
        .save-bar {
            position: fixed; bottom: 0; left: 0; right: 0;
            background: white; box-shadow: 0 -2px 12px rgba(0,0,0,0.1);
            padding: 12px 30px; display: none; align-items: center;
            justify-content: center; gap: 12px; z-index: 200;
        }
        .btn-save {
            background: #28a745; color: white; border: none;
            padding: 10px 28px; border-radius: 6px; font-size: 14px;
            cursor: pointer; font-family: 'Ubuntu', sans-serif;
            display: inline-flex; align-items: center; gap: 6px;
        }
        .btn-save:hover { background: #218838; }
        .btn-cancel {
            background: #f0f0f0; color: #555; border: 1px solid #ddd;
            padding: 10px 24px; border-radius: 6px; font-size: 14px;
            cursor: pointer; font-family: 'Ubuntu', sans-serif;
        }

        /* ── AI panel ── */
        .ai-panel {
            background: #f0faf2; border: 1px solid #c3e6cb; border-radius: 8px;
            padding: 18px 20px; margin-bottom: 20px;
        }

        /* ── Form section ── */
        .form-answer { padding: 12px 0; border-bottom: 1px solid #f5f5f5; }
        .form-answer:last-child { border-bottom: none; }
        .form-answer label { font-size: 11px; font-weight: 700; color: #aaa; text-transform: uppercase; letter-spacing: 0.5px; display: block; margin-bottom: 4px; }

        /* ── Plan / gap ── */
        .plan-row { display: flex; gap: 12px; padding: 10px 0; border-bottom: 1px solid #f5f5f5; font-size: 13px; }
        .plan-row:last-child { border-bottom: none; }
        .plan-key { font-weight: 600; color: #555; min-width: 160px; flex-shrink: 0; }
        .strength-list { padding-left: 18px; margin: 0; }
        .strength-list li { font-size: 13px; color: #2e7d32; line-height: 1.8; }
        .gap-list { padding-left: 18px; margin: 0; }
        .gap-list li { font-size: 13px; color: #444; line-height: 1.8; }

        /* ── Job Search Modal ── */
        .js-spinner { width:36px; height:36px; border:3px solid #e8f5e9; border-top-color:#28a745; border-radius:50%; animation:spin 0.8s linear infinite; margin:0 auto; }
        @keyframes spin { to { transform:rotate(360deg); } }
        .js-job-card { border:1px solid #e8e8e8; border-radius:8px; padding:14px 16px; transition:border-color 0.15s,background 0.15s; }
        .js-job-card.decided-accept { border-color:#28a745; background:#f0faf2; }
        .js-job-card.decided-decline { border-color:#ddd; background:#fafafa; opacity:0.55; }
        .js-job-title { font-size:14px; font-weight:600; color:#222; margin:0 0 3px; }
        .js-job-meta { font-size:12px; color:#888; margin:0 0 5px; }
        .js-ai-reason { font-size:11px; color:#999; font-style:italic; margin-bottom:8px; }
        .js-job-desc { font-size:12px; color:#555; line-height:1.6; background:#f9f9f9; border:1px solid #eee; border-radius:4px; padding:8px; margin:8px 0; display:none; max-height:140px; overflow-y:auto; white-space:pre-wrap; }
        .js-job-actions { display:flex; gap:8px; align-items:center; flex-wrap:wrap; margin-top:8px; }
        .js-btn-accept { background:#28a745; color:#fff; border:none; border-radius:4px; padding:5px 14px; font-size:12px; font-weight:600; cursor:pointer; display:inline-flex; align-items:center; gap:4px; font-family:inherit; }
        .js-btn-accept:hover { background:#218838; }
        .js-btn-decline { background:#f5f5f5; color:#555; border:1px solid #ddd; border-radius:4px; padding:5px 14px; font-size:12px; font-weight:600; cursor:pointer; font-family:inherit; }
        .js-btn-decline:hover { background:#fee2e2; color:#c62828; border-color:#f5c6cb; }
        .js-btn-view { background:none; color:#28a745; border:none; cursor:pointer; font-size:12px; display:inline-flex; align-items:center; gap:3px; font-family:inherit; padding:0; }
        .js-decline-input { width:100%; box-sizing:border-box; border:1px solid #ddd; border-radius:4px; padding:6px 8px; font-size:12px; margin-top:8px; font-family:inherit; }
        .js-decline-input:focus { outline:none; border-color:#28a745; }
        .js-stat-pill { display:inline-block; background:#f0faf2; color:#2e7d32; font-size:11px; font-weight:600; padding:2px 8px; border-radius:10px; border:1px solid #c3e6cb; }

        /* ── Changelog ── */
        .cl-entry { display: flex; gap: 14px; align-items: flex-start; padding: 10px 0; border-bottom: 1px solid #f5f5f5; font-size: 13px; }
        .cl-entry:last-child { border-bottom: none; }
        .cl-who { font-weight: 600; color: #28a745; min-width: 60px; }
        .cl-action { color: #444; flex: 1; }
        .cl-ts { color: #bbb; font-size: 12px; white-space: nowrap; }

        .empty-state { text-align: center; color: #bbb; font-size: 14px; padding: 30px 0; }
        .badge-count { background: #28a745; color: white; font-size: 10px; padding: 1px 6px; border-radius: 10px; font-weight: 700; }
        .coach-notes { background: #fffde7; border-left: 3px solid #f9a825; padding: 14px 18px; border-radius: 0 6px 6px 0; font-size: 13px; color: #555; line-height: 1.7; }

        /* ── Plan/Status badges in banner ── */
        .profile-badge {
            display: inline-flex; align-items: center; gap: 4px;
            font-size: 11px; font-weight: 700; padding: 3px 10px; border-radius: 12px;
            text-transform: uppercase; letter-spacing: 0.5px; cursor: pointer;
            transition: opacity 0.15s;
        }
        .profile-badge:hover { opacity: 0.8; }
        .badge-silver   { background: rgba(255,255,255,0.2); color: white; border: 1px solid rgba(255,255,255,0.4); }
        .badge-golden   { background: #fff8e1; color: #f57f17; border: 1px solid #ffe082; }
        .badge-platinum { background: #ede7f6; color: #5e35b1; border: 1px solid #ce93d8; }
        .badge-active   { background: rgba(255,255,255,0.2); color: white; border: 1px solid rgba(255,255,255,0.4); }
        .badge-inactive { background: #fafafa; color: #aaa; border: 1px solid #ddd; }

        /* ── Plan/Status modal ── */
        .ps-overlay {
            display: none; position: fixed; inset: 0;
            background: rgba(0,0,0,0.45); z-index: 1200;
            align-items: center; justify-content: center; padding: 20px;
        }
        .ps-overlay.open { display: flex; }
        .ps-panel {
            background: white; border-radius: 10px; width: 100%; max-width: 360px;
            box-shadow: 0 8px 40px rgba(0,0,0,0.2);
        }
        .ps-header { padding: 18px 22px 14px; border-bottom: 1px solid #eee; font-size: 15px; font-weight: 700; color: #222; display: flex; justify-content: space-between; align-items: center; }
        .ps-close { border: none; background: none; font-size: 18px; color: #aaa; cursor: pointer; padding: 0; line-height: 1; }
        .ps-close:hover { color: #333; }
        .ps-body { padding: 20px 22px; display: flex; flex-direction: column; gap: 14px; }
        .ps-field label { display: block; font-size: 11px; font-weight: 600; color: #aaa; text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 5px; }
        .ps-field select { width: 100%; border: 1px solid #ddd; border-radius: 5px; padding: 8px 10px; font-size: 14px; color: #333; font-family: 'Ubuntu', sans-serif; }
        .ps-field select:focus { outline: none; border-color: #28a745; }
        .ps-footer { padding: 14px 22px; border-top: 1px solid #eee; display: flex; justify-content: flex-end; gap: 10px; }
        .ps-btn-cancel { background: #f0f0f0; color: #555; border: none; border-radius: 5px; padding: 8px 18px; font-size: 13px; font-weight: 600; cursor: pointer; font-family: 'Ubuntu', sans-serif; }
        .ps-btn-save { background: #28a745; color: white; border: none; border-radius: 5px; padding: 8px 20px; font-size: 13px; font-weight: 600; cursor: pointer; font-family: 'Ubuntu', sans-serif; }
        .ps-btn-save:hover { background: #218838; }
    </style>
</head>
<body>
<%
  var cs       = locals.careerStrategy || {};
  var cv       = locals.cv             || {};
  var form     = locals.form           || {};
  var cvmaster = cv; // profile.ejs passes cv as cvmaster data
  var segments = (cs.strategy && cs.strategy.segments && cs.strategy.segments.length)
                 ? cs.strategy.segments
                 : (cs.strategicSegments || []);
  var jobs = (locals.jobtracking && locals.jobtracking.jobs) ? locals.jobtracking.jobs : [];
%>

<!-- Header -->
<div class="portal-header">
    <span class="logo-text">EcoBot</span>
    <div class="header-actions">
        <a href="/admin/dashboard" class="btn-header">
            <span class="material-icons" style="font-size:16px;">arrow_back</span>Dashboard
        </a>
        <button id="btnResendEmail" class="btn-header" onclick="resendSetupEmail()">
            <span class="material-icons" style="font-size:16px;">email</span>Resend email
        </button>
        <button id="btnAiUpdate" class="btn-header green" onclick="toggleAiPanel()">
            <span class="material-icons" style="font-size:16px;">auto_awesome</span>AI Update
        </button>
        <a href="/admin/logout" class="btn-logout-hdr">
            <span class="material-icons" style="font-size:16px;">logout</span>Logout
        </a>
    </div>
</div>

<!-- AI Update Panel -->
<div id="aiUpdatePanel" style="display:none;" class="ai-panel" style="border-radius:0;margin:0;">
    <div style="max-width:960px;margin:0 auto;padding:0 20px;">
        <h4 style="margin:0 0 8px;color:#28a745;font-size:14px;"><span class="material-icons" style="vertical-align:middle;font-size:17px;">auto_awesome</span> AI Update from notes / form</h4>
        <textarea id="aiFormText" rows="6" style="width:100%;box-sizing:border-box;border:1px solid #c3e6cb;border-radius:6px;padding:10px;font-size:13px;resize:vertical;font-family:'Ubuntu',sans-serif;" placeholder="Paste form content or notes here..."></textarea>
        <div style="margin-top:10px;text-align:right;">
            <button id="btnRunAi" onclick="runAiUpdate()" style="background:#28a745;color:#fff;border:none;border-radius:6px;padding:10px 20px;font-size:14px;cursor:pointer;font-family:'Ubuntu',sans-serif;">Update with AI</button>
        </div>
    </div>
</div>

<!-- Welcome banner -->
<%
  var csPlan   = cs.plan || 'silver';
  var csStatus = cs.status || 'active';
  var planLabel = { silver:'Silver', golden:'Golden', platinum:'Platinum' }[csPlan] || 'Silver';
  var statusLabel = csStatus === 'inactive' ? 'Inactive' : 'Active';
  var planBadgeClass   = 'badge-' + csPlan;
  var statusBadgeClass = csStatus === 'inactive' ? 'badge-inactive' : 'badge-active';
%>
<div class="welcome-banner">
    <div class="welcome-avatar"><%= (cs.leadName || 'C').charAt(0).toUpperCase() %></div>
    <div class="welcome-text" style="flex:1;">
        <h2><%= cs.leadName || slug.replace(/-/g, ' ') %></h2>
        <p><%= cs.email || '' %><% if (cs.phone) { %> · <%= cs.phone %><% } %><% if (cs.location) { %> · <%= cs.location %><% } %></p>
        <div style="margin-top:8px;display:flex;gap:6px;flex-wrap:wrap;">
            <span class="profile-badge <%= planBadgeClass %>" onclick="openPlanStatusModal('plan')" title="Change plan">
                <span class="material-icons" style="font-size:12px;">workspace_premium</span><%= planLabel %>
            </span>
            <span class="profile-badge <%= statusBadgeClass %>" onclick="openPlanStatusModal('status')" title="Change status">
                <span class="material-icons" style="font-size:12px;"><%= csStatus === 'inactive' ? 'pause_circle' : 'check_circle' %></span><%= statusLabel %>
            </span>
        </div>
    </div>
</div>

<div class="portal-body">

<!-- Tab bar -->
<div class="tab-bar">
    <button class="tab-btn active" onclick="showTab('overview', this)">
        <span class="material-icons" style="font-size:16px;">person</span>Overview
    </button>
    <button class="tab-btn" onclick="showTab('strategy', this)">
        <span class="material-icons" style="font-size:16px;">track_changes</span>Career Strategy
    </button>
    <% if (cv && Object.keys(cv).length > 0) { %>
    <button class="tab-btn" onclick="showTab('dossier', this)">
        <span class="material-icons" style="font-size:16px;">description</span>Career Dossier
    </button>
    <% } %>
    <button class="tab-btn" onclick="showTab('form', this)">
        <span class="material-icons" style="font-size:16px;">assignment</span>Form
    </button>
    <button class="tab-btn" onclick="showTab('jobs', this)">
        <span class="material-icons" style="font-size:16px;">work</span>Job Tracking
        <% if (jobs.length > 0) { %><span class="badge-count"><%= jobs.length %></span><% } %>
    </button>
    <button class="tab-btn" onclick="showTab('history', this)">
        <span class="material-icons" style="font-size:16px;">history</span>History
    </button>
</div>

<!-- ── OVERVIEW ── -->
<div id="tab-overview" class="tab-pane active">

    <div class="card">
        <div class="card-title"><span class="material-icons">info</span>Profile</div>
        <div class="info-grid">
            <% if (cs.email) { %>
            <div class="info-item"><label>Email</label>
                <p><div class="editable-field" contenteditable="true" data-field="email"><%= cs.email %></div></p>
            </div>
            <% } %>
            <div class="info-item"><label>Phone</label>
                <p><div class="editable-field" contenteditable="true" data-field="phone"><%= cs.phone || '' %></div></p>
            </div>
            <div class="info-item"><label>Location</label>
                <p><div class="editable-field" contenteditable="true" data-field="location"><%= cs.location || '' %></div></p>
            </div>
            <div class="info-item"><label>LinkedIn</label>
                <p><div class="editable-field" contenteditable="true" data-field="linkedin"><%= cs.linkedin || (cv && cv.contact && cv.contact.linkedin) || '' %></div></p>
            </div>
            <div class="info-item"><label>Nationality</label>
                <p><div class="editable-field" contenteditable="true" data-field="nationality"><%= cs.nationality || '' %></div></p>
            </div>
            <div class="info-item"><label>Seniority</label>
                <p><div class="editable-field" contenteditable="true" data-field="seniority"><%= cs.seniority || '' %></div></p>
            </div>
            <div class="info-item"><label>Salary Target</label>
                <p><div class="editable-field" contenteditable="true" data-field="salaryTarget"><%= cs.salaryTarget || '' %></div></p>
            </div>
            <% if (cs.workPermits && cs.workPermits.length) { %>
            <div class="info-item"><label>Work Permits</label>
                <p><%= cs.workPermits.join(', ') %></p>
            </div>
            <% } %>
        </div>

        <% if (cs.languages && cs.languages.length) { %>
        <div style="margin-top:16px;padding-top:14px;border-top:1px solid #f0f0f0;">
            <label style="font-size:11px;font-weight:600;color:#aaa;text-transform:uppercase;letter-spacing:0.5px;display:block;margin-bottom:8px;">Languages</label>
            <div class="tag-input-container editable-tags" data-field="languages" data-type="array">
                <% cs.languages.forEach(function(l){ %>
                    <span class="tag" contenteditable="false"><%= l %><span class="remove-tag">×</span></span>
                <% }); %>
            </div>
        </div>
        <% } %>

        <% var desc = cs.shortDescription || (cv && cv.summary); %>
        <% if (desc) { %>
        <div style="margin-top:16px;padding-top:14px;border-top:1px solid #f0f0f0;">
            <label style="font-size:11px;font-weight:600;color:#aaa;text-transform:uppercase;letter-spacing:0.5px;display:block;margin-bottom:6px;">Summary</label>
            <div class="editable-field" contenteditable="true" data-field="shortDescription"><%= desc %></div>
        </div>
        <% } %>
    </div>

    <% if (cs.primaryRoles && cs.primaryRoles.length) { %>
    <div class="card">
        <div class="card-title"><span class="material-icons">track_changes</span>Target Roles</div>
        <div class="tag-input-container editable-tags" data-field="primaryRoles" data-type="array" style="margin-bottom:10px;">
            <% cs.primaryRoles.forEach(function(r){ %><span class="tag" contenteditable="false"><%= r %><span class="remove-tag">×</span></span><% }); %>
        </div>
        <% if (cs.secondaryRoles && cs.secondaryRoles.length) { %>
        <div class="tag-input-container editable-tags" data-field="secondaryRoles" data-type="array">
            <% cs.secondaryRoles.forEach(function(r){ %><span class="tag" contenteditable="false"><%= r %><span class="remove-tag">×</span></span><% }); %>
        </div>
        <% } %>
    </div>
    <% } %>

    <% if (cs.gapAnalysis && cs.gapAnalysis.strengths && cs.gapAnalysis.strengths.length) { %>
    <div class="card">
        <div class="card-title"><span class="material-icons">star</span>Strengths</div>
        <div class="tag-input-container editable-tags" data-field="gapAnalysis.strengths" data-type="array">
            <% cs.gapAnalysis.strengths.forEach(function(s){ %><span class="tag" contenteditable="false"><%= s %><span class="remove-tag">×</span></span><% }); %>
        </div>
    </div>
    <% } %>

</div>

<!-- ── CAREER STRATEGY ── -->
<div id="tab-strategy" class="tab-pane">

    <% if (cs.search && cs.search.positioning) { %>
    <div class="card">
        <div class="card-title"><span class="material-icons">flag</span>Positioning</div>
        <div class="editable-field" contenteditable="true" data-field="search.positioning"><%= cs.search.positioning %></div>
    </div>
    <% } %>

    <% if (cs.targetPositioning) { %>
    <div class="card">
        <div class="card-title"><span class="material-icons">my_location</span>Target Positioning</div>
        <div class="editable-field" contenteditable="true" data-field="targetPositioning"><%= cs.targetPositioning %></div>
    </div>
    <% } %>

    <div class="card">
        <div class="card-title"><span class="material-icons">view_agenda</span>Strategic Segments</div>
        <% segments.forEach(function(seg, i) { %>
        <div class="segment-card">
            <p class="segment-label"><span class="segment-num"><%= i + 1 %></span><%= seg.name || seg.label %></p>

            <% if (seg.description) { %>
            <p class="segment-narrative"><div class="editable-field" contenteditable="true" data-field="strategy.segments.<%= i %>.description"><%= seg.description %></div></p>
            <% } %>

            <% if (seg.targetRoles && seg.targetRoles.length) { %>
            <div class="segment-section">
                <div class="segment-section-title">Target Roles</div>
                <div class="tag-input-container editable-tags" data-field="strategy.segments.<%= i %>.targetRoles" data-type="array">
                    <% seg.targetRoles.forEach(function(r){ %><span class="tag" contenteditable="false"><%= r %><span class="remove-tag">×</span></span><% }); %>
                </div>
            </div>
            <% } %>

            <% if (seg.targetSectors && seg.targetSectors.length) { %>
            <div class="segment-section">
                <div class="segment-section-title">Sectors</div>
                <div class="tag-input-container editable-tags" data-field="strategy.segments.<%= i %>.targetSectors" data-type="array">
                    <% seg.targetSectors.forEach(function(s){ %><span class="tag" contenteditable="false"><%= s %><span class="remove-tag">×</span></span><% }); %>
                </div>
            </div>
            <% } %>

            <div style="display:flex;gap:24px;flex-wrap:wrap;margin-top:8px;">
                <% if (seg.targetGeographies && seg.targetGeographies.length) { %>
                <div>
                    <div class="segment-section-title">Geographies</div>
                    <div class="tag-list">
                        <% seg.targetGeographies.forEach(function(g){ %><span class="tag-blue"><%= g %></span><% }); %>
                    </div>
                </div>
                <% } %>
                <% if (seg.salaryRange) { %>
                <div>
                    <div class="segment-section-title">Salary Range</div>
                    <div class="editable-field" contenteditable="true" data-field="strategy.segments.<%= i %>.salaryRange" style="display:inline-block;font-size:13px;font-weight:600;"><%= seg.salaryRange %></div>
                </div>
                <% } %>
            </div>

            <% if (seg.keyNarrative) { %>
            <p class="segment-narrative"><div class="editable-field" contenteditable="true" data-field="strategy.segments.<%= i %>.keyNarrative"><%= seg.keyNarrative %></div></p>
            <% } %>

            <% if (seg.targetCompanies && seg.targetCompanies.length) { %>
            <div class="segment-section" style="margin-top:10px;">
                <div class="segment-section-title">Target Companies</div>
                <div class="tag-input-container editable-tags" data-field="strategy.segments.<%= i %>.targetCompanies" data-type="array">
                    <% seg.targetCompanies.forEach(function(c){ %><span class="tag" contenteditable="false"><%= c %><span class="remove-tag">×</span></span><% }); %>
                </div>
            </div>
            <% } %>
        </div>
        <% }); %>
    </div>

    <% if (cs.gapAnalysis) { %>
    <div class="card">
        <div class="card-title"><span class="material-icons">analytics</span>Gap Analysis</div>
        <% if (cs.gapAnalysis.strengths && cs.gapAnalysis.strengths.length) { %>
        <div style="margin-bottom:18px;">
            <div class="dossier-section-title">Strengths</div>
            <div class="tag-input-container editable-tags" data-field="gapAnalysis.strengths" data-type="array">
                <% cs.gapAnalysis.strengths.forEach(function(s){ %><span class="tag" contenteditable="false"><%= s %><span class="remove-tag">×</span></span><% }); %>
            </div>
        </div>
        <% } %>
        <% if (cs.gapAnalysis.gapsVsTargetRoles && cs.gapAnalysis.gapsVsTargetRoles.length) { %>
        <div style="margin-bottom:18px;">
            <div class="dossier-section-title">Areas to develop</div>
            <div class="tag-input-container editable-tags" data-field="gapAnalysis.gapsVsTargetRoles" data-type="array">
                <% cs.gapAnalysis.gapsVsTargetRoles.forEach(function(g){ %><span class="tag" contenteditable="false"><%= g %><span class="remove-tag">×</span></span><% }); %>
            </div>
        </div>
        <% } %>
        <% if (cs.gapAnalysis.gapClosurePlan && cs.gapAnalysis.gapClosurePlan.length) { %>
        <div>
            <div class="dossier-section-title">Action plan</div>
            <div class="tag-input-container editable-tags" data-field="gapAnalysis.gapClosurePlan" data-type="array">
                <% cs.gapAnalysis.gapClosurePlan.forEach(function(p){ %><span class="tag" contenteditable="false"><%= p %><span class="remove-tag">×</span></span><% }); %>
            </div>
        </div>
        <% } %>
    </div>
    <% } %>

    <% if (cs.strategy && cs.strategy.executionPlan) { %>
    <div class="card">
        <div class="card-title"><span class="material-icons">assignment</span>Execution Plan</div>
        <% var ep = cs.strategy.executionPlan; %>
        <% if (ep.weeklyTargets) { %>
        <div class="plan-row"><span class="plan-key">Weekly targets</span><span class="plan-val"><div class="editable-field" contenteditable="true" data-field="strategy.executionPlan.weeklyTargets"><%= ep.weeklyTargets %></div></span></div>
        <% } %>
        <% if (ep.applicationApproach) { %>
        <div class="plan-row"><span class="plan-key">Applications</span><span class="plan-val"><div class="editable-field" contenteditable="true" data-field="strategy.executionPlan.applicationApproach"><%= ep.applicationApproach %></div></span></div>
        <% } %>
        <% if (ep.networkingApproach) { %>
        <div class="plan-row"><span class="plan-key">Networking</span><span class="plan-val"><div class="editable-field" contenteditable="true" data-field="strategy.executionPlan.networkingApproach"><%= ep.networkingApproach %></div></span></div>
        <% } %>
        <% if (ep.linkedinStrategy) { %>
        <div class="plan-row"><span class="plan-key">LinkedIn</span><span class="plan-val"><div class="editable-field" contenteditable="true" data-field="strategy.executionPlan.linkedinStrategy"><%= ep.linkedinStrategy %></div></span></div>
        <% } %>
        <% if (cs.strategy.timeline && cs.strategy.timeline.targetPlacementBy) { %>
        <div class="plan-row">
            <span class="plan-key">Timeline</span>
            <span class="plan-val">Target: <strong><%= cs.strategy.timeline.targetPlacementBy %></strong></span>
        </div>
        <% } %>
    </div>
    <% } %>

    <%
    var hasSearch = cs.search && (
        (cs.search.targetRoles && cs.search.targetRoles.length) ||
        (cs.search.targetGeographies && cs.search.targetGeographies.length) ||
        (cs.search.targetSectors && cs.search.targetSectors.length)
    );
    %>
    <% if (hasSearch) { %>
    <div class="card">
        <div class="card-title"><span class="material-icons">search</span>Search Parameters</div>
        <% if (cs.search.targetRoles && cs.search.targetRoles.length) { %>
        <div style="margin-bottom:12px;">
            <div class="dossier-section-title">Target Roles</div>
            <div class="tag-input-container editable-tags" data-field="search.targetRoles" data-type="array">
                <% cs.search.targetRoles.forEach(function(r){ %><span class="tag" contenteditable="false"><%= r %><span class="remove-tag">×</span></span><% }); %>
            </div>
        </div>
        <% } %>
        <% if (cs.search.targetGeographies && cs.search.targetGeographies.length) { %>
        <div style="margin-bottom:12px;">
            <div class="dossier-section-title">Geographies</div>
            <div class="tag-input-container editable-tags" data-field="search.targetGeographies" data-type="array">
                <% cs.search.targetGeographies.forEach(function(g){ %><span class="tag" contenteditable="false"><%= g %><span class="remove-tag">×</span></span><% }); %>
            </div>
        </div>
        <% } %>
        <% if (cs.search.targetSectors && cs.search.targetSectors.length) { %>
        <div>
            <div class="dossier-section-title">Sectors</div>
            <div class="tag-input-container editable-tags" data-field="search.targetSectors" data-type="array">
                <% cs.search.targetSectors.forEach(function(s){ %><span class="tag" contenteditable="false"><%= s %><span class="remove-tag">×</span></span><% }); %>
            </div>
        </div>
        <% } %>
    </div>
    <% } %>

    <%
    var hasGeo = (cs.priorityCities && cs.priorityCities.length) ||
                 cs.primaryCountry ||
                 (cs.secondaryRegions && cs.secondaryRegions.length) ||
                 (cs.targetGeographies && cs.targetGeographies.length) ||
                 cs.mobility;
    %>
    <% if (hasGeo) { %>
    <div class="card">
        <div class="card-title"><span class="material-icons">location_on</span>Geography & Mobility</div>
        <% if (cs.primaryCountry) { %>
        <div class="plan-row"><span class="plan-key">Primary Country</span><span class="plan-val"><div class="editable-field" contenteditable="true" data-field="primaryCountry"><%= cs.primaryCountry %></div></span></div>
        <% } %>
        <% if (cs.priorityCities && cs.priorityCities.length) { %>
        <div style="margin:10px 0;">
            <div class="dossier-section-title">Priority Cities</div>
            <div class="tag-input-container editable-tags" data-field="priorityCities" data-type="array">
                <% cs.priorityCities.forEach(function(c){ %><span class="tag" contenteditable="false"><%= c %><span class="remove-tag">×</span></span><% }); %>
            </div>
        </div>
        <% } %>
        <% if (cs.secondaryRegions && cs.secondaryRegions.length) { %>
        <div style="margin:10px 0;">
            <div class="dossier-section-title">Secondary Regions</div>
            <div class="tag-input-container editable-tags" data-field="secondaryRegions" data-type="array">
                <% cs.secondaryRegions.forEach(function(r){ %><span class="tag" contenteditable="false"><%= r %><span class="remove-tag">×</span></span><% }); %>
            </div>
        </div>
        <% } %>
        <% if (cs.targetGeographies && cs.targetGeographies.length) { %>
        <div style="margin:10px 0;">
            <div class="dossier-section-title">Target Geographies</div>
            <div class="tag-input-container editable-tags" data-field="targetGeographies" data-type="array">
                <% cs.targetGeographies.forEach(function(g){ %><span class="tag" contenteditable="false"><%= g %><span class="remove-tag">×</span></span><% }); %>
            </div>
        </div>
        <% } %>
        <% if (cs.mobility) { %>
        <div class="plan-row" style="margin-top:10px;"><span class="plan-key">Mobility</span><span class="plan-val"><div class="editable-field" contenteditable="true" data-field="mobility"><%= cs.mobility %></div></span></div>
        <% } %>
    </div>
    <% } %>

    <%
    var hasIndustry = (cs.industrySectors && cs.industrySectors.length) ||
                      (cs.acceptableSectors && cs.acceptableSectors.length) ||
                      (cs.typeOfCompany && cs.typeOfCompany.length);
    %>
    <% if (hasIndustry) { %>
    <div class="card">
        <div class="card-title"><span class="material-icons">business</span>Industries & Company Types</div>
        <% if (cs.industrySectors && cs.industrySectors.length) { %>
        <div style="margin-bottom:12px;">
            <div class="dossier-section-title">Target Industries</div>
            <div class="tag-input-container editable-tags" data-field="industrySectors" data-type="array">
                <% cs.industrySectors.forEach(function(s){ %><span class="tag" contenteditable="false"><%= s %><span class="remove-tag">×</span></span><% }); %>
            </div>
        </div>
        <% } %>
        <% if (cs.acceptableSectors && cs.acceptableSectors.length) { %>
        <div style="margin-bottom:12px;">
            <div class="dossier-section-title">Acceptable Sectors</div>
            <div class="tag-input-container editable-tags" data-field="acceptableSectors" data-type="array">
                <% cs.acceptableSectors.forEach(function(s){ %><span class="tag" contenteditable="false"><%= s %><span class="remove-tag">×</span></span><% }); %>
            </div>
        </div>
        <% } %>
        <% if (cs.typeOfCompany && cs.typeOfCompany.length) { %>
        <div>
            <div class="dossier-section-title">Company Types</div>
            <div class="tag-input-container editable-tags" data-field="typeOfCompany" data-type="array">
                <% cs.typeOfCompany.forEach(function(t){ %><span class="tag" contenteditable="false"><%= t %><span class="remove-tag">×</span></span><% }); %>
            </div>
        </div>
        <% } %>
    </div>
    <% } %>

    <%
    var hasScope = (cs.jobScope && cs.jobScope.length) || cs.jobLanguage || cs.applicationType;
    %>
    <% if (hasScope) { %>
    <div class="card">
        <div class="card-title"><span class="material-icons">work</span>Job Scope & Application</div>
        <% if (cs.jobScope && cs.jobScope.length) { %>
        <div style="margin-bottom:12px;">
            <div class="dossier-section-title">Job Scope</div>
            <div class="tag-input-container editable-tags" data-field="jobScope" data-type="array">
                <% cs.jobScope.forEach(function(s){ %><span class="tag" contenteditable="false"><%= s %><span class="remove-tag">×</span></span><% }); %>
            </div>
        </div>
        <% } %>
        <% if (cs.jobLanguage) { %>
        <div class="plan-row"><span class="plan-key">Job Language</span><span class="plan-val"><div class="editable-field" contenteditable="true" data-field="jobLanguage"><%= cs.jobLanguage %></div></span></div>
        <% } %>
        <% if (cs.applicationType) { %>
        <div class="plan-row" style="margin-top:8px;"><span class="plan-key">Application Type</span><span class="plan-val"><div class="editable-field" contenteditable="true" data-field="applicationType"><%= cs.applicationType %></div></span></div>
        <% } %>
    </div>
    <% } %>

    <% if (cs.exclusions && cs.exclusions.length) { %>
    <div class="card">
        <div class="card-title"><span class="material-icons">block</span>Exclusions</div>
        <div class="tag-input-container editable-tags" data-field="exclusions" data-type="array">
            <% cs.exclusions.forEach(function(e){ %><span class="tag" contenteditable="false"><%= e %><span class="remove-tag">×</span></span><% }); %>
        </div>
    </div>
    <% } %>

    <% if (cs.targetCompanies && cs.targetCompanies.length) { %>
    <div class="card">
        <div class="card-title"><span class="material-icons">domain</span>Target Companies</div>
        <div class="tag-input-container editable-tags" data-field="targetCompanies" data-type="array">
            <% cs.targetCompanies.forEach(function(c){ %><span class="tag" contenteditable="false"><%= c %><span class="remove-tag">×</span></span><% }); %>
        </div>
    </div>
    <% } %>

    <% if (cs.strategicNotes) { %>
    <div class="card">
        <div class="card-title"><span class="material-icons">notes</span>Strategic Notes</div>
        <div class="editable-field" contenteditable="true" data-field="strategicNotes"><%= cs.strategicNotes %></div>
    </div>
    <% } %>

    <% if (cs.opportunities) { %>
    <div class="card">
        <div class="card-title"><span class="material-icons">lightbulb</span>Opportunities</div>
        <div class="editable-field" contenteditable="true" data-field="opportunities"><%= cs.opportunities %></div>
    </div>
    <% } %>

    <% if (cs.strategy && cs.strategy.notes) { %>
    <div class="card">
        <div class="card-title"><span class="material-icons">sticky_note_2</span>Notes</div>
        <div class="editable-field" contenteditable="true" data-field="strategy.notes"><%= cs.strategy.notes %></div>
    </div>
    <% } %>

</div>

<!-- ── CAREER DOSSIER ── -->
<% if (cv && Object.keys(cv).length > 0) { %>
<div id="tab-dossier" class="tab-pane">
    <div class="card">
        <% if (cv.headline) { %>
        <p style="font-size:20px;font-weight:700;color:#1a1a1a;margin:0 0 10px;">
            <span class="editable-field" contenteditable="true" data-file="cv" data-field="headline"><%= cv.headline %></span>
        </p>
        <% } %>
        <% var narrativeField = cv.keyNarrative !== undefined ? 'keyNarrative' : cv.narrative !== undefined ? 'narrative' : 'summary'; %>
        <% var narrative = cv.keyNarrative || cv.narrative || cv.summary; %>
        <% if (narrative) { %>
        <div class="editable-field" contenteditable="true" data-file="cv" data-field="<%= narrativeField %>" style="font-size:14px;color:#444;line-height:1.8;margin-bottom:20px;"><%= narrative %></div>
        <% } %>

        <% if (cv.experience && cv.experience.length) { %>
        <div style="margin-bottom:26px;">
            <div class="dossier-section-title">Experience</div>
            <% cv.experience.forEach(function(exp, i) { %>
            <div class="exp-entry">
                <p class="exp-title"><span class="editable-field" contenteditable="true" data-file="cv" data-field="experience.<%= i %>.title"><%= exp.title || '' %></span></p>
                <p class="exp-company">
                    <span class="editable-field" contenteditable="true" data-file="cv" data-field="experience.<%= i %>.company" style="margin-right:4px;"><%= exp.company || '' %></span>
                    <span style="color:#bbb;margin:0 4px;">·</span><span class="editable-field" contenteditable="true" data-file="cv" data-field="experience.<%= i %>.location"><%= exp.location || '' %></span>
                </p>
                <p class="exp-dates"><span class="editable-field" contenteditable="true" data-file="cv" data-field="experience.<%= i %>.period"><%= exp.period || [exp.from, exp.to].filter(Boolean).join(' – ') || '' %></span></p>
                <div style="margin-top:8px;">
                    <div class="tag-input-container editable-tags" data-file="cv" data-field="experience.<%= i %>.highlights" data-type="array" style="flex-wrap:wrap;gap:6px;">
                        <% (exp.highlights || []).forEach(function(h){ %><span class="tag" contenteditable="false" style="white-space:normal;height:auto;line-height:1.4;padding:4px 8px;"><%= h %><span class="remove-tag">×</span></span><% }); %>
                    </div>
                </div>
            </div>
            <% }); %>
        </div>
        <% } %>

        <% if (cv.education && cv.education.length) { %>
        <div style="margin-bottom:26px;">
            <div class="dossier-section-title">Education</div>
            <% cv.education.forEach(function(edu, i) { %>
            <div class="exp-entry">
                <p class="exp-title"><span class="editable-field" contenteditable="true" data-file="cv" data-field="education.<%= i %>.degree"><%= edu.degree || edu.title || '' %></span></p>
                <p class="exp-company"><span class="editable-field" contenteditable="true" data-file="cv" data-field="education.<%= i %>.institution"><%= edu.institution || edu.school || '' %></span></p>
                <p class="exp-dates"><span class="editable-field" contenteditable="true" data-file="cv" data-field="education.<%= i %>.period"><%= edu.period || [edu.from, edu.to].filter(Boolean).join(' – ') || edu.year || edu.years || '' %></span></p>
            </div>
            <% }); %>
        </div>
        <% } %>

        <% if (cv.skills && cv.skills.length) { %>
        <div style="margin-bottom:26px;">
            <div class="dossier-section-title">Skills</div>
            <div class="tag-input-container editable-tags" data-file="cv" data-field="skills" data-type="array">
                <% cv.skills.forEach(function(s){ %><span class="tag" contenteditable="false"><%= s %><span class="remove-tag">×</span></span><% }); %>
            </div>
        </div>
        <% } %>

        <% if (cv.languages && cv.languages.length) { %>
        <div style="margin-bottom:26px;">
            <div class="dossier-section-title">Languages</div>
            <div class="tag-input-container editable-tags" data-file="cv" data-field="languages" data-type="array">
                <% cv.languages.forEach(function(l){ %><span class="tag" contenteditable="false"><%= typeof l === 'string' ? l : (l.language + (l.level ? ' (' + l.level + ')' : '')) %><span class="remove-tag">×</span></span><% }); %>
            </div>
        </div>
        <% } %>

        <% if (cv.certifications && cv.certifications.length) { %>
        <div style="margin-bottom:26px;">
            <div class="dossier-section-title">Certifications</div>
            <div class="tag-input-container editable-tags" data-file="cv" data-field="certifications" data-type="array">
                <% cv.certifications.forEach(function(c){ %><span class="tag" contenteditable="false"><%= typeof c === 'string' ? c : c.name %><span class="remove-tag">×</span></span><% }); %>
            </div>
        </div>
        <% } %>

        <div class="dossier-section-title" style="margin-top:16px;">Coach Notes</div>
        <div class="coach-notes"><div class="editable-field" contenteditable="true" data-file="cv" data-field="coachNotes"><%= cv.coachNotes || '' %></div></div>
    </div>
</div>
<% } %>

<!-- ── FORM ── -->
<div id="tab-form" class="tab-pane">
    <% if (form && form.answers && Object.keys(form.answers).length > 0) { %>
    <div class="card">
        <div class="card-title"><span class="material-icons">assignment</span>Client Form Answers</div>
        <% Object.entries(form.answers).forEach(function(entry) {
            var key = entry[0], value = entry[1];
            if (!value || value === '__skipped__') return;
            var lbl = key.replace(/_/g, ' ').replace(/\b\w/g, function(c){ return c.toUpperCase(); });
        %>
        <div class="form-answer">
            <label><%= lbl %></label>
            <div class="editable-field" contenteditable="true" data-file="form" data-field="<%= key %>"><%= value %></div>
        </div>
        <% }); %>
    </div>
    <% } else { %>
    <div class="card"><div class="empty-state"><span class="material-icons" style="font-size:40px;display:block;margin-bottom:8px;">assignment</span>No form answers yet.</div></div>
    <% } %>
</div>

<!-- ── JOB TRACKING ── -->
<div id="tab-jobs" class="tab-pane">
    <div class="card">
        <div class="card-title" style="justify-content:space-between;">
            <span style="display:flex;align-items:center;gap:8px;">
                <span class="material-icons">work</span>Job Tracking
                <span style="font-size:12px;color:#aaa;font-weight:400;"><%= jobs.length %> job<%= jobs.length !== 1 ? 's' : '' %></span>
            </span>
            <div style="display:flex;gap:8px;align-items:center;">
                <div style="position:relative;" id="jt-dl-wrap">
                    <button onclick="toggleDlMenu()" style="background:#1565c0;color:#fff;border:none;border-radius:6px;padding:6px 14px;font-size:12px;font-weight:600;cursor:pointer;display:inline-flex;align-items:center;gap:5px;font-family:inherit;">
                        <span class="material-icons" style="font-size:15px;">download</span>Download
                    </button>
                    <div id="jt-dl-menu" style="display:none;position:absolute;right:0;top:calc(100% + 4px);background:#fff;border:1px solid #e0e0e0;border-radius:7px;box-shadow:0 4px 16px rgba(0,0,0,0.12);z-index:200;min-width:140px;overflow:hidden;">
                        <div onclick="downloadJobsCSV()" style="padding:10px 16px;font-size:13px;cursor:pointer;display:flex;align-items:center;gap:8px;color:#333;" onmouseover="this.style.background='#f5f5f5'" onmouseout="this.style.background=''">
                            <span class="material-icons" style="font-size:16px;color:#1565c0;">table_chart</span>Excel / CSV
                        </div>
                        <div onclick="downloadJobsPDF()" style="padding:10px 16px;font-size:13px;cursor:pointer;display:flex;align-items:center;gap:8px;color:#333;border-top:1px solid #f0f0f0;" onmouseover="this.style.background='#f5f5f5'" onmouseout="this.style.background=''">
                            <span class="material-icons" style="font-size:16px;color:#c62828;">picture_as_pdf</span>PDF
                        </div>
                    </div>
                </div>
                <button onclick="openJobSearchModal()" style="background:#28a745;color:#fff;border:none;border-radius:6px;padding:6px 14px;font-size:12px;font-weight:600;cursor:pointer;display:inline-flex;align-items:center;gap:5px;font-family:inherit;">
                    <span class="material-icons" style="font-size:15px;">search</span>Search Jobs
                </button>
            </div>
        </div>
        <div id="jt-empty" class="empty-state" style="<%= jobs.length ? 'display:none' : '' %>">No jobs tracked yet. Search jobs in the ecobot and save them to start tracking.</div>
        <table id="jt-table" class="job-table" style="<%= !jobs.length ? 'display:none' : '' %>">
            <thead>
                <tr>
                    <th class="jt-th" onclick="jtSort('title')">Role <span id="jt-sort-title" class="jt-sort-icon">↕</span></th>
                    <th class="jt-th" onclick="jtSort('company')">Company <span id="jt-sort-company" class="jt-sort-icon">↕</span></th>
                    <th class="jt-th" onclick="jtSort('location')">Location <span id="jt-sort-location" class="jt-sort-icon">↕</span></th>
                    <th class="jt-th" onclick="jtSort('status')">Status <span id="jt-sort-status" class="jt-sort-icon">↕</span></th>
                    <th class="jt-th" onclick="jtSort('foundAt')">Found <span id="jt-sort-foundAt" class="jt-sort-icon">↓</span></th>
                    <th class="jt-th" onclick="jtSort('appliedAt')">Applied <span id="jt-sort-appliedAt" class="jt-sort-icon">↕</span></th>
                    <th class="jt-th" onclick="jtSort('interviewDate')">Interview <span id="jt-sort-interviewDate" class="jt-sort-icon">↕</span></th>
                </tr>
            </thead>
            <tbody id="jt-tbody"></tbody>
        </table>
    </div>
</div>

<!-- ── HISTORY ── -->
<div id="tab-history" class="tab-pane">
    <div class="card">
        <div class="card-title"><span class="material-icons">history</span>Change History</div>
        <div id="changelogList"><div class="empty-state">Loading...</div></div>
    </div>
</div>

</div><!-- .portal-body -->

<!-- ── JOB MODAL ── -->
<div id="jobModal" class="jm-overlay" style="display:none" onclick="if(event.target===this)closeJobModal()">
  <div class="jm-panel">
    <div class="jm-header">
      <div>
        <div class="jm-title" id="jm-title"></div>
        <div class="jm-subtitle" id="jm-subtitle"></div>
      </div>
      <button class="jm-close" onclick="closeJobModal()">✕</button>
    </div>
    <div class="jm-body">
      <div style="display:flex;gap:8px;flex-wrap:wrap;">
        <button class="jm-gen-btn" id="jm-cv-btn" onclick="openCvModal('cv')">
          <span class="material-icons" style="font-size:14px;">description</span><span id="jm-cv-label">Create CV</span>
        </button>
        <button class="jm-gen-btn" id="jm-cl-btn" onclick="openCvModal('cover_letter')">
          <span class="material-icons" style="font-size:14px;">mail</span><span id="jm-cl-label">Create Cover Letter</span>
        </button>
        <button class="jm-gen-btn" id="jm-outreach-btn" onclick="runOutreach()">
          <span class="material-icons" style="font-size:14px;">people</span><span id="jm-outreach-label">Find Contacts</span>
        </button>
      </div>
      <div class="jm-field">
        <label>Status</label>
        <select id="jm-status" onchange="updateStatusSelectColor(this)" style="font-weight:600;transition:background 0.2s,color 0.2s;">
          <optgroup label="─── Declined ───────────────────">
            <option value="declined_not_interested"  style="background:#fce4ec;color:#c62828;">Declined · Not interested</option>
            <option value="declined_doesnt_qualify"  style="background:#fce4ec;color:#ad1457;">Declined · Doesn't qualify</option>
            <option value="declined_applied_before"  style="background:#fff3e0;color:#e65100;">Declined · Applied before</option>
            <option value="declined_position_closed" style="background:#fce4ec;color:#b71c1c;">Declined · Position closed</option>
            <option value="declined_no_answer"       style="background:#f3e5f5;color:#6a1b9a;">Declined · No answer</option>
          </optgroup>
          <optgroup label="─── In progress ────────────────">
            <option value="under_analysis"  style="background:#f5f5f5;color:#757575;">Under analysis</option>
            <option value="approved"        style="background:#e8eaf6;color:#3949ab;">Approved</option>
            <option value="in_preparation"  style="background:#e3f2fd;color:#1565c0;">In preparation</option>
            <option value="cv_in_drive"     style="background:#e0f2f1;color:#00695c;">CV in Drive</option>
            <option value="login_needed"    style="background:#fff8e1;color:#f57f17;">Login needed</option>
            <option value="applied"         style="background:#dbeafe;color:#1d4ed8;">Applied</option>
            <option value="interview"       style="background:#fff7ed;color:#c2410c;">Interview</option>
            <option value="offer_received"  style="background:#e8f5e9;color:#388e3c;">Offer received</option>
            <option value="offer_accepted"  style="background:#c8e6c9;color:#1b5e20;">Offer accepted</option>
          </optgroup>
        </select>
      </div>
      <div class="jm-row">
        <div class="jm-field">
          <label>Applied Date</label>
          <input type="date" id="jm-applied">
        </div>
        <div class="jm-field">
          <label>Interview Date</label>
          <input type="date" id="jm-interview-date">
        </div>
      </div>
      <div class="jm-row">
        <div class="jm-field">
          <label>Interview Type</label>
          <input type="text" id="jm-interview-type" placeholder="e.g. Phone, Video, On-site">
        </div>
        <div class="jm-field">
          <label>Offer Details</label>
          <input type="text" id="jm-offer" placeholder="Salary, conditions…">
        </div>
      </div>
      <div class="jm-field">
        <label>Notes</label>
        <textarea id="jm-notes" placeholder="Internal notes…"></textarea>
      </div>
      <div id="jm-outreach-section" style="display:none;margin-top:14px;">
        <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:8px;">
          <span style="font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:1px;color:#28a745;">Network Contacts</span>
          <span id="jm-outreach-status" style="font-size:11px;color:#aaa;"></span>
        </div>
        <div id="jm-outreach-results"></div>
      </div>

      <div id="jm-details-section" style="display:none">
        <button class="jm-details-toggle" id="jm-details-toggle" onclick="toggleJobDetails()">
          <span class="jm-toggle-arrow">▶</span> Job Details
        </button>
        <div class="jm-details-body" id="jm-details-body">
          <div id="jm-detail-url" class="jm-detail-row" style="display:none"><label>URL</label><span></span></div>
          <div id="jm-detail-source" class="jm-detail-row" style="display:none"><label>Source</label><span></span></div>
          <div id="jm-detail-found" class="jm-detail-row" style="display:none"><label>Found at</label><span></span></div>
          <div id="jm-detail-ai" style="display:none"><div class="jm-ai-reason" id="jm-detail-ai-text"></div></div>
          <div id="jm-detail-desc" style="display:none"><div class="jm-desc" id="jm-desc"></div></div>
        </div>
      </div>
    </div>
    <div class="jm-footer">
      <button class="jm-btn jm-btn-cancel" onclick="closeJobModal()">Cancel</button>
      <button class="jm-btn jm-btn-save" onclick="saveJobModal()">Save</button>
    </div>
  </div>
</div>

<script>
var _jobsData = <%- JSON.stringify(jobs) %>;
var _currentJobId = null;
var _slug = '<%= slug %>';

var STATUS_COLORS = {
  declined_not_interested:  { bg:'#fce4ec', color:'#c62828' },
  declined_doesnt_qualify:  { bg:'#fce4ec', color:'#ad1457' },
  declined_applied_before:  { bg:'#fff3e0', color:'#e65100' },
  declined_position_closed: { bg:'#fce4ec', color:'#b71c1c' },
  declined_no_answer:       { bg:'#f3e5f5', color:'#6a1b9a' },
  under_analysis:           { bg:'#f5f5f5', color:'#757575' },
  approved:                 { bg:'#e8eaf6', color:'#3949ab' },
  in_preparation:           { bg:'#e3f2fd', color:'#1565c0' },
  cv_in_drive:              { bg:'#e0f2f1', color:'#00695c' },
  login_needed:             { bg:'#fff8e1', color:'#f57f17' },
  applied:                  { bg:'#dbeafe', color:'#1d4ed8' },
  interview:                { bg:'#fff7ed', color:'#c2410c' },
  offer_received:           { bg:'#e8f5e9', color:'#388e3c' },
  offer_accepted:           { bg:'#c8e6c9', color:'#1b5e20' },
  proposed:                 { bg:'#f5f5f5', color:'#757575' },
  declined:                 { bg:'#fce4ec', color:'#c62828' },
  cv_requested:             { bg:'#e0f2f1', color:'#00695c' },
  offer:                    { bg:'#e8f5e9', color:'#388e3c' },
  rejected:                 { bg:'#fce4ec', color:'#c62828' },
  accepted:                 { bg:'#c8e6c9', color:'#1b5e20' }
};

var STATUS_LABELS = {
  declined_not_interested:  'Declined · Not interested',
  declined_doesnt_qualify:  'Declined · Doesn\'t qualify',
  declined_applied_before:  'Declined · Applied before',
  declined_position_closed: 'Declined · Position closed',
  declined_no_answer:       'Declined · No answer',
  under_analysis:           'Under analysis',
  approved:                 'Approved',
  in_preparation:           'In preparation',
  cv_in_drive:              'CV in Drive',
  login_needed:             'Login needed',
  applied:                  'Applied',
  interview:                'Interview',
  offer_received:           'Offer received',
  offer_accepted:           'Offer accepted',
  proposed:                 'Under analysis',
  declined:                 'Declined · Not interested',
  cv_requested:             'CV in Drive',
  offer:                    'Offer received',
  rejected:                 'Declined · No answer',
  accepted:                 'Offer accepted'
};

var STATUS_CLASS = {
  declined_not_interested:  'status-dec-not-interested',
  declined_doesnt_qualify:  'status-dec-doesnt-qualify',
  declined_applied_before:  'status-dec-applied-before',
  declined_position_closed: 'status-dec-position-closed',
  declined_no_answer:       'status-dec-no-answer',
  under_analysis:           'status-under-analysis',
  approved:                 'status-approved',
  in_preparation:           'status-in-preparation',
  cv_in_drive:              'status-cv-in-drive',
  login_needed:             'status-login-needed',
  applied:                  'status-applied',
  interview:                'status-interview',
  offer_received:           'status-offer-received',
  offer_accepted:           'status-offer-accepted',
  proposed:                 'status-under-analysis',
  declined:                 'status-dec-not-interested',
  cv_requested:             'status-cv-in-drive',
  offer:                    'status-offer-received',
  rejected:                 'status-dec-no-answer',
  accepted:                 'status-offer-accepted'
};

function escHtml(s) {
  return String(s || '').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}

var STATUS_ORDER = {
  offer_accepted: 0, accepted: 0,
  offer_received: 1, offer: 1,
  interview: 2,
  applied: 3,
  login_needed: 4,
  cv_in_drive: 5, cv_requested: 5,
  in_preparation: 6,
  approved: 7,
  proposed: 8, under_analysis: 8,
  declined_not_interested: 9, declined_doesnt_qualify: 9,
  declined_applied_before: 9, declined_position_closed: 9,
  declined_no_answer: 9, declined: 9, rejected: 9
};

var _jtSortCol = 'foundAt';
var _jtSortDir = -1;

function jtSort(col) {
  if (_jtSortCol === col) _jtSortDir = -_jtSortDir;
  else { _jtSortCol = col; _jtSortDir = 1; }
  renderJobTable();
}

function toggleDlMenu() {
  var m = document.getElementById('jt-dl-menu');
  m.style.display = m.style.display === 'none' ? 'block' : 'none';
}
document.addEventListener('click', function(e) {
  var wrap = document.getElementById('jt-dl-wrap');
  if (wrap && !wrap.contains(e.target)) {
    var m = document.getElementById('jt-dl-menu');
    if (m) m.style.display = 'none';
  }
});

function downloadJobsCSV() {
  document.getElementById('jt-dl-menu').style.display = 'none';
  var cols = ['title','company','location','status','foundAt','appliedAt','interviewDate','url','notes'];
  var header = ['Role','Company','Location','Status','Found','Applied','Interview','URL','Notes'];
  var rows = [header];
  _jobsData.forEach(function(j) {
    rows.push(cols.map(function(c) {
      var v = j[c] || '';
      if ((c === 'foundAt' || c === 'appliedAt' || c === 'interviewDate') && v) {
        try { v = new Date(v).toLocaleDateString(); } catch(e) {}
      }
      v = String(v).replace(/"/g, '""');
      return '"' + v + '"';
    }));
  });
  var csv = rows.map(function(r){ return r.join(','); }).join('\n');
  var blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
  var url = URL.createObjectURL(blob);
  var a = document.createElement('a'); a.href = url;
  a.download = 'job-tracking-' + SLUG + '.csv';
  document.body.appendChild(a); a.click(); document.body.removeChild(a);
  URL.revokeObjectURL(url);
}

function downloadJobsPDF() {
  document.getElementById('jt-dl-menu').style.display = 'none';
  var cols = ['title','company','location','status','foundAt','appliedAt','interviewDate'];
  var labels = ['Role','Company','Location','Status','Found','Applied','Interview'];
  var rows = _jobsData.map(function(j) {
    return cols.map(function(c) {
      var v = j[c] || '';
      if ((c === 'foundAt' || c === 'appliedAt' || c === 'interviewDate') && v) {
        try { v = new Date(v).toLocaleDateString(); } catch(e) {}
      }
      return v;
    });
  });
  var html = '<html><head><title>Job Tracking – ' + SLUG + '</title><style>'
    + 'body{font-family:sans-serif;font-size:12px;padding:24px;}'
    + 'h2{margin-bottom:16px;}'
    + 'table{width:100%;border-collapse:collapse;}'
    + 'th{text-align:left;padding:6px 10px;background:#f5f5f5;border-bottom:2px solid #ccc;font-size:11px;text-transform:uppercase;letter-spacing:0.5px;}'
    + 'td{padding:6px 10px;border-bottom:1px solid #eee;vertical-align:top;}'
    + 'tr:nth-child(even) td{background:#fafafa;}'
    + '</style></head><body>'
    + '<h2>Job Tracking — ' + SLUG + '</h2>'
    + '<table><thead><tr>' + labels.map(function(l){ return '<th>' + l + '</th>'; }).join('') + '</tr></thead>'
    + '<tbody>' + rows.map(function(r){ return '<tr>' + r.map(function(v){ return '<td>' + (v||'–') + '</td>'; }).join('') + '</tr>'; }).join('') + '</tbody>'
    + '</table></body></html>';
  var w = window.open('', '_blank');
  w.document.write(html);
  w.document.close();
  w.focus();
  w.print();
}

function renderJobTable() {
  var tbody = document.getElementById('jt-tbody');
  var empty = document.getElementById('jt-empty');
  var table = document.getElementById('jt-table');
  if (!tbody) return;

  var cols = ['title','company','location','status','foundAt','appliedAt','interviewDate'];
  cols.forEach(function(col) {
    var el = document.getElementById('jt-sort-' + col);
    if (!el) return;
    if (col === _jtSortCol) {
      el.textContent = _jtSortDir === 1 ? '↑' : '↓';
      el.style.color = '#28a745';
    } else {
      el.textContent = '↕';
      el.style.color = '#ccc';
    }
  });

  if (!_jobsData.length) {
    if (empty) empty.style.display = '';
    if (table) table.style.display = 'none';
    return;
  }
  if (empty) empty.style.display = 'none';
  if (table) table.style.display = '';

  var sorted = _jobsData.slice().sort(function(a, b) {
    var va, vb, r;
    if (_jtSortCol === 'status') {
      va = STATUS_ORDER[a.status] !== undefined ? STATUS_ORDER[a.status] : 8;
      vb = STATUS_ORDER[b.status] !== undefined ? STATUS_ORDER[b.status] : 8;
      r = va - vb;
    } else if (_jtSortCol === 'foundAt' || _jtSortCol === 'appliedAt' || _jtSortCol === 'interviewDate') {
      va = a[_jtSortCol] ? new Date(a[_jtSortCol]).getTime() : 0;
      vb = b[_jtSortCol] ? new Date(b[_jtSortCol]).getTime() : 0;
      r = va - vb;
    } else {
      va = (a[_jtSortCol] || '').toLowerCase();
      vb = (b[_jtSortCol] || '').toLowerCase();
      r = va < vb ? -1 : va > vb ? 1 : 0;
    }
    return r * _jtSortDir;
  });

  tbody.innerHTML = sorted.map(function(job) {
    var sc = STATUS_CLASS[job.status] || 'status-under-analysis';
    var sl = STATUS_LABELS[job.status] || job.status || '—';
    var fDate = job.foundAt ? new Date(job.foundAt).toLocaleDateString('en-GB',{day:'2-digit',month:'short'}) : '—';
    var aDate = job.appliedAt ? new Date(job.appliedAt).toLocaleDateString('en-GB',{day:'2-digit',month:'short'}) : '—';
    var iDate = job.interviewDate ? new Date(job.interviewDate).toLocaleDateString('en-GB',{day:'2-digit',month:'short'}) : (job.interviewScheduled ? '✓' : '—');
    var titleCell = job.url
      ? '<a href="' + escHtml(job.url) + '" target="_blank" rel="noopener" style="color:#28a745;text-decoration:none;font-weight:500;" onclick="event.stopPropagation()">' + escHtml(job.title) + '</a>'
      : '<span style="font-weight:500;color:#333">' + escHtml(job.title) + '</span>';
    return '<tr onclick="openJobModal(\'' + escHtml(job.id) + '\')">' +
      '<td>' + titleCell + '</td>' +
      '<td>' + escHtml(job.company || '—') + '</td>' +
      '<td style="color:#888;font-size:12px;">' + escHtml(job.location || '—') + '</td>' +
      '<td><span class="job-status ' + sc + '">' + escHtml(sl) + '</span></td>' +
      '<td style="color:#bbb;font-size:12px;">' + fDate + '</td>' +
      '<td style="color:#bbb;font-size:12px;">' + aDate + '</td>' +
      '<td style="color:#bbb;font-size:12px;">' + iDate + '</td>' +
      '</tr>';
  }).join('');
}

document.addEventListener('DOMContentLoaded', renderJobTable);

function updateStatusSelectColor(sel) {
  var c = STATUS_COLORS[sel.value] || { bg:'#f5f5f5', color:'#757575' };
  sel.style.background = c.bg;
  sel.style.color = c.color;
}

function openJobModal(jobId) {
  var job = _jobsData.find(function(j){ return j.id === jobId; });
  if (!job) return;
  _currentJobId = jobId;

  document.getElementById('jm-title').textContent = job.title || '—';
  document.getElementById('jm-subtitle').textContent = [job.company, job.location].filter(Boolean).join(' · ');
  var statusSel = document.getElementById('jm-status');
  statusSel.value = job.status || 'under_analysis';
  if (!statusSel.value) statusSel.value = 'under_analysis';
  updateStatusSelectColor(statusSel);
  document.getElementById('jm-applied').value = job.appliedAt ? job.appliedAt.slice(0,10) : '';
  document.getElementById('jm-interview-date').value = job.interviewDate ? job.interviewDate.slice(0,10) : '';
  document.getElementById('jm-interview-type').value = job.interviewType || '';
  document.getElementById('jm-offer').value = job.offerDetails || '';
  document.getElementById('jm-notes').value = job.notes || '';

  var hasDetails = false;

  function _setDetail(id, value, render) {
    var row = document.getElementById(id);
    if (value) { render(row, value); row.style.display = ''; hasDetails = true; }
    else { row.style.display = 'none'; }
  }

  _setDetail('jm-detail-url', job.url, function(row, v) {
    row.querySelector('span').innerHTML = '<a href="' + v + '" target="_blank" rel="noopener">' + v + '</a>';
  });
  _setDetail('jm-detail-source', job.source, function(row, v) {
    row.querySelector('span').textContent = v;
  });
  _setDetail('jm-detail-found', job.foundAt, function(row, v) {
    row.querySelector('span').textContent = new Date(v).toLocaleDateString();
  });
  _setDetail('jm-detail-ai', job.aiReason, function(row, v) {
    document.getElementById('jm-detail-ai-text').textContent = '🤖 ' + v;
  });
  _setDetail('jm-detail-desc', job.description, function(row, v) {
    document.getElementById('jm-desc').textContent = v;
  });

  var detailsSection = document.getElementById('jm-details-section');
  var detailsBody = document.getElementById('jm-details-body');
  var detailsToggle = document.getElementById('jm-details-toggle');
  if (hasDetails) {
    detailsSection.style.display = '';
    detailsBody.classList.remove('open');
    detailsToggle.classList.remove('open');
  } else {
    detailsSection.style.display = 'none';
  }

  // Update CV/CL button labels
  document.getElementById('jm-cv-label').textContent = job.generatedCv ? 'Edit CV' : 'Create CV';
  document.getElementById('jm-cl-label').textContent = job.generatedCoverLetter ? 'Edit Cover Letter' : 'Create Cover Letter';

  // Show saved outreach contacts if any
  var outreachSection = document.getElementById('jm-outreach-section');
  var outreachResults = document.getElementById('jm-outreach-results');
  var outreachStatus  = document.getElementById('jm-outreach-status');
  document.getElementById('jm-outreach-label').textContent = 'Find Contacts';
  if (job.outreachContacts && job.outreachContacts.length) {
    outreachSection.style.display = '';
    var ran = job.outreachRunAt ? new Date(job.outreachRunAt).toLocaleDateString() : '';
    outreachStatus.textContent = ran ? 'last run ' + ran : '';
    outreachResults.innerHTML = _renderOutreachCards(job.outreachContacts);
    document.getElementById('jm-outreach-label').textContent = 'Refresh Contacts';
  } else {
    outreachSection.style.display = 'none';
    outreachResults.innerHTML = '';
    outreachStatus.textContent = '';
  }

  var _jmEl = document.getElementById('jobModal');
  _jmEl.style.display = 'flex';
  requestAnimationFrame(function(){ requestAnimationFrame(function(){ _jmEl.classList.add('is-open'); }); });
}

function closeJobModal() {
  var _jmEl = document.getElementById('jobModal');
  _jmEl.classList.remove('is-open');
  _jmEl.addEventListener('transitionend', function _h(e){ if(e.target===_jmEl&&e.propertyName==='opacity'){ _jmEl.style.display='none'; _jmEl.removeEventListener('transitionend',_h); } });
  _currentJobId = null;
}

function toggleJobDetails() {
  var body = document.getElementById('jm-details-body');
  var toggle = document.getElementById('jm-details-toggle');
  var isOpen = body.classList.contains('open');
  body.classList.toggle('open', !isOpen);
  toggle.classList.toggle('open', !isOpen);
}

// ── Outreach ─────────────────────────────────────────────────────────────────
function _renderOutreachCards(contacts) {
  return contacts.map(function(c) {
    var scoreColor = c.score >= 80 ? '#28a745' : c.score >= 60 ? '#f57f17' : '#aaa';
    var html = '<div class="outreach-card">';
    html += '<div class="outreach-card-head">';
    html += '<span class="outreach-card-name">' + escHtml(c.name) + '</span>';
    html += '<span class="outreach-card-score" style="background:' + scoreColor + '20;color:' + scoreColor + ';">' + c.score + '%</span>';
    if (c.linkedin_url) html += '<a class="outreach-card-link" href="' + escHtml(c.linkedin_url) + '" target="_blank">LinkedIn ↗</a>';
    html += '</div>';
    html += '<div class="outreach-card-title">' + escHtml(c.title) + (c.location ? ' · <span class="outreach-card-loc">' + escHtml(c.location) + '</span>' : '') + '</div>';
    if (c.draft_message) html += '<div class="outreach-card-msg">"' + escHtml(c.draft_message) + '"</div>';
    html += '</div>';
    return html;
  }).join('');
}

async function runOutreach() {
  if (!_currentJobId) return;
  var btn = document.getElementById('jm-outreach-btn');
  var label = document.getElementById('jm-outreach-label');
  var section = document.getElementById('jm-outreach-section');
  var results = document.getElementById('jm-outreach-results');
  var status  = document.getElementById('jm-outreach-status');

  btn.disabled = true;
  label.textContent = 'Searching…';
  section.style.display = '';
  status.textContent = 'contacting outreach service…';
  results.innerHTML = '<div style="font-size:12px;color:#aaa;padding:10px 0;"><span class="spinner"></span> Finding contacts, this may take ~90 seconds…</div>';

  try {
    var r = await fetch('/admin/api/profile/' + _slug + '/jobtracking/' + _currentJobId + '/outreach', {
      method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{}'
    });
    var data = await r.json();
    if (!r.ok) throw new Error(data.error || 'Request failed');

    var contacts = data.contacts || [];
    var job = _jobsData.find(function(j){ return j.id === _currentJobId; });
    if (job) {
      job.outreachContacts = contacts;
      job.outreachRunAt = new Date().toISOString();
    }

    if (!contacts.length) {
      results.innerHTML = '<p style="font-size:12px;color:#aaa;">No contacts found.</p>';
      status.textContent = '';
    } else {
      results.innerHTML = _renderOutreachCards(contacts);
      status.textContent = 'found ' + contacts.length;
    }
    label.textContent = 'Refresh Contacts';
  } catch (e) {
    results.innerHTML = '<p style="font-size:12px;color:#c62828;">Error: ' + escHtml(e.message) + '</p>';
    status.textContent = '';
    label.textContent = 'Find Contacts';
  } finally {
    btn.disabled = false;
  }
}

// ── A4 CV / Cover Letter modal ──────────────────────────────────────────────
var _cvaHistory = [];
var _cvaHistoryIdx = -1;
var _cvaType = null;

function openCvModal(type) {
  _cvaType = type;
  _cvaHistory = [];
  _cvaHistoryIdx = -1;
  document.getElementById('cva-title').textContent = type === 'cv' ? 'Curriculum Vitae' : 'Cover Letter';
  var _cvEl = document.getElementById('cv-a4-modal');
  _cvEl.style.display = 'flex';
  requestAnimationFrame(function(){ requestAnimationFrame(function(){ _cvEl.classList.add('is-open'); }); });
  document.getElementById('cva-instruction').value = '';
  _cvaUpdateNavBtns();

  var job = _jobsData.find(function(j){ return j.id === _currentJobId; });
  var existing = job && (type === 'cv' ? job.generatedCv : job.generatedCoverLetter);
  if (existing) {
    _cvaPushHistory(existing);
    showCvContent(existing);
  } else {
    generateCvDoc(false);
  }
}

function closeCvModal() {
  var _cvEl = document.getElementById('cv-a4-modal');
  _cvEl.classList.remove('is-open');
  _cvEl.addEventListener('transitionend', function _h(e){ if(e.target===_cvEl&&e.propertyName==='opacity'){ _cvEl.style.display='none'; _cvEl.removeEventListener('transitionend',_h); } });
  _cvaType = null;
  _cvaHistory = [];
  _cvaHistoryIdx = -1;
}

function showCvContent(html) {
  document.getElementById('cva-loading').style.display = 'none';
  var paper = document.getElementById('cva-paper');
  paper.style.display = '';
  paper.innerHTML = html;
}

function showCvaLoading() {
  document.getElementById('cva-loading').style.display = 'flex';
  document.getElementById('cva-paper').style.display = 'none';
}

function _cvaPushHistory(html) {
  _cvaHistory = _cvaHistory.slice(0, _cvaHistoryIdx + 1);
  _cvaHistory.push(html);
  _cvaHistoryIdx = _cvaHistory.length - 1;
  _cvaUpdateNavBtns();
}

function _cvaUpdateNavBtns() {
  document.getElementById('cva-undo-btn').disabled = _cvaHistoryIdx <= 0;
  document.getElementById('cva-redo-btn').disabled = _cvaHistoryIdx >= _cvaHistory.length - 1;
}

function undoCv() {
  if (_cvaHistoryIdx <= 0) return;
  _cvaHistoryIdx--;
  showCvContent(_cvaHistory[_cvaHistoryIdx]);
  _cvaUpdateNavBtns();
}

function redoCv() {
  if (_cvaHistoryIdx >= _cvaHistory.length - 1) return;
  _cvaHistoryIdx++;
  showCvContent(_cvaHistory[_cvaHistoryIdx]);
  _cvaUpdateNavBtns();
}

async function generateCvDoc(isRegen) {
  if (!_currentJobId || !_cvaType) return;
  showCvaLoading();
  var regenBtn = document.getElementById('cva-regen-btn');
  if (regenBtn) regenBtn.disabled = true;

  var maxAttempts = 3;
  var lastErr = null;
  for (var attempt = 1; attempt <= maxAttempts; attempt++) {
    try {
      if (attempt > 1) {
        var loadingEl = document.getElementById('cva-loading');
        var loadingMsg = loadingEl && loadingEl.querySelector('div');
        if (loadingMsg) loadingMsg.textContent = 'Retrying… (attempt ' + attempt + ')';
        await new Promise(function(res){ setTimeout(res, 1500); });
      }
      var r = await fetch(BASE + '/api/profile/' + _slug + '/jobtracking/' + _currentJobId + '/generate', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ type: _cvaType })
      });
      var data = await r.json();
      if (!data.success) throw new Error(data.error || 'Generation failed');
      _cvaPushHistory(data.content);
      showCvContent(data.content);
      var job = _jobsData.find(function(j){ return j.id === _currentJobId; });
      if (job) {
        if (_cvaType === 'cv') { job.generatedCv = data.content; document.getElementById('jm-cv-label').textContent = 'Edit CV'; }
        else { job.generatedCoverLetter = data.content; document.getElementById('jm-cl-label').textContent = 'Edit Cover Letter'; }
      }
      lastErr = null;
      break; // success
    } catch(e) {
      lastErr = e;
      // Only retry on network errors (fetch threw), not on server 4xx/5xx which returned JSON
      var isNetworkErr = e instanceof TypeError;
      if (!isNetworkErr || attempt === maxAttempts) break;
    }
  }

  if (lastErr) {
    document.getElementById('cva-loading').style.display = 'none';
    var paper = document.getElementById('cva-paper');
    paper.style.display = '';
    paper.innerHTML = '<p style="color:red;">Error: ' + lastErr.message + '</p>';
  }
  if (regenBtn) regenBtn.disabled = false;
}

async function applyCvChange() {
  if (!_currentJobId || !_cvaType) return;
  var instruction = document.getElementById('cva-instruction').value.trim();
  if (!instruction) return;
  var currentContent = document.getElementById('cva-paper').innerHTML;
  var applyBtn = document.getElementById('cva-apply-btn');
  applyBtn.disabled = true;
  applyBtn.innerHTML = '<span class="material-icons" style="font-size:14px;">hourglass_empty</span>Applying…';

  try {
    var r = await fetch(BASE + '/api/profile/' + _slug + '/jobtracking/' + _currentJobId + '/refine', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ type: _cvaType, instruction: instruction, currentContent: currentContent })
    });
    var data = await r.json();
    if (!data.success) throw new Error(data.error || 'Refine failed');
    _cvaPushHistory(data.content);
    showCvContent(data.content);
    document.getElementById('cva-instruction').value = '';
    var job = _jobsData.find(function(j){ return j.id === _currentJobId; });
    if (job) {
      if (_cvaType === 'cv') job.generatedCv = data.content;
      else job.generatedCoverLetter = data.content;
    }
  } catch(e) {
    alert('Error: ' + e.message);
  } finally {
    applyBtn.disabled = false;
    applyBtn.innerHTML = '<span class="material-icons" style="font-size:14px;">auto_fix_high</span>Apply';
  }
}

async function saveCvModal() {
  if (!_currentJobId || !_cvaType) return;
  var html = document.getElementById('cva-paper').innerHTML;
  var field = _cvaType === 'cv' ? 'generatedCv' : 'generatedCoverLetter';
  var btn = document.getElementById('cva-save-btn');
  btn.innerHTML = '<span class="material-icons" style="font-size:14px;">hourglass_empty</span>Saving…';
  btn.disabled = true;

  try {
    var r = await fetch(BASE + '/api/profile/' + _slug + '/jobtracking/' + _currentJobId, {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ [field]: html })
    });
    var data = await r.json();
    if (!data.success) throw new Error(data.error || 'Save failed');
    var job = _jobsData.find(function(j){ return j.id === _currentJobId; });
    if (job) job[field] = html;
    btn.innerHTML = '<span class="material-icons" style="font-size:14px;">check</span>Saved!';
    setTimeout(function(){ btn.innerHTML = '<span class="material-icons" style="font-size:14px;">save</span>Save'; btn.disabled = false; }, 1500);
  } catch(e) {
    alert('Error: ' + e.message);
    btn.innerHTML = '<span class="material-icons" style="font-size:14px;">save</span>Save';
    btn.disabled = false;
  }
}

function copyCvModal(btnEl) {
  var html = document.getElementById('cva-paper').innerHTML;
  if (!html) return;
  navigator.clipboard.writeText(html).then(function() {
    var orig = btnEl.innerHTML;
    btnEl.innerHTML = '<span class="material-icons" style="font-size:14px;">check</span>Copied!';
    setTimeout(function(){ btnEl.innerHTML = orig; }, 1500);
  }).catch(function() {
    var ta = document.createElement('textarea');
    ta.value = html; document.body.appendChild(ta); ta.select();
    document.execCommand('copy'); document.body.removeChild(ta);
  });
}

function _cvPrintHtml(content, title) {
  return '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>' + (title || 'Document') + '</title>' +
    '<link href="https://fonts.googleapis.com/css2?family=Ubuntu:wght@300;400;500;700&display=swap" rel="stylesheet">' +
    '<style>' +
    '*{box-sizing:border-box;}html,body{margin:0;padding:0;}' +
    'body{background:#fff;padding:15mm 18mm;box-decoration-break:clone;-webkit-box-decoration-break:clone;font-family:Ubuntu,Arial,sans-serif;-webkit-print-color-adjust:exact;print-color-adjust:exact;orphans:3;widows:3;}' +
    /* margin:0 → sem URL/número de página do browser.
       box-decoration-break:clone → padding repete-se em TODAS as páginas incluindo pág 2+. */
    '@page{size:A4;margin:0;}' +
    'h1,h2,h3,h4,h5,h6{break-after:avoid;page-break-after:avoid;break-inside:avoid;page-break-inside:avoid;}' +
    'p{orphans:3;widows:3;}' +
    'li{break-inside:avoid;page-break-inside:avoid;}' +
    'h2+*,h3+*{break-before:avoid;page-break-before:avoid;}' +
    '</style>' +
    '</head><body>' + content + '</body></html>';
}

function printCvModal() {
  var content = document.getElementById('cva-paper').innerHTML;
  if (!content) return;
  var title = document.getElementById('cva-title').textContent || 'Document';
  var iframe = document.createElement('iframe');
  iframe.style.cssText = 'position:fixed;left:-9999px;top:-9999px;width:210mm;height:297mm;border:none;';
  document.body.appendChild(iframe);
  iframe.contentDocument.open();
  iframe.contentDocument.write(_cvPrintHtml(content, title));
  iframe.contentDocument.close();

  var iDoc = iframe.contentDocument;

  // 1. Headings: never break after, keep glued to next element
  iDoc.querySelectorAll('h1,h2,h3,h4,h5,h6').forEach(function(el) {
    el.style.breakAfter = 'avoid';
    el.style.pageBreakAfter = 'avoid';
    el.style.breakInside = 'avoid';
    el.style.pageBreakInside = 'avoid';
    var next = el.nextElementSibling;
    if (next) { next.style.breakBefore = 'avoid'; next.style.pageBreakBefore = 'avoid'; }
  });

  // 2. Job entry wrappers: new CVs have break-inside in inline style already (from prompt).
  //    For older CVs without wrapper, detect the pattern: bold div followed by italic div + ul
  //    and wrap them on-the-fly.
  iDoc.querySelectorAll('div').forEach(function(el) {
    var s = el.getAttribute('style') || '';
    var isBoldDiv = s.indexOf('font-weight:700') !== -1 || s.indexOf('font-weight: 700') !== -1;
    if (!isBoldDiv) return;
    // Check it's a leaf-ish job title (no nested h2/h3 section headers)
    if (el.querySelectorAll('h2,h3').length > 0) return;
    // Collect this node + next siblings until the next bold div or h2
    var nodes = [el];
    var sib = el.nextElementSibling;
    while (sib && sib.tagName !== 'H2' && sib.tagName !== 'H3') {
      var sibS = sib.getAttribute('style') || '';
      if (sibS.indexOf('font-weight:700') !== -1 || sibS.indexOf('font-weight: 700') !== -1) break;
      nodes.push(sib);
      sib = sib.nextElementSibling;
      // Stop after ul/ol (end of this entry's bullets)
      if (nodes.length > 1 && (nodes[nodes.length-1].tagName === 'UL' || nodes[nodes.length-1].tagName === 'OL')) break;
    }
    if (nodes.length < 2) return; // not a job entry pattern
    // Wrap in a break-inside:avoid container
    var wrapper = iDoc.createElement('div');
    wrapper.style.cssText = 'break-inside:avoid;page-break-inside:avoid;';
    el.parentNode.insertBefore(wrapper, el);
    nodes.forEach(function(n) { wrapper.appendChild(n); });
  });

  // 3. List items and table rows: avoid breaking mid-item
  iDoc.querySelectorAll('li,tr').forEach(function(el) {
    el.style.breakInside = 'avoid';
    el.style.pageBreakInside = 'avoid';
  });
  iframe.contentWindow.focus();
  setTimeout(function() {
    iframe.contentWindow.print();
    setTimeout(function() { document.body.removeChild(iframe); }, 1500);
  }, 600);
}

function toggleCvaDownloadMenu(e) {
  e.stopPropagation();
  var menu = document.getElementById('cva-download-menu');
  menu.style.display = menu.style.display === 'none' ? 'block' : 'none';
}
document.addEventListener('click', function() {
  var menu = document.getElementById('cva-download-menu');
  if (menu) menu.style.display = 'none';
});

function downloadCvModal(format) {
  var menu = document.getElementById('cva-download-menu');
  if (menu) menu.style.display = 'none';
  var content = document.getElementById('cva-paper').innerHTML;
  if (!content) return;
  var rawTitle = (document.getElementById('cva-title').textContent || 'document').trim();
  var fileName = rawTitle.replace(/[^a-z0-9\-_\s]/gi, '').replace(/\s+/g, '-').toLowerCase() || 'document';

  if (format === 'pdf') {
    var btn = document.getElementById('cva-download-btn');
    btn.disabled = true; btn.style.opacity = '0.6';
    function _doHtml2Pdf() {
      var el = document.getElementById('cva-paper');
      html2pdf().set({
        margin: [15, 18, 15, 18],
        filename: fileName + '.pdf',
        image: { type: 'jpeg', quality: 0.97 },
        html2canvas: { scale: 2, useCORS: true, letterRendering: true },
        jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' },
        pagebreak: { mode: ['avoid-all', 'css'] }
      }).from(el).save().then(function() {
        btn.disabled = false; btn.style.opacity = '1';
      }).catch(function() {
        btn.disabled = false; btn.style.opacity = '1';
      });
    }
    if (typeof html2pdf === 'undefined') {
      var s = document.createElement('script');
      s.src = 'https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js';
      s.onload = _doHtml2Pdf;
      document.head.appendChild(s);
    } else {
      _doHtml2Pdf();
    }

  } else if (format === 'docx') {
    var btn2 = document.getElementById('cva-download-btn');
    btn2.disabled = true; btn2.style.opacity = '0.6';
    function _doDocx() {
      var fullHtml = '<!DOCTYPE html><html><head><meta charset="UTF-8">' +
        '<style>body{font-family:Arial,sans-serif;padding:20pt 24pt;}p,li,h1,h2,h3,h4{margin:0 0 6pt;}</style>' +
        '</head><body>' + document.getElementById('cva-paper').innerHTML + '</body></html>';
      var blob = htmlDocx.asBlob(fullHtml);
      var url = URL.createObjectURL(blob);
      var a = document.createElement('a');
      a.href = url; a.download = fileName + '.docx';
      document.body.appendChild(a); a.click();
      document.body.removeChild(a);
      setTimeout(function() { URL.revokeObjectURL(url); }, 1000);
      btn2.disabled = false; btn2.style.opacity = '1';
    }
    if (typeof htmlDocx === 'undefined') {
      var s2 = document.createElement('script');
      s2.src = 'https://cdnjs.cloudflare.com/ajax/libs/html-docx-js/0.3.1/html-docx.js';
      s2.onload = _doDocx;
      document.head.appendChild(s2);
    } else {
      _doDocx();
    }
  }
}

function saveJobModal() {
  if (!_currentJobId) return;
  var btn = document.querySelector('.jm-btn-save');
  btn.textContent = 'Saving…'; btn.disabled = true;

  var applied = document.getElementById('jm-applied').value;
  var interviewDate = document.getElementById('jm-interview-date').value;

  var updates = {
    status:            document.getElementById('jm-status').value,
    appliedAt:         applied ? new Date(applied).toISOString() : null,
    interviewDate:     interviewDate ? new Date(interviewDate).toISOString() : null,
    interviewType:     document.getElementById('jm-interview-type').value || null,
    interviewScheduled: !!interviewDate,
    offerDetails:      document.getElementById('jm-offer').value || null,
    offerReceived:     ['offer_received','offer_accepted','offer','accepted'].indexOf(document.getElementById('jm-status').value) !== -1,
    notes:             document.getElementById('jm-notes').value,
  };

  fetch('/admin/api/profile/' + _slug + '/jobtracking/' + _currentJobId, {
    method: 'PATCH',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(updates),
  })
  .then(function(r){ return r.json(); })
  .then(function(data){
    if (data.success) {
      // Update local jobs array so table reflects changes without reload
      var job = _jobsData.find(function(j){ return j.id === _currentJobId; });
      if (job) Object.assign(job, updates);
      // Refresh the status badge in the table row
      refreshJobRow(_currentJobId, updates.status);
      closeJobModal();
    } else {
      alert('Error: ' + (data.error || 'unknown'));
    }
  })
  .catch(function(e){ alert('Request failed: ' + e.message); })
  .finally(function(){ btn.textContent = 'Save'; btn.disabled = false; });
}

function refreshJobRow(jobId, newStatus) {
  var job = _jobsData.find(function(j){ return j.id === jobId; });
  if (job) job.status = newStatus;
  renderJobTable();
}
</script>

<!-- ── JOB SEARCH MODAL ── -->
<div id="jsModal" class="jm-overlay" style="display:none" onclick="if(event.target===this)closeJsModal()">
  <div class="jm-panel" style="max-width:680px;">

    <!-- Stage: Input -->
    <div id="js-stage-input">
      <div class="jm-header">
        <div>
          <div class="jm-title"><span class="material-icons" style="vertical-align:middle;font-size:17px;margin-right:4px;">auto_awesome</span>Search Jobs with AI</div>
          <div class="jm-subtitle">TheirStack, LinkedIn, Indeed & Glassdoor — AI screens each result against career strategy</div>
        </div>
        <button class="jm-close" onclick="closeJsModal()">✕</button>
      </div>
      <div class="jm-body">
        <div id="js-search-preview" style="font-size:13px;color:#444;line-height:2;background:#f9fdf9;border:1px solid #d4edda;border-radius:6px;padding:14px 16px;"></div>
      </div>
      <div class="jm-footer">
        <button class="jm-btn jm-btn-cancel" onclick="closeJsModal()">Cancel</button>
        <button class="jm-btn jm-btn-save" onclick="runJobSearch()" id="js-search-btn">
          <span class="material-icons" style="font-size:15px;vertical-align:middle;">search</span> Search Jobs
        </button>
      </div>
    </div>

    <!-- Stage: Loading -->
    <div id="js-stage-loading" style="display:none">
      <div class="jm-header">
        <div class="jm-title">Searching...</div>
        <button class="jm-close" onclick="closeJsModal()">✕</button>
      </div>
      <div class="jm-body" style="align-items:center;text-align:center;padding:48px 24px;">
        <div class="js-spinner"></div>
        <div id="js-status" style="font-size:14px;color:#444;margin-top:18px;font-weight:500;">Connecting to job boards...</div>
        <div id="js-substatus" style="font-size:12px;color:#aaa;margin-top:6px;">LinkedIn · Indeed · Glassdoor</div>
      </div>
    </div>

    <!-- Stage: Results -->
    <div id="js-stage-results" style="display:none">
      <div class="jm-header">
        <div>
          <div class="jm-title">AI-Screened Jobs</div>
          <div class="jm-subtitle" id="js-results-subtitle" style="line-height:1.6;"></div>
        </div>
        <button class="jm-close" onclick="closeJsModal()">✕</button>
      </div>
      <div id="js-jobs-list" style="padding:12px 24px;display:flex;flex-direction:column;gap:10px;"></div>
      <!-- Filtered by AI -->
      <div id="js-rejected-wrap" style="display:none;border-top:1px solid #f5f5f5;">
        <button onclick="toggleRejectedSection()" style="padding:8px 24px;background:none;border:none;color:#aaa;font-size:12px;cursor:pointer;display:flex;align-items:center;gap:4px;font-family:inherit;width:100%;text-align:left;">
          <span class="material-icons" style="font-size:14px;">filter_list_off</span>
          <span id="js-rejected-label">0 filtered by AI</span>
          <span class="material-icons" id="js-rejected-chevron" style="font-size:14px;margin-left:auto;">expand_more</span>
        </button>
        <div id="js-rejected-body" style="display:none;padding:0 24px 8px;"></div>
      </div>
      <!-- Expand / Refine search -->
      <div id="js-expand-wrap" style="border-top:1px solid #f0f0f0;padding:10px 24px;">
        <button onclick="toggleExpandPanel()" id="js-expand-toggle" style="background:none;border:none;color:#28a745;font-size:12px;font-weight:600;cursor:pointer;display:inline-flex;align-items:center;gap:4px;font-family:inherit;padding:0;">
          <span class="material-icons" style="font-size:15px;">tune</span> Expand / Refine search
        </button>
        <div id="js-expand-body" style="display:none;margin-top:10px;">
          <textarea id="js-expand-input" rows="2" placeholder='e.g. "search in Canada as well" or "broaden to VP level too"' style="width:100%;box-sizing:border-box;border:1px solid #ddd;border-radius:5px;padding:8px 10px;font-size:13px;font-family:inherit;resize:none;transition:border-color 0.15s;" onfocus="this.style.borderColor='#28a745'" onblur="this.style.borderColor='#ddd'"></textarea>
          <div style="display:flex;justify-content:space-between;align-items:center;margin-top:8px;">
            <div id="js-expand-status" style="font-size:12px;color:#888;flex:1;margin-right:10px;"></div>
            <button id="js-expand-btn" onclick="runExpandSearch()" class="jm-btn jm-btn-save" style="padding:6px 16px;font-size:12px;white-space:nowrap;">
              <span class="material-icons" style="font-size:14px;vertical-align:middle;">search</span> Re-search
            </button>
          </div>
        </div>
      </div>
      <div class="jm-footer" style="justify-content:space-between;align-items:center;">
        <span id="js-decision-count" style="font-size:12px;color:#aaa;"></span>
        <div style="display:flex;gap:10px;">
          <button class="jm-btn jm-btn-cancel" onclick="closeJsModal()">Cancel</button>
          <button class="jm-btn jm-btn-save" id="js-apply-btn" onclick="applyJobDecisions()">Apply decisions</button>
        </div>
      </div>
    </div>

    <!-- Stage: Done -->
    <div id="js-stage-done" style="display:none">
      <div class="jm-header">
        <div class="jm-title">Done!</div>
        <button class="jm-close" onclick="location.reload()">✕</button>
      </div>
      <div class="jm-body" style="text-align:center;padding:40px 24px;align-items:center;">
        <span class="material-icons" style="font-size:52px;color:#28a745;">check_circle</span>
        <div id="js-done-msg" style="font-size:15px;font-weight:600;color:#333;margin-top:14px;"></div>
        <div id="js-strategy-update" style="display:none;margin-top:16px;background:#f0faf2;border:1px solid #c3e6cb;border-radius:8px;padding:14px;font-size:13px;color:#2e7d32;text-align:left;width:100%;box-sizing:border-box;"></div>
      </div>
      <div class="jm-footer" style="justify-content:flex-end;">
        <button class="jm-btn jm-btn-save" onclick="location.reload()">Refresh page</button>
      </div>
    </div>

  </div>
</div>

<!-- Save bar -->
<div class="save-bar" id="saveBar">
    <span style="font-size:13px;color:#555;margin-right:8px;">Unsaved changes</span>
    <button class="btn-cancel" onclick="cancelEdit()">Cancel</button>
    <button class="btn-save" onclick="saveChanges()"><span class="material-icons" style="font-size:16px;">save</span>Save</button>
</div>

<script>
    // ── Tab switching ──
    function showTab(name, btn) {
        document.querySelectorAll('.tab-pane').forEach(function(p){ p.classList.remove('active'); });
        document.querySelectorAll('.tab-btn').forEach(function(b){ b.classList.remove('active'); });
        var pane = document.getElementById('tab-' + name);
        if (pane) pane.classList.add('active');
        btn.classList.add('active');
        if (name === 'history') loadChangelog();
    }

    // ── Editable fields ──
    var hasChanges = false;
    var originalData = {};

    document.querySelectorAll('.editable-field').forEach(function(field) {
        var key = (field.dataset.file || 'cs') + ':' + field.dataset.field;
        originalData[key] = field.textContent.trim();

        field.addEventListener('focus', function(){ this.classList.add('editing'); });
        field.addEventListener('blur', function(){
            this.classList.remove('editing');
            if (this.textContent.trim() !== originalData[key]) markChanged();
        });
        field.addEventListener('keydown', function(e){
            if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); this.blur(); }
        });
    });

    document.querySelectorAll('.tag-input-container').forEach(function(container) {
        var key = (container.dataset.file || 'cs') + ':' + container.dataset.field;
        originalData[key] = Array.from(container.querySelectorAll('.tag')).map(function(t){ return t.firstChild.textContent.trim(); });

        var input = document.createElement('input');
        input.type = 'text'; input.className = 'tag-input'; input.placeholder = 'Add…';
        container.appendChild(input);

        container.addEventListener('click', function(e) {
            if (e.target.classList.contains('remove-tag')) { e.target.closest('.tag').remove(); markChanged(); }
            else if (e.target !== input) input.focus();
        });

        input.addEventListener('keydown', function(e) {
            if (e.key === 'Enter' || e.key === ',') {
                e.preventDefault();
                var val = this.value.replace(/,/g,'').trim();
                if (val) { addTag(container, input, val); this.value = ''; markChanged(); }
            } else if (e.key === 'Backspace' && this.value === '') {
                var tags = container.querySelectorAll('.tag');
                if (tags.length) { tags[tags.length-1].remove(); markChanged(); }
            }
        });
        input.addEventListener('input', function() {
            if (this.value.includes(',')) {
                var parts = this.value.split(','); var last = parts.pop().trim();
                parts.map(function(v){ return v.trim(); }).filter(Boolean).forEach(function(v){ addTag(container, input, v); });
                this.value = last; markChanged();
            }
        });
        input.addEventListener('paste', function(e) {
            e.preventDefault();
            var pasted = (e.clipboardData || window.clipboardData).getData('text');
            pasted.split(/[,\n]+/).map(function(v){ return v.trim(); }).filter(Boolean).forEach(function(v){ addTag(container, input, v); });
            this.value = ''; markChanged();
        });
    });

    function addTag(container, input, value) {
        var tag = document.createElement('span'); tag.className = 'tag';
        var tn = document.createTextNode(value);
        var rm = document.createElement('span'); rm.className = 'remove-tag'; rm.textContent = '×';
        tag.appendChild(tn); tag.appendChild(rm);
        container.insertBefore(tag, input);
    }

    function markChanged() {
        hasChanges = true;
        document.getElementById('saveBar').style.display = 'flex';
    }

    function saveChanges() {
        var byFile = {};
        document.querySelectorAll('.editable-field').forEach(function(field) {
            var file = field.dataset.file || 'career-strategy';
            var key  = field.dataset.field;
            if (!key) return;
            if (!byFile[file]) byFile[file] = {};
            byFile[file][key] = field.textContent.trim();
        });
        document.querySelectorAll('.tag-input-container').forEach(function(container) {
            var file = container.dataset.file || 'career-strategy';
            var key  = container.dataset.field;
            if (!key) return;
            if (!byFile[file]) byFile[file] = {};
            byFile[file][key] = Array.from(container.querySelectorAll('.tag')).map(function(t){ return t.firstChild.textContent.trim(); });
        });

        var calls = Object.entries(byFile).map(function(entry) {
            var file = entry[0], fields = entry[1];
            var url, body;
            if (file === 'cv') { url = BASE + '/api/profile/' + SLUG + '/cv'; body = fields; }
            else if (file === 'form') { url = BASE + '/api/profile/' + SLUG + '/form'; body = { answers: fields }; }
            else { url = BASE + '/api/profile/' + SLUG; body = fields; }
            return fetch(url, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }).then(function(r){ return r.json(); });
        });

        Promise.all(calls).then(function(results) {
            var failed = results.filter(function(r){ return !r.success; });
            if (!failed.length) {
                hasChanges = false;
                document.getElementById('saveBar').style.display = 'none';
                // flash green
                var bar = document.getElementById('saveBar');
                bar.style.background = '#e8f5e9'; bar.style.display = 'flex';
                setTimeout(function(){ bar.style.background = 'white'; bar.style.display = 'none'; }, 1200);
            } else {
                alert('Error: ' + (failed[0].error || 'Save failed'));
            }
        }).catch(function(){ alert('Connection error'); });
    }

    function cancelEdit() {
        document.querySelectorAll('.editable-field').forEach(function(field) {
            var key = (field.dataset.file || 'cs') + ':' + field.dataset.field;
            if (originalData[key] !== undefined) field.textContent = originalData[key];
            field.classList.remove('editing');
        });
        document.querySelectorAll('.tag-input-container').forEach(function(container) {
            var key = (container.dataset.file || 'cs') + ':' + container.dataset.field;
            var inp = container.querySelector('.tag-input');
            container.querySelectorAll('.tag').forEach(function(t){ t.remove(); });
            (originalData[key] || []).forEach(function(v){ addTag(container, inp, v); });
        });
        hasChanges = false;
        document.getElementById('saveBar').style.display = 'none';
    }

    window.addEventListener('beforeunload', function(e) {
        if (hasChanges) { e.preventDefault(); e.returnValue = ''; }
    });

    // ── AI Update ──
    function toggleAiPanel() {
        var p = document.getElementById('aiUpdatePanel');
        p.style.display = p.style.display === 'none' ? 'block' : 'none';
    }

    async function runAiUpdate() {
        var text = document.getElementById('aiFormText').value.trim();
        if (!text) { alert('Paste some text first.'); return; }
        var btn = document.getElementById('btnRunAi');
        btn.disabled = true; btn.textContent = 'Processing...';
        try {
            var aiRes = await fetch('https://api.anthropic.com/v1/messages', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', 'x-api-key': ANTHROPIC_KEY, 'anthropic-version': '2023-06-01' },
                body: JSON.stringify({ model: 'claude-haiku-4-5', max_tokens: 1024, messages: [{ role: 'user', content: 'Merge new information into the existing profile JSON. Add missing fields, update outdated values, preserve existing data not contradicted. Return ONLY valid JSON.\n\nEXISTING:\n' + JSON.stringify(CURRENT_PROFILE, null, 2) + '\n\nNEW:\n' + text }] })
            });
            if (!aiRes.ok) { var err = await aiRes.json().catch(function(){ return {}; }); throw new Error(err.error?.message || 'OpenAI error'); }
            var aiData = await aiRes.json();
            var content = aiData.content[0].text.trim().replace(/^```(?:json)?\n?/, '').replace(/\n?```$/, '');
            var updated = JSON.parse(content);
            var saveRes = await fetch(BASE + '/api/profile/' + SLUG, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(updated) });
            var saveResult = await saveRes.json();
            if (saveResult.success) { alert('Profile updated by AI! Reloading...'); location.reload(); }
            else throw new Error(saveResult.error || 'Save failed');
        } catch(e) {
            alert('Error: ' + e.message);
            btn.disabled = false; btn.textContent = 'Update with AI';
        }
    }

    // ── Resend email ──
    function resendSetupEmail() {
        var btn = document.getElementById('btnResendEmail');
        btn.disabled = true;
        btn.innerHTML = '<span class="material-icons" style="font-size:16px;">hourglass_empty</span>Sending...';
        fetch(BASE + '/api/mentee/' + SLUG + '/resend-setup', { method: 'POST' })
        .then(function(r){ return r.json(); })
        .then(function(data) {
            if (data.success) btn.innerHTML = '<span class="material-icons" style="font-size:16px;">check</span>Sent!';
            else { btn.innerHTML = '<span class="material-icons" style="font-size:16px;">error</span>Error'; btn.disabled = false; }
        })
        .catch(function(){ btn.innerHTML = '<span class="material-icons" style="font-size:16px;">error</span>Error'; btn.disabled = false; });
    }

    // ── Job Search ──
    var _jsResults = [];
    var _jsRejected = [];
    var _jsCurrentRoles = [];
    var _jsCurrentLocation = '';

    function openJobSearchModal() {
        var cs = CURRENT_PROFILE;
        var seg = (cs.strategy && cs.strategy.segments && cs.strategy.segments[0]) || {};
        var roles = seg.targetRoles || cs.primaryRoles || cs.targetRoleFamilies || [];
        var location = (seg.targetGeographies && seg.targetGeographies[0])
            || (cs.priorityCities && cs.priorityCities[0])
            || cs.primaryCountry || cs.location || '—';

        var html = '';
        if (roles.length) {
            html += '<div><strong>Roles:</strong> ' + escHtml(roles.join(', ')) + '</div>';
        } else {
            html += '<div style="color:#e53935;">⚠ No target roles found in career strategy.</div>';
        }
        html += '<div><strong>Location:</strong> ' + escHtml(location) + '</div>';
        if (cs.exclusions && cs.exclusions.length) {
            html += '<div style="color:#888;font-size:12px;"><strong>Exclusions:</strong> ' + escHtml(cs.exclusions.join(', ')) + '</div>';
        }
        document.getElementById('js-search-preview').innerHTML = html;
        document.getElementById('js-search-btn').disabled = !roles.length;

        jsShowStage('input');
        var _jsEl = document.getElementById('jsModal');
        _jsEl.style.display = 'flex';
        requestAnimationFrame(function(){ requestAnimationFrame(function(){ _jsEl.classList.add('is-open'); }); });
    }

    function closeJsModal() {
        var _jsEl = document.getElementById('jsModal');
        _jsEl.classList.remove('is-open');
        _jsEl.addEventListener('transitionend', function _h(e){ if(e.target===_jsEl&&e.propertyName==='opacity'){ _jsEl.style.display='none'; _jsEl.removeEventListener('transitionend',_h); } });
    }

    function jsShowStage(stage) {
        ['input','loading','results','done'].forEach(function(s) {
            document.getElementById('js-stage-' + s).style.display = s === stage ? '' : 'none';
        });
    }

    function jsSetStatus(main, sub) {
        document.getElementById('js-status').textContent = main;
        document.getElementById('js-substatus').textContent = sub || '';
    }

    function escHtml(str) {
        if (!str) return '';
        return String(str).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
    }

    async function runJobSearch() {
        jsShowStage('loading');

        var statusCycle = [
            ['Searching TheirStack, LinkedIn, Indeed & Glassdoor...', 'Running parallel searches — this may take up to 30 seconds'],
            ['Fetching job descriptions...', 'Getting full details for AI screening'],
            ['AI screening in progress...', 'Checking each job against career strategy'],
            ['Almost there...', 'Finalizing results']
        ];
        var cycleIdx = 0;
        jsSetStatus(statusCycle[0][0], statusCycle[0][1]);
        var statusTimer = setInterval(function() {
            cycleIdx = (cycleIdx + 1) % statusCycle.length;
            jsSetStatus(statusCycle[cycleIdx][0], statusCycle[cycleIdx][1]);
        }, 6000);

        try {
            var r = await fetch(BASE + '/api/profile/' + SLUG + '/job-search', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({})
            });
            clearInterval(statusTimer);

            if (!r.ok) {
                var err = await r.json().catch(function(){ return {}; });
                throw new Error(err.error || 'Search failed (' + r.status + ')');
            }

            var data = await r.json();
            _jsResults = data.passed.map(function(job) {
                return Object.assign({}, job, { decision: null, declineReason: '' });
            });
            _jsRejected = (data.failed || []);
            _jsCurrentRoles = data.searchRoles || [];
            _jsCurrentLocation = data.searchLocation || '';

            renderJsResults(data);
            renderRejectedSection();
            jsShowStage('results');
            document.getElementById('js-expand-body').style.display = 'none';
            document.getElementById('js-expand-input').value = '';
            document.getElementById('js-expand-status').textContent = '';
        } catch(e) {
            clearInterval(statusTimer);
            alert('Error: ' + e.message);
            jsShowStage('input');
        }
    }

    function renderJsResults(data) {
        var stats = data.stats;
        var subtitle = '';
        if (stats.total) subtitle += stats.total + ' found · ';
        if (stats.skipped) subtitle += stats.skipped + ' already tracked · ';
        if (stats.failed) subtitle += stats.failed + ' filtered by AI · ';
        subtitle += '<strong>' + stats.passed + ' match your strategy</strong>';
        document.getElementById('js-results-subtitle').innerHTML = subtitle;

        var list = document.getElementById('js-jobs-list');
        if (!_jsResults.length) {
            list.innerHTML = '<div class="empty-state" style="padding:40px 0;"><span class="material-icons" style="font-size:40px;display:block;margin-bottom:8px;">search_off</span>No new matching jobs found.</div>';
            updateJsDecisionCount();
            return;
        }

        list.innerHTML = _jsResults.map(function(job, i) {
            return buildJobCard(job, i);
        }).join('');

        updateJsDecisionCount();
    }

    function toggleJsDesc(i) {
        var el = document.getElementById('js-desc-' + i);
        if (el) el.style.display = el.style.display === 'none' ? '' : 'none';
    }

    function jsDecide(i, decision) {
        _jsResults[i].decision = decision;
        var card = document.getElementById('js-card-' + i);
        var reasonDiv = document.getElementById('js-reason-' + i);
        card.classList.remove('decided-accept', 'decided-decline');
        if (decision === 'accept') {
            card.classList.add('decided-accept');
            reasonDiv.style.display = 'none';
        } else {
            card.classList.add('decided-decline');
            reasonDiv.style.display = '';
            setTimeout(function(){ reasonDiv.querySelector('input').focus(); }, 50);
        }
        updateJsDecisionCount();
    }

    function updateJsDecisionCount() {
        var decided = _jsResults.filter(function(j){ return j.decision; }).length;
        document.getElementById('js-decision-count').textContent = decided + ' of ' + _jsResults.length + ' reviewed';
        var btn = document.getElementById('js-apply-btn');
        if (btn) btn.disabled = decided === 0;
    }

    function toggleExpandPanel() {
        var body = document.getElementById('js-expand-body');
        var isOpen = body.style.display !== 'none';
        body.style.display = isOpen ? 'none' : '';
        if (!isOpen) setTimeout(function(){ document.getElementById('js-expand-input').focus(); }, 50);
    }

    function renderRejectedSection() {
        var wrap = document.getElementById('js-rejected-wrap');
        if (!_jsRejected.length) { wrap.style.display = 'none'; return; }
        wrap.style.display = '';
        document.getElementById('js-rejected-label').textContent = _jsRejected.length + ' filtered by AI — show';
        var body = document.getElementById('js-rejected-body');
        if (body.style.display === 'none') return;
        body.innerHTML = _jsRejected.map(function(job, i) {
            return '<div style="border:1px solid #eee;border-radius:8px;padding:12px 14px;background:#fafafa;">' +
                '<div style="font-size:13px;font-weight:600;color:#666;">' +
                    (job.url ? '<a href="' + escHtml(job.url) + '" target="_blank" style="color:#666;text-decoration:none;" onclick="event.stopPropagation()">' + escHtml(job.title) + ' <span class="material-icons" style="font-size:11px;vertical-align:middle;">open_in_new</span></a>' : escHtml(job.title)) +
                '</div>' +
                '<div style="font-size:12px;color:#aaa;margin:2px 0 5px;">' + escHtml(job.company) + ' · ' + escHtml(job.location) + '</div>' +
                (job.aiReason ? '<div style="font-size:11px;color:#e57373;font-style:italic;margin-bottom:7px;">AI: ' + escHtml(job.aiReason) + '</div>' : '') +
                '<button onclick="overrideRejected(' + i + ')" style="background:none;border:1px solid #28a745;color:#28a745;border-radius:4px;padding:4px 12px;font-size:12px;font-weight:600;cursor:pointer;font-family:inherit;">Override & Accept</button>' +
            '</div>';
        }).join('');
    }

    function toggleRejectedSection() {
        var body = document.getElementById('js-rejected-body');
        var chevron = document.getElementById('js-rejected-chevron');
        var isOpen = body.style.display !== 'none';
        body.style.display = isOpen ? 'none' : '';
        chevron.textContent = isOpen ? 'expand_more' : 'expand_less';
        document.getElementById('js-rejected-label').textContent =
            _jsRejected.length + ' filtered by AI — ' + (isOpen ? 'show' : 'hide');
        if (!isOpen) renderRejectedSection();
    }

    function overrideRejected(i) {
        var job = _jsRejected.splice(i, 1)[0];
        var newJob = Object.assign({}, job, { decision: null, declineReason: '' });
        var newIdx = _jsResults.length;
        _jsResults.push(newJob);
        var list = document.getElementById('js-jobs-list');
        var emptyState = list.querySelector('.empty-state');
        if (emptyState) list.innerHTML = '';
        list.insertAdjacentHTML('beforeend', buildJobCard(newJob, newIdx));
        renderRejectedSection();
        updateJsDecisionCount();
    }

    function syncDeclineReasons() {
        _jsResults.forEach(function(job, i) {
            if (job.decision === 'decline') {
                var input = document.querySelector('#js-reason-' + i + ' input');
                if (input) job.declineReason = input.value;
            }
        });
    }

    function buildJobCard(job, i) {
        var hasDesc = job.description && job.description.length > 0;
        return '<div class="js-job-card' + (job.decision ? ' decided-' + job.decision : '') + '" id="js-card-' + i + '">' +
            '<div class="js-job-title">' +
                (job.url ? '<a href="' + escHtml(job.url) + '" target="_blank" style="color:#222;text-decoration:none;" onclick="event.stopPropagation()">' + escHtml(job.title) + ' <span class="material-icons" style="font-size:12px;vertical-align:middle;color:#28a745;">open_in_new</span></a>' : escHtml(job.title)) +
            '</div>' +
            '<div class="js-job-meta">' + escHtml(job.company) + ' · ' + escHtml(job.location) + ' <span style="color:#ccc;">· ' + escHtml(job.source || '') + '</span></div>' +
            (job.aiReason ? '<div class="js-ai-reason">AI: ' + escHtml(job.aiReason) + '</div>' : '') +
            (hasDesc ? '<div class="js-job-desc" id="js-desc-' + i + '">' + escHtml(job.description) + '</div>' : '') +
            '<div class="js-job-actions">' +
                (hasDesc ? '<button class="js-btn-view" onclick="toggleJsDesc(' + i + ')"><span class="material-icons" style="font-size:14px;">visibility</span>Description</button>' : '') +
                '<button class="js-btn-accept" onclick="jsDecide(' + i + ',\'accept\')"><span class="material-icons" style="font-size:14px;">check</span>Accept</button>' +
                '<button class="js-btn-decline" onclick="jsDecide(' + i + ',\'decline\')">Decline</button>' +
            '</div>' +
            '<div id="js-reason-' + i + '" style="display:' + (job.decision === 'decline' ? '' : 'none') + ';">' +
                '<input class="js-decline-input" type="text" placeholder="Reason for declining…" value="' + escHtml(job.declineReason || '') + '">' +
            '</div>' +
        '</div>';
    }

    async function runExpandSearch() {
        var instruction = document.getElementById('js-expand-input').value.trim();
        if (!instruction) { alert('Describe how to adjust the search.'); return; }

        var btn = document.getElementById('js-expand-btn');
        var status = document.getElementById('js-expand-status');
        btn.disabled = true;
        btn.innerHTML = '<span class="material-icons" style="font-size:14px;vertical-align:middle;">hourglass_empty</span> Searching...';
        status.textContent = 'AI interpreting instruction...';

        syncDeclineReasons();

        var seenKeys = _jsResults.map(function(j) {
            return (j.title || '').toLowerCase().trim() + '|' + (j.company || '').toLowerCase().trim();
        });

        try {
            var r = await fetch(BASE + '/api/profile/' + SLUG + '/job-search/expand', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    instruction: instruction,
                    currentRoles: _jsCurrentRoles,
                    currentLocation: _jsCurrentLocation,
                    seenKeys: seenKeys
                })
            });
            if (!r.ok) {
                var err = await r.json().catch(function(){ return {}; });
                throw new Error(err.error || 'Expand failed (' + r.status + ')');
            }
            var data = await r.json();

            _jsCurrentRoles = data.newRoles || _jsCurrentRoles;
            _jsCurrentLocation = data.newLocation || _jsCurrentLocation;

            var seenSet = new Set(seenKeys);
            var fresh = (data.passed || []).filter(function(j) {
                var key = (j.title || '').toLowerCase().trim() + '|' + (j.company || '').toLowerCase().trim();
                return !seenSet.has(key);
            }).map(function(job) {
                return Object.assign({}, job, { decision: null, declineReason: '' });
            });

            var startIdx = _jsResults.length;
            _jsResults = _jsResults.concat(fresh);

            var list = document.getElementById('js-jobs-list');
            var emptyState = list.querySelector('.empty-state');
            if (emptyState) list.innerHTML = '';

            if (fresh.length) {
                if (startIdx > 0) {
                    list.insertAdjacentHTML('beforeend',
                        '<div style="border-top:2px dashed #e8f5e9;margin:6px 0 2px;font-size:11px;color:#aaa;text-align:center;padding-top:6px;">' +
                        '— ' + fresh.length + ' new result(s) from expanded search —</div>');
                }
                list.insertAdjacentHTML('beforeend', fresh.map(function(job, offset) {
                    return buildJobCard(job, startIdx + offset);
                }).join(''));
            }

            _jsRejected = _jsRejected.concat(data.failed || []);
            renderRejectedSection();

            var subtitleEl = document.getElementById('js-results-subtitle');
            subtitleEl.innerHTML = subtitleEl.innerHTML +
                ' · <span style="color:#28a745;font-weight:600;">+' + fresh.length + ' from "' + escHtml(instruction) + '"</span>';

            status.innerHTML = 'Searched: <strong>' + escHtml((data.newRoles || []).join(', ')) + '</strong> in <strong>' + escHtml(data.newLocation || '') + '</strong>';
            updateJsDecisionCount();
            document.getElementById('js-expand-input').value = '';
            btn.disabled = false;
            btn.innerHTML = '<span class="material-icons" style="font-size:14px;vertical-align:middle;">search</span> Re-search';

        } catch(e) {
            status.textContent = 'Error: ' + e.message;
            btn.disabled = false;
            btn.innerHTML = '<span class="material-icons" style="font-size:14px;vertical-align:middle;">search</span> Re-search';
        }
    }

    async function applyJobDecisions() {
        var decided = _jsResults.filter(function(j){ return j.decision; });
        if (!decided.length) { alert('Review at least one job first.'); return; }

        // Collect decline reasons from inputs
        _jsResults.forEach(function(job, i) {
            if (job.decision === 'decline') {
                var input = document.querySelector('#js-reason-' + i + ' input');
                if (input) job.declineReason = input.value.trim();
            }
        });

        var btn = document.getElementById('js-apply-btn');
        btn.textContent = 'Saving…'; btn.disabled = true;

        try {
            var r = await fetch(BASE + '/api/profile/' + SLUG + '/job-search/apply', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ jobs: decided })
            });
            var data = await r.json();
            if (!data.success) throw new Error(data.error || 'Apply failed');

            document.getElementById('js-done-msg').textContent =
                data.accepted + ' job' + (data.accepted !== 1 ? 's' : '') + ' added to tracking · ' +
                data.declined + ' declined';

            if (data.strategyUpdates && data.strategyUpdates.addedExclusions && data.strategyUpdates.addedExclusions.length) {
                var upd = document.getElementById('js-strategy-update');
                upd.style.display = '';
                upd.innerHTML = '<strong>Career strategy updated — new exclusion' +
                    (data.strategyUpdates.addedExclusions.length > 1 ? 's' : '') + ' added:</strong><br>' +
                    data.strategyUpdates.addedExclusions.map(function(e){ return '• ' + escHtml(e); }).join('<br>');
            }

            jsShowStage('done');
        } catch(e) {
            alert('Error: ' + e.message);
            btn.textContent = 'Apply decisions'; btn.disabled = false;
        }
    }

    // ── Changelog ──
    function loadChangelog() {
        fetch(BASE + '/api/mentee/' + SLUG + '/changelog')
        .then(function(r){ return r.json(); })
        .then(function(log) {
            var el = document.getElementById('changelogList');
            if (!log.length) { el.innerHTML = '<div class="empty-state">No changes recorded yet.</div>'; return; }
            el.innerHTML = log.map(function(e) {
                var who    = e.who === 'client' ? 'Client' : 'Coach (' + (e.email || '') + ')';
                var action = e.action === 'profile_edit' ? 'Edited profile'
                           : e.action === 'ai_update'   ? 'AI update'
                           : e.action === 'cv_edit'     ? 'Edited CV' : e.action;
                var fields = e.fields ? ' · ' + e.fields.join(', ') : '';
                var ts = new Date(e.ts).toLocaleString('en-GB', { day:'2-digit', month:'short', year:'numeric', hour:'2-digit', minute:'2-digit' });
                return '<div class="cl-entry"><span class="cl-who">' + who + '</span><span class="cl-action">' + action + fields + '</span><span class="cl-ts">' + ts + '</span></div>';
            }).join('');
        })
        .catch(function(){ document.getElementById('changelogList').innerHTML = '<div class="empty-state">Could not load history.</div>'; });
    }
</script>

<!-- ── A4 CV / Cover Letter modal ── -->
<div id="cv-a4-modal" style="display:none;">
  <!-- Toolbar -->
  <div id="cva-toolbar">
    <button onclick="closeCvModal()" style="background:#dc3545;color:#fff;border:none;border-radius:5px;padding:6px 12px;font-size:12px;font-weight:600;cursor:pointer;font-family:inherit;display:inline-flex;align-items:center;gap:4px;">
      <span class="material-icons" style="font-size:14px;">close</span>Close
    </button>
    <span id="cva-title" style="color:#eee;font-size:13px;font-weight:600;flex:1;margin-left:4px;"></span>
    <button id="cva-undo-btn" onclick="undoCv()" style="background:#333;color:#aaa;border:1px solid #555;border-radius:5px;padding:6px 10px;font-size:12px;cursor:pointer;font-family:inherit;display:inline-flex;align-items:center;gap:4px;">
      <span class="material-icons" style="font-size:14px;">undo</span>Undo
    </button>
    <button id="cva-redo-btn" onclick="redoCv()" style="background:#333;color:#aaa;border:1px solid #555;border-radius:5px;padding:6px 10px;font-size:12px;cursor:pointer;font-family:inherit;display:inline-flex;align-items:center;gap:4px;">
      <span class="material-icons" style="font-size:14px;">redo</span>Redo
    </button>
    <button id="cva-regen-btn" onclick="generateCvDoc(true)" style="background:#333;color:#aaa;border:1px solid #555;border-radius:5px;padding:6px 10px;font-size:12px;cursor:pointer;font-family:inherit;display:inline-flex;align-items:center;gap:4px;">
      <span class="material-icons" style="font-size:14px;">refresh</span>Regenerate
    </button>
    <button id="cva-save-btn" onclick="saveCvModal()" style="background:#28a745;color:#fff;border:none;border-radius:5px;padding:6px 12px;font-size:12px;font-weight:600;cursor:pointer;font-family:inherit;display:inline-flex;align-items:center;gap:4px;">
      <span class="material-icons" style="font-size:14px;">save</span>Save
    </button>
    <button id="cva-copy-btn" onclick="copyCvModal(this)" style="background:#333;color:#aaa;border:1px solid #555;border-radius:5px;padding:6px 10px;font-size:12px;cursor:pointer;font-family:inherit;display:inline-flex;align-items:center;gap:4px;">
      <span class="material-icons" style="font-size:14px;">content_copy</span>Copy
    </button>
    <button id="cva-print-btn" onclick="printCvModal()" style="background:#333;color:#aaa;border:1px solid #555;border-radius:5px;padding:6px 10px;font-size:12px;cursor:pointer;font-family:inherit;display:inline-flex;align-items:center;gap:4px;">
      <span class="material-icons" style="font-size:14px;">print</span>Print
    </button>
    <div style="position:relative;display:inline-flex;">
      <button id="cva-download-btn" onclick="toggleCvaDownloadMenu(event)" style="background:#1565c0;color:#fff;border:none;border-radius:5px;padding:6px 12px;font-size:12px;font-weight:600;cursor:pointer;font-family:inherit;display:inline-flex;align-items:center;gap:4px;">
        <span class="material-icons" style="font-size:14px;">download</span>Download<span class="material-icons" style="font-size:13px;">arrow_drop_down</span>
      </button>
      <div id="cva-download-menu" style="display:none;position:absolute;top:calc(100% + 4px);right:0;background:#fff;border:1px solid #ddd;border-radius:6px;box-shadow:0 4px 16px rgba(0,0,0,0.18);z-index:20;min-width:130px;overflow:hidden;">
        <button onclick="downloadCvModal('pdf')" style="display:flex;align-items:center;gap:8px;width:100%;padding:10px 14px;border:none;background:none;cursor:pointer;font-size:12px;color:#333;font-family:inherit;text-align:left;">
          <span class="material-icons" style="font-size:15px;color:#dc3545;">picture_as_pdf</span>PDF
        </button>
        <button onclick="downloadCvModal('docx')" style="display:flex;align-items:center;gap:8px;width:100%;padding:10px 14px;border:none;background:#fafafa;cursor:pointer;font-size:12px;color:#333;font-family:inherit;text-align:left;border-top:1px solid #f0f0f0;">
          <span class="material-icons" style="font-size:15px;color:#1565c0;">description</span>DOCX
        </button>
      </div>
    </div>
  </div>
  <!-- Instruction bar -->
  <div id="cva-instruction-bar">
    <textarea id="cva-instruction" placeholder="Propose a change… e.g. 'make it shorter', 'remove experience at Company X', 'add skill Y'"></textarea>
    <button id="cva-apply-btn" onclick="applyCvChange()" style="background:#28a745;color:#fff;border:none;border-radius:5px;padding:8px 14px;font-size:12px;font-weight:600;cursor:pointer;font-family:inherit;white-space:nowrap;display:inline-flex;align-items:center;gap:4px;">
      <span class="material-icons" style="font-size:14px;">auto_fix_high</span>Apply
    </button>
  </div>
  <!-- Page area -->
  <div id="cva-page-area">
    <div id="cva-loading">
      <div class="js-spinner" style="width:36px;height:36px;"></div>
      <div style="font-size:13px;color:#555;">AI generating…</div>
    </div>
    <div id="cva-paper" contenteditable="true" style="display:none;"></div>
  </div>
</div>

<!-- ── Plan / Status Modal ── -->
<div class="ps-overlay" id="psOverlay">
    <div class="ps-panel">
        <div class="ps-header">
            <span id="psModalTitle">Change Plan</span>
            <button class="ps-close" onclick="closePlanStatusModal()">×</button>
        </div>
        <div class="ps-body" id="psBody">
            <!-- filled dynamically -->
        </div>
        <div class="ps-footer">
            <button class="ps-btn-cancel" onclick="closePlanStatusModal()">Cancel</button>
            <button class="ps-btn-save" id="psSaveBtn" onclick="savePlanStatus()">Save</button>
        </div>
    </div>
</div>

<script>
(function() {
    let psMode = 'plan';

    function openPlanStatusModal(mode) {
        psMode = mode;
        const title = document.getElementById('psModalTitle');
        const body  = document.getElementById('psBody');
        title.textContent = mode === 'plan' ? 'Change Plan' : 'Change Status';

        const currentPlan   = '<%= csPlan %>';
        const currentStatus = '<%= csStatus %>';
        const currentReason = '<%= cs.inactiveReason || "" %>';

        if (mode === 'plan') {
            body.innerHTML = `
                <div class="ps-field">
                    <label>Plan</label>
                    <select id="psSelectPlan">
                        <option value="silver"   ${currentPlan==='silver'?'selected':''}>Silver</option>
                        <option value="golden"   ${currentPlan==='golden'?'selected':''}>Golden</option>
                        <option value="platinum" ${currentPlan==='platinum'?'selected':''}>Platinum</option>
                    </select>
                </div>`;
        } else {
            body.innerHTML = `
                <div class="ps-field">
                    <label>Status</label>
                    <select id="psSelectStatus" onchange="toggleReasonField(this.value)">
                        <option value="active"   ${currentStatus==='active'?'selected':''}>Active</option>
                        <option value="inactive" ${currentStatus==='inactive'?'selected':''}>Inactive</option>
                    </select>
                </div>
                <div class="ps-field" id="psReasonField" style="${currentStatus==='inactive'?'':'display:none'}">
                    <label>Reason for inactivity</label>
                    <select id="psSelectReason">
                        <option value=""                 ${!currentReason?'selected':''}>Select reason…</option>
                        <option value="found a job"      ${currentReason==='found a job'?'selected':''}>Found a job</option>
                        <option value="declined plan"    ${currentReason==='declined plan'?'selected':''}>Declined plan</option>
                        <option value="no payment"       ${currentReason==='no payment'?'selected':''}>No payment</option>
                    </select>
                </div>`;
        }
        document.getElementById('psOverlay').classList.add('open');
    }

    window.openPlanStatusModal = openPlanStatusModal;

    window.toggleReasonField = function(val) {
        document.getElementById('psReasonField').style.display = val === 'inactive' ? '' : 'none';
    };

    window.closePlanStatusModal = function() {
        document.getElementById('psOverlay').classList.remove('open');
    };

    window.savePlanStatus = async function() {
        const btn = document.getElementById('psSaveBtn');
        btn.disabled = true;
        btn.textContent = 'Saving…';
        try {
            const body = {};
            if (psMode === 'plan') {
                body.plan = document.getElementById('psSelectPlan').value;
            } else {
                body.status = document.getElementById('psSelectStatus').value;
                if (body.status === 'inactive') {
                    body.inactiveReason = document.getElementById('psSelectReason').value;
                }
            }
            const r = await fetch(BASE + '/api/admin/profile/' + SLUG + '/plan-status', {
                method: 'PATCH',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(body)
            });
            const data = await r.json();
            if (!r.ok) throw new Error(data.error || 'Failed to save');
            window.location.reload();
        } catch (e) {
            alert('Error: ' + e.message);
            btn.disabled = false;
            btn.textContent = 'Save';
        }
    };

    document.getElementById('psOverlay').addEventListener('click', function(e) {
        if (e.target === this) closePlanStatusModal();
    });
})();
</script>
</body>
</html>