<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>EcoBot — My Career Dossier</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">
    <style>
        body { display: block; background: #f4f6f4; min-height: 100vh; }

        .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; }
        .portal-header .user-info { display: flex; align-items: center; gap: 12px; font-size: 14px; color: #555; }
        .btn-logout {
            display: flex; align-items: center; gap: 4px;
            background: #dc3545; color: white; text-decoration: none; font-size: 13px;
            padding: 6px 12px; border-radius: 4px; transition: background 0.2s; border: none;
        }
        .btn-logout:hover { background: #c82333; color: white; }

        .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; }

        .portal-body { max-width: 960px; margin: 0 auto; padding: 0 20px 60px; }

        .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; }

        .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 { 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; }

        .tag-list { display: flex; flex-wrap: wrap; gap: 6px; }
        .tag {
            background: #e8f5e9; color: #2e7d32;
            font-size: 12px; padding: 4px 11px; 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 card */
        .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-meta { font-size: 12px; color: #888; margin-bottom: 10px; }
        .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;
        }
        .segment-companies { font-size: 12px; color: #888; margin-top: 6px; }

        /* Gap analysis */
        .gap-list { padding-left: 18px; margin: 0; }
        .gap-list li { font-size: 13px; color: #444; line-height: 1.8; }
        .strength-list { padding-left: 18px; margin: 0; }
        .strength-list li { font-size: 13px; color: #2e7d32; line-height: 1.8; }

        /* Execution plan */
        .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: 140px; flex-shrink: 0; }
        .plan-val { color: #333; }

        /* Dossier */
        .dossier-headline { font-size: 20px; font-weight: 700; color: #1a1a1a; margin: 0 0 10px; }
        .dossier-summary  { font-size: 14px; color: #444; line-height: 1.8; margin: 0 0 20px; }
        .dossier-section  { margin-bottom: 26px; }
        .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; }
        .lang-level { color: #888; font-size: 13px; }

        /* 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-status { display: inline-block; padding: 2px 8px; border-radius: 3px; font-size: 11px; font-weight: 600; }
        .status-proposed  { background: #f5f5f5; color: #666; }
        .status-applied   { background: #e3f2fd; color: #1565c0; }
        .status-interview { background: #fff8e1; color: #f57f17; }
        .status-offer     { background: #e8f5e9; color: #2e7d32; }
        .status-rejected  { background: #fce4ec; color: #c62828; }

        /* CV files */
        .cv-file-row {
            display: flex; align-items: center; justify-content: space-between;
            padding: 14px 0; border-bottom: 1px solid #f5f5f5;
        }
        .cv-file-row:last-child { border-bottom: none; }
        .cv-file-info { display: flex; align-items: center; gap: 12px; }
        .cv-file-icon { color: #28a745; }
        .cv-file-name { font-size: 14px; font-weight: 500; color: #333; }
        .cv-file-status { font-size: 12px; color: #888; }
        .cv-file-missing { font-size: 14px; color: #bbb; display: flex; align-items: center; gap: 8px; }
        .btn-download {
            display: inline-flex; align-items: center; gap: 6px;
            background: #28a745; color: white; padding: 7px 14px;
            border-radius: 6px; text-decoration: none; font-size: 13px;
            font-weight: 500; transition: background 0.2s;
        }
        .btn-download:hover { background: #218838; }

        .empty-state { text-align: center; color: #bbb; font-size: 14px; padding: 30px 0; }
        .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;
        }
        .badge-count {
            background: #28a745; color: white; font-size: 10px;
            padding: 1px 6px; border-radius: 10px; font-weight: 700;
        }

        /* Edit profile */
        .btn-edit-profile {
            display: inline-flex; align-items: center; gap: 5px;
            background: none; border: 1px solid #28a745; color: #28a745;
            padding: 5px 14px; border-radius: 5px; font-size: 13px;
            cursor: pointer; font-family: 'Ubuntu', sans-serif; transition: all 0.15s;
        }
        .btn-edit-profile:hover { background: #28a745; color: white; }
        .edit-field {
            width: 100%; box-sizing: border-box;
            border: 1px solid #c3e6cb; border-radius: 5px;
            padding: 6px 10px; font-size: 14px; color: #333;
            font-family: 'Ubuntu', sans-serif;
            outline: none;
        }
        .edit-field:focus { border-color: #28a745; box-shadow: 0 0 0 2px rgba(40,167,69,0.12); }
        .btn-save-edit {
            background: #28a745; color: white; border: none;
            padding: 8px 20px; border-radius: 5px; font-size: 14px;
            cursor: pointer; font-family: 'Ubuntu', sans-serif;
            display: inline-flex; align-items: center; gap: 5px;
        }
        .btn-save-edit:hover { background: #218838; }
        .btn-cancel-edit {
            background: #f0f0f0; color: #555; border: 1px solid #ddd;
            padding: 8px 20px; border-radius: 5px; 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;
        }
        .ai-panel h4 { margin: 0 0 8px; color: #28a745; font-size: 14px; }
        .ai-panel textarea {
            width: 100%; box-sizing: border-box; border: 1px solid #c3e6cb;
            border-radius: 5px; padding: 10px; font-size: 13px; resize: vertical;
            font-family: 'Ubuntu', sans-serif; min-height: 100px;
        }

        /* 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; }

        /* Job table */
        .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; }
        .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; }
        .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; }
        .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-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; }

        /* A4 CV 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; }

        /* 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; }

        /* ── Mobile responsiveness ─────────────────────────── */
        @media (max-width: 640px) {
            /* Header */
            .portal-header { padding: 0 14px; height: auto; min-height: 52px; flex-wrap: wrap; gap: 6px; }
            .portal-header .logo-text { font-size: 17px; }
            .portal-header .user-info { font-size: 13px; gap: 8px; }
            .btn-logout { font-size: 12px; padding: 5px 10px; }

            /* Welcome banner */
            .welcome-banner { padding: 18px 16px; gap: 14px; }
            .welcome-avatar { width: 44px; height: 44px; font-size: 18px; }
            .welcome-text h2 { font-size: 16px; }
            .welcome-text p  { font-size: 12px; }

            /* Portal body */
            .portal-body { padding: 0 12px 48px; }

            /* Cards */
            .card { padding: 16px 14px; }

            /* Job table — keep only Role + Status on mobile, no scroll */
            .job-table { table-layout: fixed; width: 100%; }
            .job-table thead th:nth-child(2),  /* Company */
            .job-table thead th:nth-child(3),  /* Location */
            .job-table thead th:nth-child(5),  /* Found */
            .job-table thead th:nth-child(6),  /* Applied */
            .job-table thead th:nth-child(7) { display: none; }  /* Interview */

            .job-table tbody td:nth-child(2),
            .job-table tbody td:nth-child(3),
            .job-table tbody td:nth-child(5),
            .job-table tbody td:nth-child(6),
            .job-table tbody td:nth-child(7) { display: none; }

            /* Role takes remaining space, Status shrinks to fit badge */
            .job-table td:nth-child(1), .job-table th:nth-child(1) { width: auto; word-break: break-word; }
            .job-table td:nth-child(4), .job-table th:nth-child(4) { width: 1%; white-space: nowrap; }

            /* Execution plan key label — allow wrap */
            .plan-row { flex-wrap: wrap; gap: 4px; }
            .plan-key { min-width: unset; width: 100%; font-size: 11px; color: #888; font-weight: 700; margin-bottom: 1px; }

            /* CV file row */
            .cv-file-row { flex-wrap: wrap; gap: 8px; }

            /* Changelog timestamp — allow wrap */
            .cl-ts { white-space: normal; }

            /* Job modal row — stack fields */
            .jm-row { grid-template-columns: 1fr; }

            /* AI panel textarea */
            .ai-panel textarea { min-height: 80px; }

            /* Tab btn smaller on mobile */
            .tab-btn { padding: 11px 14px; font-size: 12px; }
        }

        /* ── Validation badge ── */
        .warn-badge {
            display: inline-flex; align-items: center; justify-content: center;
            width: 16px; height: 16px; border-radius: 3px;
            background: #f59e0b; color: white; font-size: 10px; font-weight: 700;
            margin-left: 4px; line-height: 1; flex-shrink: 0;
        }
        .validate-bar {
            background: #fffbeb; border: 1px solid #fde68a; border-radius: 8px;
            padding: 14px 18px; display: flex; align-items: center; gap: 12px;
            margin-bottom: 20px; font-size: 13px; color: #92400e;
        }
        .validate-bar .material-icons { color: #f59e0b; font-size: 20px; flex-shrink: 0; }
        .btn-validate {
            margin-left: auto; background: #28a745; color: white; border: none;
            border-radius: 5px; padding: 7px 16px; font-size: 13px; font-weight: 600;
            cursor: pointer; font-family: inherit; display: flex; align-items: center; gap: 5px;
            transition: background 0.15s; flex-shrink: 0;
        }
        .btn-validate:hover { background: #218838; }
        .btn-validate:disabled { background: #aaa; cursor: default; }

        /* ── Welcome modal ── */
        .welcome-modal-overlay {
            position: fixed; inset: 0; background: rgba(0,0,0,0.5);
            z-index: 9999; display: flex; align-items: center; justify-content: center;
            padding: 20px;
        }
        .welcome-modal {
            background: white; border-radius: 14px; max-width: 520px; width: 100%;
            box-shadow: 0 20px 60px rgba(0,0,0,0.25); overflow: hidden;
            animation: wm-in 0.3s cubic-bezier(0.34,1.4,0.64,1);
        }
        @keyframes wm-in { from { transform: translateY(24px) scale(0.97); opacity: 0; } to { transform: none; opacity: 1; } }
        .welcome-modal-header {
            background: linear-gradient(135deg, #28a745, #20c997);
            padding: 28px 28px 20px; color: white;
        }
        .welcome-modal-header h2 { margin: 0 0 6px; font-size: 22px; }
        .welcome-modal-header p  { margin: 0; font-size: 13px; opacity: 0.88; }
        .welcome-modal-body { padding: 24px 28px; }
        .welcome-modal-body p { font-size: 14px; color: #444; line-height: 1.7; margin: 0 0 14px; }
        .welcome-checklist { list-style: none; padding: 0; margin: 0 0 20px; }
        .welcome-checklist li {
            display: flex; align-items: flex-start; gap: 10px;
            font-size: 13px; color: #444; padding: 8px 0;
            border-bottom: 1px solid #f0f0f0;
        }
        .welcome-checklist li:last-child { border-bottom: none; }
        .welcome-checklist .wc-icon {
            width: 24px; height: 24px; border-radius: 50%; flex-shrink: 0;
            display: flex; align-items: center; justify-content: center;
            font-size: 13px;
        }
        .wc-warn { background: #fef3c7; color: #92400e; }
        .welcome-modal-footer { padding: 0 28px 24px; text-align: right; }
        .btn-welcome-close {
            background: #28a745; color: white; border: none; border-radius: 6px;
            padding: 10px 24px; font-size: 14px; font-weight: 600; cursor: pointer;
            font-family: inherit;
        }
        .btn-welcome-close:hover { background: #218838; }

        /* ── Form tab fields ── */
        .form-field { margin-bottom: 16px; }
        .form-field label {
            display: block; font-size: 11px; font-weight: 600; color: #aaa;
            text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 5px;
        }
        .form-field input, .form-field textarea, .form-field select {
            width: 100%; box-sizing: border-box;
            border: 1px solid #e0e0e0; border-radius: 5px;
            padding: 8px 10px; font-size: 13px; font-family: inherit; color: #333;
            background: #fafafa; transition: border 0.15s;
        }
        .form-field input:focus, .form-field textarea:focus {
            outline: none; border-color: #28a745; background: white;
        }
        .form-field textarea { min-height: 72px; resize: vertical; }
        .form-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 0 20px; }
        @media (max-width: 600px) { .form-grid { grid-template-columns: 1fr; } }
    </style>
</head>
<body>
<%
  var cs             = locals.careerStrategy  || {};
  var cvmaster       = locals.cvmaster         || null;
  var jobtracking    = locals.jobtracking      || null;
  var form           = locals.form             || null;
  var formValidated  = locals.formValidated    === true;
  var dossierValidated = locals.dossierValidated === true;
  var hasPersonalCv  = locals.hasPersonalCv    || false;
  var hasLinkedinCv  = locals.hasLinkedinCv    || false;
  var jobs = (jobtracking && jobtracking.jobs) ? jobtracking.jobs : [];
  var segments = (cs.strategy && cs.strategy.segments && cs.strategy.segments.length)
                 ? cs.strategy.segments
                 : (cs.strategicSegments || []);
  var firstName = (cs.leadName || 'Client').split(' ')[0];
  var needsValidation = !formValidated || (cvmaster && !dossierValidated);
%>

<!-- Welcome modal (shown once per session) -->
<% if (needsValidation) { %>
<div class="welcome-modal-overlay" id="welcomeModal">
    <div class="welcome-modal">
        <div class="welcome-modal-header">
            <h2>Welcome, <%= firstName %>!</h2>
            <p>Your career profile has been set up. A few things need your attention.</p>
        </div>
        <div class="welcome-modal-body">
            <p>Our team has pre-filled your profile based on your CV. Please review and confirm the information below so we can provide you with the best possible career guidance.</p>
            <ul class="welcome-checklist">
                <% if (!formValidated) { %>
                <li>
                    <span class="wc-icon wc-warn">!</span>
                    <div><strong>Profile Form</strong> — Review and confirm your career goals, background, and preferences.</div>
                </li>
                <% } %>
                <% if (cvmaster && !dossierValidated) { %>
                <li>
                    <span class="wc-icon wc-warn">!</span>
                    <div><strong>Career Dossier</strong> — Confirm your experience, education, and skills are accurate.</div>
                </li>
                <% } %>
            </ul>
            <p style="font-size:12px;color:#999;margin:0;">You can validate each section using the <strong>Confirm & Save</strong> button at the bottom of each tab.</p>
        </div>
        <div class="welcome-modal-footer">
            <button class="btn-welcome-close" onclick="closeWelcomeModal()">Got it, let's go →</button>
        </div>
    </div>
</div>
<% } %>

<!-- Header -->
<div class="portal-header">
    <span class="logo-text">EcoBot</span>
    <div class="user-info">
        <span class="material-icons" style="color:#28a745;font-size:20px;">person</span>
        <span><%= cs.leadName || 'Client' %></span>
        <a href="<%= BASE_PATH %>/client/logout" class="btn-logout">
            <span class="material-icons" style="font-size:16px;">logout</span>
            Logout
        </a>
    </div>
</div>

<!-- Welcome banner -->
<div class="welcome-banner">
    <div class="welcome-avatar"><%= (cs.leadName || 'C').charAt(0).toUpperCase() %></div>
    <div class="welcome-text">
        <h2>Hello, <%= (cs.leadName || 'Client').split(' ')[0] %>!</h2>
        <p><%= cs.targetPositioning || (cvmaster && cvmaster.headline) || cs.shortDescription || 'Welcome to your career dossier.' %></p>
    </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>
    <% if (segments.length > 0) { %>
    <button class="tab-btn" onclick="showTab('strategy', this)">
        <span class="material-icons" style="font-size:16px;">track_changes</span>
        Career Strategy
    </button>
    <% } %>
    <% if (form) { %>
    <button class="tab-btn" onclick="showTab('form', this)">
        <span class="material-icons" style="font-size:16px;">assignment</span>
        My Form
        <% if (!formValidated) { %><span class="warn-badge" title="Needs your confirmation">!</span><% } %>
    </button>
    <% } %>
    <% if (cvmaster) { %>
    <button class="tab-btn" onclick="showTab('dossier', this)">
        <span class="material-icons" style="font-size:16px;">description</span>
        Career Dossier
        <% if (!dossierValidated) { %><span class="warn-badge" title="Needs your confirmation">!</span><% } %>
    </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('cvs', this)">
        <span class="material-icons" style="font-size:16px;">upload_file</span>
        My CVs
    </button>
    <button class="tab-btn" onclick="showTab('edit', this)">
        <span class="material-icons" style="font-size:16px;">edit</span>
        Edit
    </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><%= cs.email %></p></div>
            <% } %>
            <% if (cs.phone) { %>
            <div class="info-item"><label>Phone</label><p><%= cs.phone %></p></div>
            <% } %>
            <% if (cs.location || (cvmaster && cvmaster.contact && cvmaster.contact.location)) { %>
            <div class="info-item"><label>Location</label><p><%= cs.location || cvmaster.contact.location %></p></div>
            <% } %>
            <% var linkedin = cs.linkedin || (cvmaster && cvmaster.contact && cvmaster.contact.linkedin); %>
            <% if (linkedin) { %>
            <div class="info-item">
                <label>LinkedIn</label>
                <p><a href="https://<%= linkedin.replace(/^https?:\/\//,'') %>" target="_blank" style="color:#28a745;"><%= linkedin %></a></p>
            </div>
            <% } %>
            <% if (cs.nationality) { %>
            <div class="info-item"><label>Nationality</label><p><%= cs.nationality %></p></div>
            <% } %>
            <% if (cs.seniority) { %>
            <div class="info-item"><label>Seniority</label><p><%= cs.seniority %></p></div>
            <% } %>
            <% if (cs.salaryTarget) { %>
            <div class="info-item"><label>Salary Target</label><p><%= cs.salaryTarget %></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-list">
                <% cs.languages.forEach(function(l){ %><span class="tag-grey"><%= l %></span><% }); %>
            </div>
        </div>
        <% } %>

        <% var openTo = []; %>
        <% if (cs.openToRemote) openTo.push('Remote'); %>
        <% if (cs.openToRelocate) openTo.push('Open to relocate'); %>
        <% if (openTo.length) { %>
        <div style="margin-top:14px;padding-top:12px;border-top:1px solid #f0f0f0;">
            <div class="tag-list">
                <% openTo.forEach(function(t){ %><span class="tag"><%= t %></span><% }); %>
            </div>
        </div>
        <% } %>

        <% var desc = cs.shortDescription || (cvmaster && cvmaster.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>
            <p style="font-size:14px;color:#444;line-height:1.8;margin:0;"><%= desc %></p>
        </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>
        <% if (cs.primaryRoles && cs.primaryRoles.length) { %>
        <div style="margin-bottom:12px;">
            <div class="tag-list">
                <% cs.primaryRoles.forEach(function(r){ %><span class="tag"><%= r %></span><% }); %>
            </div>
        </div>
        <% } %>
        <% if (cs.secondaryRoles && cs.secondaryRoles.length) { %>
        <div class="tag-list">
            <% cs.secondaryRoles.forEach(function(r){ %><span class="tag-grey"><%= r %></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>Your Strengths</div>
        <ul class="strength-list">
            <% cs.gapAnalysis.strengths.forEach(function(s){ %><li><%= s %></li><% }); %>
        </ul>
    </div>
    <% } %>

</div>

<!-- ── CAREER STRATEGY ── -->
<% if (segments.length > 0) { %>
<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>Your Positioning</div>
        <p style="font-size:14px;color:#333;line-height:1.8;margin:0;"><%= cs.search.positioning %></p>
    </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.label %>
            </p>

            <% if (seg.targetRoles && seg.targetRoles.length) { %>
            <div class="segment-section">
                <div class="segment-section-title">Target Roles</div>
                <div class="tag-list">
                    <% seg.targetRoles.forEach(function(r){ %><span class="tag"><%= r %></span><% }); %>
                </div>
            </div>
            <% } %>

            <% if (seg.targetSectors && seg.targetSectors.length) { %>
            <div class="segment-section">
                <div class="segment-section-title">Sectors</div>
                <div class="tag-list">
                    <% seg.targetSectors.forEach(function(s){ %><span class="tag-grey"><%= s %></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>
                    <span style="font-size:13px;font-weight:600;color:#333;"><%= seg.salaryRange %></span>
                </div>
                <% } %>
            </div>

            <% if (seg.keyNarrative) { %>
            <p class="segment-narrative"><%= seg.keyNarrative %></p>
            <% } %>

            <% if (seg.targetCompanies && seg.targetCompanies.length) { %>
            <p class="segment-companies">
                <span style="font-weight:600;">Target companies:</span>
                <%= seg.targetCompanies.join(', ') %>
            </p>
            <% } %>
        </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" style="margin-bottom:10px;">Strengths</div>
            <ul class="strength-list">
                <% cs.gapAnalysis.strengths.forEach(function(s){ %><li><%= s %></li><% }); %>
            </ul>
        </div>
        <% } %>

        <% if (cs.gapAnalysis.gapsVsTargetRoles && cs.gapAnalysis.gapsVsTargetRoles.length) { %>
        <div style="margin-bottom:18px;">
            <div class="dossier-section-title" style="margin-bottom:10px;">Areas to develop</div>
            <ul class="gap-list">
                <% cs.gapAnalysis.gapsVsTargetRoles.forEach(function(g){ %><li><%= g %></li><% }); %>
            </ul>
        </div>
        <% } %>

        <% if (cs.gapAnalysis.gapClosurePlan && cs.gapAnalysis.gapClosurePlan.length) { %>
        <div>
            <div class="dossier-section-title" style="margin-bottom:10px;">Action plan</div>
            <ul class="strength-list">
                <% cs.gapAnalysis.gapClosurePlan.forEach(function(p){ %><li><%= p %></li><% }); %>
            </ul>
        </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"><%= ep.weeklyTargets %></span></div>
        <% } %>
        <% if (ep.applicationApproach) { %>
        <div class="plan-row"><span class="plan-key">Applications</span><span class="plan-val"><%= ep.applicationApproach %></span></div>
        <% } %>
        <% if (ep.networkingApproach) { %>
        <div class="plan-row"><span class="plan-key">Networking</span><span class="plan-val"><%= ep.networkingApproach %></span></div>
        <% } %>
        <% if (ep.linkedinStrategy) { %>
        <div class="plan-row"><span class="plan-key">LinkedIn</span><span class="plan-val"><%= ep.linkedinStrategy %></span></div>
        <% } %>
        <% if (cs.strategy.timeline) { %>
        <div class="plan-row">
            <span class="plan-key">Timeline</span>
            <span class="plan-val">Target placement by <strong><%= cs.strategy.timeline.targetPlacementBy || '' %></strong></span>
        </div>
        <% } %>
    </div>
    <% } %>

    <% if (cs.interviewReadiness) { %>
    <div class="card">
        <div class="card-title"><span class="material-icons">record_voice_over</span>Interview Readiness</div>
        <% var ir = cs.interviewReadiness; %>
        <% if (ir.confidence) { %>
        <div class="plan-row"><span class="plan-key">Confidence</span><span class="plan-val"><%= ir.confidence %></span></div>
        <% } %>
        <% if (ir.salaryNegotiation) { %>
        <div class="plan-row"><span class="plan-key">Salary negotiation</span><span class="plan-val"><%= ir.salaryNegotiation %></span></div>
        <% } %>
        <% if (ir.notes) { %>
        <div class="plan-row"><span class="plan-key">Coach priority</span><span class="plan-val"><%= ir.notes %></span></div>
        <% } %>
    </div>
    <% } %>

</div>
<% } %>

<!-- ── MY FORM ── -->
<% if (form) { %>
<div id="tab-form" class="tab-pane">
    <% if (!formValidated) { %>
    <div class="validate-bar">
        <span class="material-icons">warning_amber</span>
        <span>Please review the information below and confirm it's correct.</span>
        <button class="btn-validate" id="btnValidateForm" onclick="validateSection('form')">
            <span class="material-icons" style="font-size:15px;">check_circle</span>Confirm & Save
        </button>
    </div>
    <% } %>
    <div class="card">
        <div class="card-title"><span class="material-icons">assignment</span>Profile Form</div>
        <div class="form-grid">

            <%# ── Current situation ── %>
            <div class="form-field">
                <label>Current (or most recent) job title</label>
                <input id="ff-current_position" value="<%= (form.answers && form.answers.current_position) || '' %>" placeholder="e.g. Head of Finance at Acme Corp">
            </div>
            <div class="form-field">
                <label>Current area of work</label>
                <input id="ff-current_area" value="<%= (form.answers && form.answers.current_area) || '' %>" placeholder="e.g. Finance & Accounting, Technology, HR">
            </div>
            <div class="form-field">
                <label>Annual bonus (if any)</label>
                <input id="ff-annual_bonus" value="<%= (form.answers && form.answers.annual_bonus) || '' %>" placeholder="e.g. ~15% of base, or 'none'">
            </div>
            <div class="form-field">
                <label>Phone (with country code)</label>
                <input id="ff-phone" value="<%= (form.answers && form.answers.phone) || '' %>" placeholder="+44 7700 900000">
            </div>
            <div class="form-field">
                <label>Full address</label>
                <input id="ff-address" value="<%= (form.answers && form.answers.address) || '' %>" placeholder="Street, City, Country">
            </div>
            <div class="form-field">
                <label>Date of birth</label>
                <input id="ff-date_of_birth" value="<%= (form.answers && form.answers.date_of_birth) || '' %>" placeholder="YYYY-MM-DD">
            </div>
            <div class="form-field">
                <label>Nationality</label>
                <input id="ff-nationality" value="<%= (form.answers && form.answers.nationality) || '' %>" placeholder="e.g. British, French">
            </div>
            <div class="form-field">
                <label>LinkedIn profile URL</label>
                <input id="ff-linkedin_url" value="<%= (form.answers && form.answers.linkedin_url) || '' %>" placeholder="https://linkedin.com/in/yourname">
            </div>

            <%# ── Career targets ── %>
            <div class="form-field" style="grid-column:1/-1;">
                <label>Area you want to move into</label>
                <input id="ff-desired_area" value="<%= (form.answers && form.answers.desired_area) || '' %>" placeholder="e.g. C-Suite Finance, Product Management">
            </div>
            <div class="form-field" style="grid-column:1/-1;">
                <label>Preferred sectors (not limiting, just a preference)</label>
                <input id="ff-preferred_sectors" value="<%= (form.answers && form.answers.preferred_sectors) || '' %>" placeholder="e.g. Tech, Finance, Industrial">
            </div>
            <div class="form-field" style="grid-column:1/-1;">
                <label>Specific companies to target (optional — write "none" if not)</label>
                <input id="ff-preferred_companies" value="<%= (form.answers && form.answers.preferred_companies) || '' %>" placeholder="e.g. LVMH, Nestlé, Goldman Sachs">
            </div>
            <div class="form-field" style="grid-column:1/-1;">
                <label>Other job titles you would consider</label>
                <textarea id="ff-open_roles" rows="2" placeholder="e.g. Senior HR Manager, Head of People, VP Talent"><%= (form.answers && form.answers.open_roles) || '' %></textarea>
            </div>
            <div class="form-field">
                <label>Target gross annual salary (with currency)</label>
                <input id="ff-desired_salary" value="<%= (form.answers && form.answers.desired_salary) || '' %>" placeholder="e.g. €120,000 / £95,000 / CHF 140,000">
            </div>
            <div class="form-field">
                <label>Open to relocating or working remotely?</label>
                <input id="ff-relocation_remote" value="<%= (form.answers && form.answers.relocation_remote) || '' %>" placeholder="e.g. Yes, open to relocate within Europe / Remote only">
            </div>
            <div class="form-field">
                <label>Type of company preferred</label>
                <input id="ff-preferred_company_type" value="<%= (form.answers && form.answers.preferred_company_type) || '' %>" placeholder="e.g. Startup, large corporate, remote-first, public sector">
            </div>
            <div class="form-field">
                <label>When do you want to start applying actively?</label>
                <input id="ff-job_search_start_date" value="<%= (form.answers && form.answers.job_search_start_date) || '' %>" placeholder="e.g. Immediately / January 2026">
            </div>

            <%# ── Goals & challenges ── %>
            <div class="form-field" style="grid-column:1/-1;">
                <label>Where do you want to be professionally in the next 6–12 months?</label>
                <textarea id="ff-professional_goal_6_12m" rows="3" placeholder="Describe your ideal situation in 6–12 months"><%= (form.answers && form.answers.professional_goal_6_12m) || '' %></textarea>
            </div>
            <div class="form-field" style="grid-column:1/-1;">
                <label>Biggest career challenge right now</label>
                <textarea id="ff-biggest_challenge" rows="2" placeholder="What is holding you back or making this harder?"><%= (form.answers && form.answers.biggest_challenge) || '' %></textarea>
            </div>
            <div class="form-field" style="grid-column:1/-1;">
                <label>How would you like to be perceived professionally?</label>
                <textarea id="ff-professional_perception" rows="2" placeholder="e.g. Strategic leader, innovative thinker, trusted finance advisor"><%= (form.answers && form.answers.professional_perception) || '' %></textarea>
            </div>

            <%# ── Readiness & tools ── %>
            <div class="form-field">
                <label>Do you have an up-to-date CV?</label>
                <input id="ff-updated_cv" value="<%= (form.answers && form.answers.updated_cv) || '' %>" placeholder="Yes / No / In progress">
            </div>
            <div class="form-field">
                <label>Have you recently updated your LinkedIn profile?</label>
                <input id="ff-linkedin_updated" value="<%= (form.answers && form.answers.linkedin_updated) || '' %>" placeholder="Yes / No / Partially">
            </div>
            <div class="form-field">
                <label>Have you ever used AI tools (like ChatGPT) for your career?</label>
                <input id="ff-used_ai_tools" value="<%= (form.answers && form.answers.used_ai_tools) || '' %>" placeholder="Yes / No / Occasionally">
            </div>
            <div class="form-field">
                <label>Interested in exploring digital & AI tools as part of your process?</label>
                <input id="ff-interested_in_ai" value="<%= (form.answers && form.answers.interested_in_ai) || '' %>" placeholder="Yes / No / Maybe">
            </div>

            <%# ── Process ── %>
            <div class="form-field">
                <label>How confident do you feel in job interviews?</label>
                <input id="ff-interview_confidence" value="<%= (form.answers && form.answers.interview_confidence) || '' %>" placeholder="e.g. Very confident / Nervous / It depends">
            </div>
            <div class="form-field">
                <label>Have you ever struggled to negotiate salary or stand out?</label>
                <input id="ff-salary_negotiation" value="<%= (form.answers && form.answers.salary_negotiation) || '' %>" placeholder="Yes / No / Sometimes">
            </div>
            <div class="form-field">
                <label>Hours per week available for job hunting</label>
                <input id="ff-weekly_hours" value="<%= (form.answers && form.answers.weekly_hours) || '' %>" placeholder="e.g. 5h / 10h / 20h">
            </div>
            <div class="form-field">
                <label>Applications sent per week now vs. target</label>
                <input id="ff-target_applications_week" value="<%= (form.answers && form.answers.target_applications_week) || '' %>" placeholder="e.g. Currently 2/week, aiming for 10/week">
            </div>

            <%# ── Additional ── %>
            <div class="form-field" style="grid-column:1/-1;">
                <label>Anything else you'd like to share to help us support you better?</label>
                <textarea id="ff-additional_notes" rows="3" placeholder="Any context, constraints, personal situation, or goals your coach should know"><%= (form.answers && form.answers.additional_notes) || '' %></textarea>
            </div>

        </div>
        <div style="margin-top:20px;display:flex;gap:10px;align-items:center;flex-wrap:wrap;">
            <button class="btn-save-edit" onclick="saveFormAnswers()">
                <span class="material-icons" style="font-size:16px;">save</span>Save Changes
            </button>
            <% if (!formValidated) { %>
            <button class="btn-validate" id="btnValidateForm2" onclick="validateSection('form')">
                <span class="material-icons" style="font-size:15px;">check_circle</span>Confirm & Save
            </button>
            <% } %>
            <div id="formSaveMsg" style="display:none;font-size:13px;color:#2e7d32;"></div>
        </div>
    </div>
</div>
<% } %>

<!-- ── CAREER DOSSIER ── -->
<% if (cvmaster) { %>
<div id="tab-dossier" class="tab-pane">
    <% if (!dossierValidated) { %>
    <div class="validate-bar">
        <span class="material-icons">warning_amber</span>
        <span>Please review your Career Dossier below and confirm the information is accurate.</span>
        <button class="btn-validate" onclick="validateSection('dossier')">
            <span class="material-icons" style="font-size:15px;">check_circle</span>Confirm & Save
        </button>
    </div>
    <% } %>
    <div class="card">
        <p class="dossier-headline"><%= cvmaster.headline %></p>
        <% if (cvmaster.narrative) { %><p class="dossier-summary"><%= cvmaster.narrative %></p><% } %>

        <% if (cvmaster.experience && cvmaster.experience.length) { %>
        <div class="dossier-section">
            <div class="dossier-section-title">Experience</div>
            <% cvmaster.experience.forEach(function(exp) { %>
            <div class="exp-entry">
                <p class="exp-title"><%= exp.title %></p>
                <p class="exp-company"><%= [exp.company, exp.location].filter(Boolean).join(' · ') %></p>
                <p class="exp-dates"><%= [exp.from, exp.to].filter(Boolean).join(' – ') %></p>
                <% if (exp.highlights && exp.highlights.length) { %>
                <ul class="exp-highlights">
                    <% exp.highlights.forEach(function(h){ %><li><%= h %></li><% }); %>
                </ul>
                <% } %>
            </div>
            <% }); %>
        </div>
        <% } %>

        <% if (cvmaster.education && cvmaster.education.length) { %>
        <div class="dossier-section">
            <div class="dossier-section-title">Education</div>
            <% cvmaster.education.forEach(function(edu) { %>
            <div class="exp-entry">
                <p class="exp-title"><%= edu.degree || edu.title || '' %></p>
                <p class="exp-company"><%= edu.institution || edu.school || '' %></p>
                <p class="exp-dates"><%= [edu.from, edu.to].filter(Boolean).join(' – ') || (edu.year || '') %></p>
            </div>
            <% }); %>
        </div>
        <% } %>

        <% if (cvmaster.skills && cvmaster.skills.length) { %>
        <div class="dossier-section">
            <div class="dossier-section-title">Skills</div>
            <div class="tag-list">
                <% cvmaster.skills.forEach(function(s){ %><span class="tag-grey"><%= s %></span><% }); %>
            </div>
        </div>
        <% } %>

        <% if (cvmaster.languages && cvmaster.languages.length) { %>
        <div class="dossier-section">
            <div class="dossier-section-title">Languages</div>
            <% cvmaster.languages.forEach(function(l) { %>
            <div class="lang-row">
                <span><%= l.language %></span>
                <span class="lang-level"><%= l.level %></span>
            </div>
            <% }); %>
        </div>
        <% } %>

        <% if (cvmaster.certifications && cvmaster.certifications.length) { %>
        <div class="dossier-section">
            <div class="dossier-section-title">Certifications</div>
            <div class="tag-list">
                <% cvmaster.certifications.forEach(function(c){ %><span class="tag-grey"><%= typeof c === 'string' ? c : c.name %></span><% }); %>
            </div>
        </div>
        <% } %>

        <% if (cvmaster.coachNotes) { %>
        <div class="dossier-section">
            <div class="dossier-section-title">Coach Notes</div>
            <div class="coach-notes"><%= cvmaster.coachNotes %></div>
        </div>
        <% } %>

        <% if (!dossierValidated) { %>
        <div style="margin-top:24px;padding-top:20px;border-top:1px solid #f0f0f0;display:flex;align-items:center;gap:12px;flex-wrap:wrap;">
            <span style="font-size:13px;color:#666;">Is everything above accurate?</span>
            <button class="btn-validate" id="btnValidateDossier" onclick="validateSection('dossier')">
                <span class="material-icons" style="font-size:15px;">check_circle</span>Confirm & Save
            </button>
        </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>
            <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 id="jt-empty" class="empty-state" style="<%= jobs.length ? 'display:none' : '' %>">No jobs tracked yet. Use Search Jobs to find and track opportunities.</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>

<!-- ── MY CVs ── -->
<div id="tab-cvs" class="tab-pane">
    <div class="card">
        <div class="card-title"><span class="material-icons">upload_file</span>Uploaded CVs</div>

        <div class="cv-file-row">
            <div class="cv-file-info">
                <span class="material-icons cv-file-icon" style="font-size:28px;"><%= hasPersonalCv ? 'picture_as_pdf' : 'picture_as_pdf' %></span>
                <div>
                    <div class="cv-file-name">Personal CV</div>
                    <div class="cv-file-status"><%= hasPersonalCv ? 'Uploaded' : 'Not yet uploaded' %></div>
                </div>
            </div>
            <% if (hasPersonalCv) { %>
            <a href="<%= BASE_PATH %>/db/mentees/<%= slug %>/cvs/cv-personal.pdf" target="_blank" class="btn-download">
                <span class="material-icons" style="font-size:16px;">download</span>
                Download
            </a>
            <% } else { %>
            <span style="font-size:12px;color:#bbb;">Send your CV in the WhatsApp group</span>
            <% } %>
        </div>

        <div class="cv-file-row">
            <div class="cv-file-info">
                <span class="material-icons cv-file-icon" style="font-size:28px;color:<%= hasLinkedinCv ? '#0077b5' : '#ccc' %>;">picture_as_pdf</span>
                <div>
                    <div class="cv-file-name">LinkedIn CV</div>
                    <div class="cv-file-status"><%= hasLinkedinCv ? 'Uploaded' : 'Not yet uploaded' %></div>
                </div>
            </div>
            <% if (hasLinkedinCv) { %>
            <a href="<%= BASE_PATH %>/db/mentees/<%= slug %>/cvs/cv-linkedin.pdf" target="_blank" class="btn-download">
                <span class="material-icons" style="font-size:16px;">download</span>
                Download
            </a>
            <% } else { %>
            <span style="font-size:12px;color:#bbb;">Send your LinkedIn CV in the WhatsApp group</span>
            <% } %>
        </div>
    </div>

    <% if (hasPersonalCv || hasLinkedinCv) { %>
    <div class="card" style="background:#f9fdf9;border:1px solid #e8f5e9;">
        <p style="font-size:13px;color:#555;margin:0;line-height:1.7;">
            <span class="material-icons" style="font-size:16px;vertical-align:middle;color:#28a745;">info</span>
            Your CVs are used by your coach and EcoBot to build tailored job applications. To update a CV, send the new version in your WhatsApp group.
        </p>
    </div>
    <% } %>
</div>

<!-- ── JOB SEARCH ── -->
<!-- ── EDIT ── -->
<div id="tab-edit" class="tab-pane">

    <!-- AI Update -->
    <div class="card">
        <div class="card-title"><span class="material-icons">auto_awesome</span>Update with AI</div>
        <p style="font-size:13px;color:#666;margin:0 0 14px;">Paste notes or a filled form. AI will update your profile automatically.</p>
        <div id="aiPanel" class="ai-panel" style="display:none;">
            <textarea id="aiText" placeholder="Paste your notes, a filled form, or any updated information here..."></textarea>
            <div style="margin-top:10px;text-align:right;display:flex;gap:8px;justify-content:flex-end;">
                <button class="btn-cancel-edit" onclick="document.getElementById('aiPanel').style.display='none'">Cancel</button>
                <button class="btn-save-edit" id="btnRunAi" onclick="runClientAi()">
                    <span class="material-icons" style="font-size:16px;">auto_awesome</span>Update
                </button>
            </div>
        </div>
        <div id="aiResult" style="display:none;background:#e8f5e9;padding:10px 14px;border-radius:5px;font-size:13px;color:#2e7d32;margin-bottom:12px;"></div>
        <button class="btn-edit-profile" id="btnOpenAi" onclick="document.getElementById('aiPanel').style.display='block';this.style.display='none'">
            <span class="material-icons" style="font-size:15px;">auto_awesome</span>Open AI Update
        </button>
    </div>

    <!-- Manual Edit -->
    <div class="card">
        <div class="card-title"><span class="material-icons">manage_accounts</span>Edit Profile</div>
        <div id="editForm">
            <div class="info-grid" style="gap:16px;">
                <div class="info-item">
                    <label>Phone</label>
                    <input class="edit-field" id="inp-phone" value="<%= cs.phone || '' %>" placeholder="+351 ...">
                </div>
                <div class="info-item">
                    <label>Location</label>
                    <input class="edit-field" id="inp-location" value="<%= cs.location || '' %>" placeholder="City, Country">
                </div>
                <div class="info-item">
                    <label>LinkedIn</label>
                    <input class="edit-field" id="inp-linkedin" value="<%= cs.linkedin || (cvmaster && cvmaster.contact && cvmaster.contact.linkedin) || '' %>" placeholder="linkedin.com/in/...">
                </div>
                <div class="info-item">
                    <label>Nationality</label>
                    <input class="edit-field" id="inp-nationality" value="<%= cs.nationality || '' %>" placeholder="Portuguese, ...">
                </div>
                <div class="info-item">
                    <label>Salary Target</label>
                    <input class="edit-field" id="inp-salaryTarget" value="<%= cs.salaryTarget || '' %>" placeholder="e.g. 80,000 CHF">
                </div>
                <div class="info-item">
                    <label>Languages <span style="font-weight:400;color:#bbb;">(comma-separated)</span></label>
                    <input class="edit-field" id="inp-languages" value="<%= (cs.languages || []).join(', ') %>" placeholder="English, French, Portuguese">
                </div>
                <div class="info-item">
                    <label>Work Permits <span style="font-weight:400;color:#bbb;">(comma-separated)</span></label>
                    <input class="edit-field" id="inp-workPermits" value="<%= (cs.workPermits || []).join(', ') %>" placeholder="CH, EU, ...">
                </div>
                <div class="info-item">
                    <label>Target Geographies <span style="font-weight:400;color:#bbb;">(comma-separated)</span></label>
                    <input class="edit-field" id="inp-targetGeographies" value="<%= (cs.targetGeographies || []).join(', ') %>" placeholder="Switzerland, Germany, ...">
                </div>
                <div class="info-item">
                    <label>Exclusions <span style="font-weight:400;color:#bbb;">(keywords to filter out)</span></label>
                    <input class="edit-field" id="inp-exclusions" value="<%= (cs.exclusions || []).join(', ') %>" placeholder="Junior, Intern, ...">
                </div>
                <div class="info-item" style="grid-column:1/-1;">
                    <label>Short Description</label>
                    <textarea class="edit-field" id="inp-shortDescription" rows="3" placeholder="A short professional summary..."><%= cs.shortDescription || '' %></textarea>
                </div>
            </div>
            <div style="margin-top:14px;display:flex;gap:14px;align-items:center;flex-wrap:wrap;">
                <label style="display:flex;align-items:center;gap:6px;font-size:13px;color:#555;cursor:pointer;">
                    <input type="checkbox" id="inp-openToRemote" <%= cs.openToRemote ? 'checked' : '' %>> Open to Remote
                </label>
                <label style="display:flex;align-items:center;gap:6px;font-size:13px;color:#555;cursor:pointer;">
                    <input type="checkbox" id="inp-openToRelocate" <%= cs.openToRelocate ? 'checked' : '' %>> Open to Relocate
                </label>
            </div>
            <div style="margin-top:20px;display:flex;gap:10px;align-items:center;">
                <button class="btn-save-edit" onclick="saveProfileEdit()">
                    <span class="material-icons" style="font-size:16px;">save</span>Save Changes
                </button>
                <div id="editMsg" style="display:none;font-size:13px;"></div>
            </div>
        </div>
    </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;">
        <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>
      </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="Notes…"></textarea>
      </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>

<!-- ── 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;">
    <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>
    <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>
    <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>
      <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>
      <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;" 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>
    <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>

<!-- ── A4 CV / Cover Letter modal ── -->
<div id="cv-a4-modal" style="display:none;">
  <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>
  </div>
  <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>
  <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>

<script>
    var BASE = '/admin';
    var SLUG = '<%= slug %>';
    var JOBS = <%- JSON.stringify(jobs) %>;
    var CURRENT_PROFILE = <%- JSON.stringify(cs) %>;
    var _jobsData = JOBS;
    var _currentJobId = null;

    // ── Welcome modal ──────────────────────────────────────────────────
    function closeWelcomeModal() {
        var el = document.getElementById('welcomeModal');
        if (el) {
            el.style.opacity = '0';
            el.style.transition = 'opacity 0.2s';
            setTimeout(function(){ el.remove(); }, 200);
        }
        try { sessionStorage.setItem('ecobe_welcomed_' + SLUG, '1'); } catch(e) {}
    }
    // Only show once per session
    (function(){
        try {
            if (sessionStorage.getItem('ecobe_welcomed_' + SLUG)) {
                var el = document.getElementById('welcomeModal');
                if (el) el.remove();
            }
        } catch(e) {}
    })();

    // ── Validate form / dossier ────────────────────────────────────────
    async function validateSection(type) {
        var btns = type === 'form'
            ? [document.getElementById('btnValidateForm'), document.getElementById('btnValidateForm2')]
            : [document.getElementById('btnValidateDossier')];
        btns.forEach(function(b){ if(b){ b.disabled = true; b.innerHTML = '<span class="material-icons" style="font-size:15px;">hourglass_empty</span>Saving…'; } });

        if (type === 'form') {
            await saveFormAnswers(true); // save first, then validate
        }

        try {
            var r = await fetch(BASE + '/api/client/validate', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ type: type })
            });
            var d = await r.json();
            if (!d.success) throw new Error(d.error || 'Failed');
            // Remove badges and bars
            if (type === 'form') {
                document.querySelectorAll('#tab-form .validate-bar').forEach(function(el){ el.remove(); });
                document.querySelectorAll('#tab-form .btn-validate').forEach(function(el){ el.remove(); });
                document.querySelectorAll('.tab-btn').forEach(function(btn){
                    if (btn.onclick && btn.onclick.toString().includes("'form'")) {
                        btn.querySelectorAll('.warn-badge').forEach(function(b){ b.remove(); });
                    }
                });
                showFormMsg('✓ Profile form confirmed. Thank you!', '#2e7d32');
            } else {
                document.querySelectorAll('#tab-dossier .validate-bar').forEach(function(el){ el.remove(); });
                document.querySelectorAll('#tab-dossier .btn-validate').forEach(function(el){ el.remove(); });
                document.querySelectorAll('.tab-btn').forEach(function(btn){
                    if (btn.onclick && btn.onclick.toString().includes("'dossier'")) {
                        btn.querySelectorAll('.warn-badge').forEach(function(b){ b.remove(); });
                    }
                });
            }
        } catch(e) {
            btns.forEach(function(b){ if(b){ b.disabled = false; b.innerHTML = '<span class="material-icons" style="font-size:15px;">check_circle</span>Confirm & Save'; } });
            alert('Error: ' + e.message);
        }
    }

    // ── Save form answers ──────────────────────────────────────────────
    async function saveFormAnswers(silent) {
        var fields = [
            'current_position','current_area','annual_bonus','desired_area','preferred_sectors',
            'preferred_companies','open_roles','desired_salary','date_of_birth','address',
            'phone','linkedin_url','nationality','relocation_remote','professional_goal_6_12m',
            'biggest_challenge','updated_cv','linkedin_updated','professional_perception',
            'used_ai_tools','interested_in_ai','interview_confidence','salary_negotiation',
            'weekly_hours','additional_notes','target_applications_week','preferred_company_type',
            'job_search_start_date'
        ];
        var answers = {};
        fields.forEach(function(f){
            var el = document.getElementById('ff-' + f);
            if (el) answers[f] = el.value.trim() || null;
        });

        try {
            var r = await fetch(BASE + '/api/profile/' + SLUG + '/form', {
                method: 'PUT',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ answers: answers })
            });
            var d = await r.json();
            if (!d.success) throw new Error(d.error || 'Failed');
            if (!silent) showFormMsg('✓ Saved', '#2e7d32');
        } catch(e) {
            if (!silent) showFormMsg('Error: ' + e.message, '#c0392b');
        }
    }

    function showFormMsg(msg, color) {
        var el = document.getElementById('formSaveMsg');
        if (!el) return;
        el.textContent = msg;
        el.style.color = color || '#2e7d32';
        el.style.display = 'inline';
        setTimeout(function(){ el.style.display = 'none'; }, 3000);
    }

    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();
    }

    // ── Edit Profile ──
    function splitTags(str) {
        return str.split(',').map(function(s){ return s.trim(); }).filter(Boolean);
    }
    function saveProfileEdit() {
        var btn = document.querySelector('#editForm .btn-save-edit');
        btn.disabled = true;
        var msg = document.getElementById('editMsg');
        msg.style.display = 'none';
        var body = {
            phone:              document.getElementById('inp-phone').value.trim(),
            location:           document.getElementById('inp-location').value.trim(),
            linkedin:           document.getElementById('inp-linkedin').value.trim(),
            nationality:        document.getElementById('inp-nationality').value.trim(),
            salaryTarget:       document.getElementById('inp-salaryTarget').value.trim(),
            shortDescription:   document.getElementById('inp-shortDescription').value.trim(),
            languages:          splitTags(document.getElementById('inp-languages').value),
            workPermits:        splitTags(document.getElementById('inp-workPermits').value),
            targetGeographies:  splitTags(document.getElementById('inp-targetGeographies').value),
            exclusions:         splitTags(document.getElementById('inp-exclusions').value),
            openToRemote:       document.getElementById('inp-openToRemote').checked,
            openToRelocate:     document.getElementById('inp-openToRelocate').checked
        };
        fetch(BASE + '/api/client/profile', {
            method: 'PUT',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(body)
        })
        .then(function(r){ return r.json(); })
        .then(function(data) {
            if (data.success) {
                msg.textContent = 'Saved!'; msg.style.color = '#2e7d32'; msg.style.display = 'block';
                setTimeout(function(){ msg.style.display = 'none'; }, 2500);
            } else {
                msg.textContent = 'Error: ' + (data.error || 'Save failed');
                msg.style.color = '#c62828'; msg.style.display = 'block';
            }
            btn.disabled = false;
        })
        .catch(function() {
            msg.textContent = 'Connection error'; msg.style.color = '#c62828'; msg.style.display = 'block';
            btn.disabled = false;
        });
    }

    // ── AI Update ──
    function runClientAi() {
        var text = document.getElementById('aiText').value.trim();
        if (!text) { alert('Paste some text first.'); return; }
        var btn = document.getElementById('btnRunAi');
        btn.disabled = true; btn.innerHTML = '<span class="material-icons" style="font-size:16px;">hourglass_top</span>Processing...';
        fetch(BASE + '/api/client/ai-update', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ text: text })
        })
        .then(function(r){ return r.json(); })
        .then(function(data) {
            if (data.success) {
                document.getElementById('aiPanel').style.display = 'none';
                document.getElementById('btnOpenAi').style.display = 'inline-flex';
                var res = document.getElementById('aiResult');
                res.textContent = 'Profile updated! Reload to see changes.';
                res.style.display = 'block';
            } else {
                alert('Error: ' + (data.error || 'AI failed'));
            }
            btn.disabled = false; btn.innerHTML = '<span class="material-icons" style="font-size:16px;">auto_awesome</span>Update';
        })
        .catch(function() {
            alert('Connection error');
            btn.disabled = false; btn.innerHTML = '<span class="material-icons" style="font-size:16px;">auto_awesome</span>Update';
        });
    }

    // ── Job Tracking ──
    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'
    };
    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
    };

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

    var _jtSortCol = 'status';
    var _jtSortDir = 1;

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

    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'; }
      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';
      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);
    }

    // ── 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;
      try {
        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'; }
        }
      } catch(e) {
        document.getElementById('cva-loading').style.display = 'none';
        var paper = document.getElementById('cva-paper');
        paper.style.display = '';
        paper.innerHTML = '<p style="color:red;">Error: ' + e.message + '</p>';
      } finally {
        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 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(BASE + '/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) {
          var job = _jobsData.find(function(j){ return j.id === _currentJobId; });
          if (job) Object.assign(job, updates);
          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();
    }

    // ── 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 || '';
    }

    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) + '</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; }
      _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 text = e.text || (e.action === 'profile_edit' ? 'Edited profile (' + (e.fields||[]).join(', ') + ')'
                         : e.action === 'ai_update' ? 'AI profile update'
                         : e.action === 'cv_edit'   ? 'Edited CV'
                         : e.action || 'Change');
                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-action" style="flex:1;">' + text + '</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>
</body>
</html>
