<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>EcoBot - Dashboard</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">
    <!-- Client-side document parsers (no server packages needed) -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.16.105/pdf.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/mammoth@1.4.2/mammoth.browser.min.js"></script>
    <style>
        .dashboard-header { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 12px; }
        .btn-new-mentee {
            display: inline-flex; align-items: center; gap: 6px;
            background: #28a745; color: white; border: none; padding: 10px 18px;
            border-radius: 6px; font-family: 'Ubuntu', sans-serif; font-size: 14px;
            font-weight: 600; cursor: pointer; transition: background 0.2s;
        }
        .btn-new-mentee:hover { background: #218838; }
        .btn-logout { display: inline-flex; align-items: center; gap: 6px; }

        .modal-overlay {
            display: none; position: fixed; inset: 0;
            background: rgba(0,0,0,0.5); z-index: 1000;
            align-items: center; justify-content: center; padding: 20px;
        }
        .modal-overlay.active { display: flex; }
        .modal {
            background: white; border-radius: 12px; width: 100%; max-width: 640px;
            max-height: 90vh; overflow-y: auto;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
            animation: modalIn 0.2s ease;
        }
        @keyframes modalIn { from { opacity:0; transform:translateY(-20px); } to { opacity:1; transform:translateY(0); } }
        .modal-header {
            background: linear-gradient(135deg,#28a745,#20c997);
            padding: 22px 28px; border-radius: 12px 12px 0 0;
            display: flex; align-items: center; justify-content: space-between;
            position: sticky; top: 0; z-index: 1;
        }
        .modal-header h2 { color: white; margin: 0; font-size: 19px; }
        .modal-close { background: none; border: none; color: white; cursor: pointer; padding: 4px; opacity: 0.8; }
        .modal-close:hover { opacity: 1; }
        .modal-body { padding: 26px 28px; }
        .modal-footer { padding: 0 28px 24px; display: flex; gap: 10px; justify-content: flex-end; }

        .steps { display: flex; margin-bottom: 22px; }
        .step { flex: 1; text-align: center; padding: 8px 4px; font-size: 13px; font-weight: 500; color: #999; border-bottom: 3px solid #e0e0e0; transition: all 0.2s; }
        .step.active { color: #28a745; border-color: #28a745; }
        .step.done { color: #28a745; border-color: #28a745; opacity: 0.5; }

        .field-group { margin-bottom: 15px; }
        .field-group label { display: block; font-size: 13px; font-weight: 500; color: #444; margin-bottom: 5px; }
        .field-group input, .field-group textarea, .field-group select {
            width: 100%; padding: 10px 13px; border: 1.5px solid #ddd; border-radius: 6px;
            font-family: 'Ubuntu', sans-serif; font-size: 14px; transition: border-color 0.2s; box-sizing: border-box;
            background: white;
        }
        .field-group input:focus, .field-group textarea:focus, .field-group select:focus { outline: none; border-color: #28a745; }
        .field-group textarea { resize: vertical; min-height: 70px; }
        .field-row { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; }

        .upload-area {
            border: 2px dashed #ccc; border-radius: 8px; padding: 18px; text-align: center;
            cursor: pointer; transition: all 0.2s; position: relative; margin-bottom: 12px;
        }
        .upload-area:hover { border-color: #28a745; background: #f6fff8; }
        .upload-area.has-file { border-color: #28a745; background: #f0fff4; }
        .upload-area.loading-file { border-color: #ffc107; background: #fffdf0; }
        .upload-area input[type=file] { position: absolute; inset: 0; opacity: 0; cursor: pointer; width: 100%; height: 100%; }
        .upload-icon { color: #28a745; font-size: 28px; }
        .upload-area p { margin: 5px 0 2px; font-size: 13px; color: #555; }
        .upload-area small { color: #999; font-size: 12px; }
        .file-name { font-size: 13px; color: #28a745; font-weight: 500; margin-top: 4px; }
        .upload-label { font-size: 13px; font-weight: 500; color: #444; margin-bottom: 6px; display: block; }
        .autofill-badge {
            display: none; align-items: center; gap: 5px; font-size: 12px;
            color: #2e7d32; background: #e8f5e9; padding: 3px 10px; border-radius: 20px;
            margin-top: 6px; width: fit-content;
        }
        .autofill-badge.visible { display: inline-flex; }

        .preview-grid { display: grid; gap: 12px; }
        .preview-field label { display: block; font-size: 11px; font-weight: 600; color: #28a745; text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 3px; }
        .preview-field input, .preview-field textarea, .preview-field select {
            width: 100%; padding: 8px 11px; border: 1.5px solid #e0e0e0; border-radius: 5px;
            font-family: 'Ubuntu', sans-serif; font-size: 13px; box-sizing: border-box; background: white;
        }
        .preview-field input:focus, .preview-field textarea:focus, .preview-field select:focus { outline: none; border-color: #28a745; }
        .preview-field textarea { resize: vertical; min-height: 56px; }

        .ai-badge {
            display: none; align-items: center; gap: 5px;
            background: #e8f5e9; color: #2e7d32; padding: 5px 12px;
            border-radius: 20px; font-size: 12px; font-weight: 500; margin-bottom: 16px;
        }
        .ai-badge.visible { display: inline-flex; }

        .btn { padding: 10px 20px; border-radius: 6px; font-family: 'Ubuntu', sans-serif; font-size: 14px; font-weight: 600; cursor: pointer; border: none; transition: all 0.2s; display: inline-flex; align-items: center; gap: 6px; }
        .btn-primary { background: #28a745; color: white; }
        .btn-primary:hover { background: #218838; }
        .btn-primary:disabled { background: #aaa; cursor: not-allowed; }
        .btn-secondary { background: white; color: #555; border: 1.5px solid #ddd; }
        .btn-secondary:hover { border-color: #999; }

        .loading { display: none; flex-direction: column; align-items: center; padding: 40px 28px; gap: 14px; }
        .loading.active { display: flex; }
        .spinner { width: 38px; height: 38px; border: 3px solid #e0e0e0; border-top-color: #28a745; border-radius: 50%; animation: spin 0.8s linear infinite; }
        @keyframes spin { to { transform: rotate(360deg); } }
        .loading p { color: #555; font-size: 14px; text-align: center; }

        .error-box { background: #fee2e2; color: #dc2626; padding: 10px 14px; border-radius: 6px; font-size: 13px; margin-bottom: 14px; display: none; }
        .error-box.active { display: block; }
        .section-divider { font-size: 11px; font-weight: 700; color: #28a745; text-transform: uppercase; letter-spacing: 0.6px; margin: 18px 0 10px; border-bottom: 1px solid #e8f5e9; padding-bottom: 4px; }
        .hint { font-size: 12px; color: #888; margin-top: 4px; }

        /* Extraction overlay */
        .extract-overlay {
            display: none; position: absolute; inset: 0;
            background: rgba(255,255,255,0.92); border-radius: 0 0 12px 12px;
            z-index: 10; flex-direction: column; align-items: center; justify-content: center;
            gap: 16px; backdrop-filter: blur(2px);
        }
        .extract-overlay.active { display: flex; }
        .extract-spinner {
            width: 44px; height: 44px;
            border: 3px solid #e0e0e0; border-top-color: #28a745;
            border-radius: 50%; animation: spin 0.8s linear infinite;
        }
        .extract-msg { font-size: 14px; font-weight: 600; color: #333; }
        .extract-sub { font-size: 12px; color: #888; margin-top: -8px; }

        /* ── Professional Dashboard Layout ── */
        body { display: block; background: #f0f4f0; min-height: 100vh; }

        .top-bar {
            background: white; box-shadow: 0 2px 8px rgba(0,0,0,0.08);
            padding: 0 32px; display: flex; align-items: center;
            justify-content: space-between; height: 64px;
            position: sticky; top: 0; z-index: 100;
        }
        .top-bar-logo { font-size: 22px; font-weight: 700; color: #28a745; letter-spacing: -0.5px; }
        .top-bar-logo span { color: #aaa; font-weight: 300; font-size: 16px; margin-left: 10px; }
        .top-bar-actions { display: flex; align-items: center; gap: 10px; }
        .tb-btn {
            display: inline-flex; align-items: center; gap: 6px;
            background: #28a745; color: white; border: none; padding: 9px 18px;
            border-radius: 6px; font-family: 'Ubuntu', sans-serif; font-size: 13px;
            font-weight: 600; cursor: pointer; transition: background 0.2s;
        }
        .tb-btn:hover { background: #218838; }
        .tb-btn-ghost {
            display: inline-flex; align-items: center; gap: 5px;
            background: none; border: 1px solid #ddd; color: #666;
            padding: 8px 14px; border-radius: 6px; font-family: 'Ubuntu', sans-serif;
            font-size: 13px; cursor: pointer; text-decoration: none; transition: all 0.15s;
        }
        .tb-btn-ghost:hover { border-color: #999; color: #333; }

        .dash-body { max-width: 1280px; margin: 0 auto; padding: 28px 32px 60px; }

        .dash-hero {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
            border-radius: 12px; padding: 28px 32px; margin-bottom: 28px;
            display: flex; align-items: center; justify-content: space-between; gap: 20px;
        }
        .dash-hero-text h2 { color: white; font-size: 22px; margin: 0 0 4px; }
        .dash-hero-text p  { color: rgba(255,255,255,0.8); font-size: 14px; margin: 0; }
        .dash-stats { display: flex; gap: 20px; }
        .stat-pill {
            background: rgba(255,255,255,0.2); border-radius: 8px; padding: 10px 18px;
            text-align: center; color: white; min-width: 72px;
        }
        .stat-pill-num { font-size: 24px; font-weight: 700; line-height: 1; }
        .stat-pill-lbl { font-size: 11px; opacity: 0.85; margin-top: 3px; text-transform: uppercase; letter-spacing: 0.5px; }

        .section-bar {
            display: flex; align-items: center; justify-content: space-between;
            margin-bottom: 16px;
        }
        .section-bar h3 { font-size: 16px; font-weight: 600; color: #333; margin: 0; }
        .filter-tabs { display: flex; gap: 4px; }
        .filter-tab {
            padding: 5px 14px; border-radius: 20px; font-size: 12px; font-weight: 600;
            cursor: pointer; border: none; background: #e8f5e9; color: #2e7d32;
            font-family: 'Ubuntu', sans-serif; transition: all 0.15s;
        }
        .filter-tab:hover { background: #c8e6c9; }
        .filter-tab.active { background: #28a745; color: white; }

        .mentees-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
            gap: 16px;
        }

        .mentee-card {
            background: white; border-radius: 10px;
            border-left: 5px solid #aaa;
            box-shadow: 0 1px 6px rgba(0,0,0,0.06);
            cursor: pointer; transition: transform 0.18s, box-shadow 0.18s;
            overflow: hidden; position: relative;
        }
        .mentee-card:hover { transform: translateY(-3px); box-shadow: 0 6px 20px rgba(0,0,0,0.1); }
        .mentee-card.plan-silver  { border-left-color: #9e9e9e; }
        .mentee-card.plan-golden  { border-left-color: #f9a825; }
        .mentee-card.plan-platinum { border-left-color: #7e57c2; }

        .mc-body { padding: 18px 18px 14px; }
        .mc-avatar {
            width: 38px; height: 38px; border-radius: 50%;
            display: flex; align-items: center; justify-content: center;
            font-size: 15px; font-weight: 700; color: white; margin-bottom: 12px;
            flex-shrink: 0;
        }
        .plan-silver  .mc-avatar { background: #9e9e9e; }
        .plan-golden  .mc-avatar { background: #f9a825; }
        .plan-platinum .mc-avatar { background: #7e57c2; }

        .mc-name { font-size: 14px; font-weight: 700; color: #222; margin: 0 0 3px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
        .mc-email { font-size: 12px; color: #888; margin: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }

        .mc-footer {
            padding: 8px 18px; background: #fafafa; border-top: 1px solid #f0f0f0;
            display: flex; align-items: center; justify-content: space-between;
        }
        .plan-badge {
            font-size: 10px; font-weight: 700; padding: 2px 8px; border-radius: 10px;
            text-transform: uppercase; letter-spacing: 0.5px;
        }
        .plan-silver  .plan-badge { background: #f5f5f5; color: #757575; }
        .plan-golden  .plan-badge { background: #fff8e1; color: #f57f17; }
        .plan-platinum .plan-badge { background: #ede7f6; color: #5e35b1; }
        .status-dot { width: 7px; height: 7px; border-radius: 50%; display: inline-block; margin-right: 4px; }
        .status-dot.active   { background: #28a745; }
        .status-dot.inactive { background: #bbb; }
        .status-label { font-size: 11px; color: #aaa; font-weight: 500; }

        .empty-state { text-align: center; padding: 60px 20px; color: #bbb; }
        .empty-state .material-icons { font-size: 48px; display: block; margin-bottom: 12px; }
        .empty-state p { font-size: 14px; }
    </style>
</head>
<body>
    <!-- Top bar -->
    <div class="top-bar">
        <div class="top-bar-logo">EcoBot<span>Admin</span></div>
        <div class="top-bar-actions">
            <button class="tb-btn" onclick="openModal()">
                <span class="material-icons" style="font-size:17px;">person_add</span>New Mentee
            </button>
            <a href="/admin/logout" class="tb-btn-ghost">
                <span class="material-icons" style="font-size:16px;">logout</span>Logout
            </a>
        </div>
    </div>

    <div class="dash-body">
        <%
          var total    = (mentees || []).length;
          var active   = (mentees || []).filter(m => m.status === 'active').length;
          var inactive = total - active;
        %>
        <!-- Hero -->
        <div class="dash-hero">
            <div class="dash-hero-text">
                <h2>Welcome back, <%= username.split('@')[0] %>!</h2>
                <p>Manage your mentees and track their career progress.</p>
            </div>
            <div class="dash-stats">
                <div class="stat-pill">
                    <div class="stat-pill-num"><%= total %></div>
                    <div class="stat-pill-lbl">Total</div>
                </div>
                <div class="stat-pill">
                    <div class="stat-pill-num"><%= active %></div>
                    <div class="stat-pill-lbl">Active</div>
                </div>
                <div class="stat-pill">
                    <div class="stat-pill-num"><%= inactive %></div>
                    <div class="stat-pill-lbl">Inactive</div>
                </div>
            </div>
        </div>

        <!-- Section bar + filter -->
        <div class="section-bar">
            <h3>Mentees</h3>
            <div class="filter-tabs">
                <button class="filter-tab active" onclick="filterMentees('all', this)">All</button>
                <button class="filter-tab" onclick="filterMentees('active', this)">Active</button>
                <button class="filter-tab" onclick="filterMentees('inactive', this)">Inactive</button>
                <button class="filter-tab" onclick="filterMentees('silver', this)">Silver</button>
                <button class="filter-tab" onclick="filterMentees('golden', this)">Golden</button>
                <button class="filter-tab" onclick="filterMentees('platinum', this)">Platinum</button>
            </div>
        </div>

        <!-- Mentees grid -->
        <div id="menteesGrid" class="mentees-grid">
            <% if (mentees && mentees.length > 0) { %>
                <% mentees.forEach(mentee => {
                    const planClass = 'plan-' + (mentee.plan || 'silver');
                    const initials = (mentee.name || '?').trim().split(' ').map(w => w[0]).join('').slice(0,2).toUpperCase();
                    const planLabel = { silver: 'Silver', golden: 'Golden', platinum: 'Platinum' }[mentee.plan] || 'Silver';
                    const isActive = mentee.status !== 'inactive';
                %>
                <div class="mentee-card <%= planClass %>"
                     data-plan="<%= mentee.plan || 'silver' %>"
                     data-status="<%= mentee.status || 'active' %>"
                     onclick="window.location.href='/admin/profile/<%= mentee.slug %>'">
                    <div class="mc-body">
                        <div class="mc-avatar"><%= initials %></div>
                        <div class="mc-name" title="<%= mentee.name %>"><%= mentee.name %></div>
                        <div class="mc-email" title="<%= mentee.email %>"><%= mentee.email || '—' %></div>
                    </div>
                    <div class="mc-footer">
                        <span class="plan-badge"><%= planLabel %></span>
                        <span>
                            <span class="status-dot <%= isActive ? 'active' : 'inactive' %>"></span>
                            <span class="status-label"><%= isActive ? 'Active' : 'Inactive' %></span>
                        </span>
                    </div>
                </div>
                <% }); %>
            <% } else { %>
                <div class="empty-state" style="grid-column:1/-1;">
                    <span class="material-icons">group_off</span>
                    <p>No mentees yet. Click <strong>New Mentee</strong> to add one.</p>
                </div>
            <% } %>
        </div>
    </div>

    <!-- ===================== CREATE MENTEE MODAL ===================== -->
    <div class="modal-overlay" id="createModal">
        <div class="modal">
            <div class="modal-header">
                <h2 id="modalTitle">New Mentee</h2>
                <button class="modal-close" onclick="closeModal()"><span class="material-icons">close</span></button>
            </div>

            <!-- STEP 1 -->
            <div id="step1" style="position:relative;">
                <!-- Extraction overlay -->
                <div class="extract-overlay" id="extractOverlay">
                    <div class="extract-spinner"></div>
                    <div class="extract-msg">Extracting data from CV…</div>
                    <div class="extract-sub">AI is reading the document, please wait</div>
                </div>

                <div class="modal-body">
                    <div class="steps">
                        <div class="step active">1 — Profile Info</div>
                        <div class="step" id="stepDot2">2 — Review & Confirm</div>
                    </div>

                    <div id="errorBox" class="error-box"></div>

                    <div class="section-divider">CV Upload</div>
                    <p class="hint" style="margin-bottom:12px;">Upload the client's CV and the AI will automatically fill in the fields below.</p>

                    <div class="field-row">
                        <div>
                            <span class="upload-label">CV (PDF or DOCX)</span>
                            <div class="upload-area" id="cvDropZone">
                                <input type="file" id="cvFile" accept=".pdf,.docx,application/pdf,application/vnd.openxmlformats-officedocument.wordprocessingml.document" onchange="handleFile('cv', this)" />
                                <span class="material-icons upload-icon">description</span>
                                <p>Click or drag CV here</p>
                                <small>PDF or DOCX</small>
                                <div class="file-name" id="cvFileName"></div>
                            </div>
                        </div>
                        <div>
                            <span class="upload-label">LinkedIn CV — optional</span>
                            <div class="upload-area" id="linkedinDropZone">
                                <input type="file" id="linkedinFile" accept=".pdf,.docx,application/pdf,application/vnd.openxmlformats-officedocument.wordprocessingml.document" onchange="handleFile('linkedin', this)" />
                                <span class="material-icons upload-icon">link</span>
                                <p>Click or drag LinkedIn CV</p>
                                <small>PDF or DOCX</small>
                                <div class="file-name" id="linkedinFileName"></div>
                            </div>
                        </div>
                    </div>

                    <div class="autofill-badge" id="autofillBadge">
                        <span class="material-icons" style="font-size:14px;">auto_awesome</span>
                        Fields auto-filled from CV — please review
                    </div>

                    <div class="section-divider">Basic Information</div>

                    <div class="field-row">
                        <div class="field-group">
                            <label>Full Name *</label>
                            <input type="text" id="inputName" placeholder="e.g. John Smith" />
                        </div>
                        <div class="field-group">
                            <label>Email *</label>
                            <input type="email" id="inputEmail" placeholder="john@email.com" />
                        </div>
                    </div>
                    <div class="field-row">
                        <div class="field-group">
                            <label>Phone *</label>
                            <input type="text" id="inputPhone" placeholder="+44 7700 900000" />
                        </div>
                        <div class="field-group">
                            <label>Plan *</label>
                            <select id="inputPlan">
                                <option value="">Select plan…</option>
                                <option value="silver">Silver</option>
                                <option value="golden">Golden</option>
                                <option value="platinum">Platinum</option>
                            </select>
                        </div>
                    </div>
                    <div class="field-group">
                        <label>Brief Description *</label>
                        <textarea id="inputDesc" placeholder="e.g. Finance executive targeting C-Level roles in the energy sector"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" onclick="closeModal()">Cancel</button>
                    <button class="btn btn-primary" id="btnGenerate" onclick="generateProfile()">
                        <span class="material-icons" style="font-size:16px;">auto_awesome</span>
                        Generate Full Profile
                    </button>
                </div>
            </div>

            <!-- LOADING -->
            <div class="loading" id="loadingSection">
                <div class="spinner"></div>
                <p id="loadingMsg">AI is analysing the CV and building the profile…</p>
            </div>

            <!-- STEP 2 -->
            <div id="step2" style="display:none;">
                <div class="modal-body">
                    <div class="steps">
                        <div class="step done">1 — Profile Info</div>
                        <div class="step active">2 — Review & Confirm</div>
                    </div>

                    <div class="ai-badge" id="aiBadge">
                        <span class="material-icons" style="font-size:15px;">auto_awesome</span>
                        AI-generated profile — review and confirm before creating
                    </div>

                    <div class="preview-grid">
                        <div class="section-divider">Basic Information</div>
                        <div class="field-row">
                            <div class="preview-field">
                                <label>Full Name *</label>
                                <input type="text" id="pvName" />
                            </div>
                            <div class="preview-field">
                                <label>Email *</label>
                                <input type="email" id="pvEmail" />
                            </div>
                        </div>
                        <div class="field-row">
                            <div class="preview-field">
                                <label>Phone</label>
                                <input type="text" id="pvPhone" />
                            </div>
                            <div class="preview-field">
                                <label>LinkedIn</label>
                                <input type="text" id="pvLinkedin" />
                            </div>
                        </div>
                        <div class="field-row">
                            <div class="preview-field">
                                <label>Location</label>
                                <input type="text" id="pvLocation" />
                            </div>
                            <div class="preview-field">
                                <label>Seniority</label>
                                <input type="text" id="pvSeniority" />
                            </div>
                        </div>
                        <div class="field-row">
                            <div class="preview-field">
                                <label>Plan</label>
                                <select id="pvPlan">
                                    <option value="">Select…</option>
                                    <option value="silver">Silver</option>
                                    <option value="golden">Golden</option>
                                    <option value="platinum">Platinum</option>
                                </select>
                            </div>
                            <div class="preview-field">
                                <label>Target Salary</label>
                                <input type="text" id="pvSalary" />
                            </div>
                        </div>
                        <div class="preview-field">
                            <label>Brief Description / Positioning</label>
                            <textarea id="pvDesc"></textarea>
                        </div>

                        <div class="section-divider">Career Strategy</div>
                        <div class="preview-field">
                            <label>Primary Target Roles</label>
                            <input type="text" id="pvRoles" placeholder="Comma-separated" />
                        </div>
                        <div class="preview-field">
                            <label>Target Sectors</label>
                            <input type="text" id="pvSectors" placeholder="Comma-separated" />
                        </div>
                        <div class="field-row">
                            <div class="preview-field">
                                <label>Priority Cities</label>
                                <input type="text" id="pvCities" placeholder="Comma-separated" />
                            </div>
                            <div class="preview-field">
                                <label>Languages</label>
                                <input type="text" id="pvLanguages" placeholder="e.g. English (Native), French (B2)" />
                            </div>
                        </div>
                        <div class="preview-field">
                            <label>Key Strengths</label>
                            <textarea id="pvStrengths" placeholder="One per line"></textarea>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" onclick="goBack()">Back</button>
                    <button class="btn btn-primary" id="btnConfirm" onclick="confirmCreate()">
                        <span class="material-icons" style="font-size:16px;">check_circle</span>
                        Create Profile
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script>
    // Configure PDF.js worker
    if (typeof pdfjsLib !== 'undefined') {
        pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.16.105/pdf.worker.min.js';
    }

    const BASE = '/admin';

    function filterMentees(filter, btn) {
        document.querySelectorAll('.filter-tab').forEach(t => t.classList.remove('active'));
        btn.classList.add('active');
        document.querySelectorAll('.mentee-card').forEach(card => {
            const plan   = card.dataset.plan;
            const status = card.dataset.status;
            let show = filter === 'all'
                || filter === status
                || filter === plan;
            card.style.display = show ? '' : 'none';
        });
    }

    let fileData = { cv: null, cvExt: null, linkedin: null, linkedinExt: null };
    let textData = { cvText: '', linkedinText: '' };
    let generatedProfile = null;

    function openModal() {
        document.getElementById('createModal').classList.add('active');
        resetModal();
    }

    function closeModal() {
        document.getElementById('createModal').classList.remove('active');
    }

    function resetModal() {
        ['step1','step2'].forEach(id => document.getElementById(id).style.display = id === 'step1' ? '' : 'none');
        document.getElementById('loadingSection').classList.remove('active');
        document.getElementById('errorBox').classList.remove('active');
        document.getElementById('autofillBadge').classList.remove('visible');
        document.getElementById('extractOverlay').classList.remove('active');
        ['inputName','inputEmail','inputPhone','inputDesc'].forEach(id => document.getElementById(id).value = '');
        document.getElementById('inputPlan').value = '';
        ['cvFileName','linkedinFileName'].forEach(id => document.getElementById(id).textContent = '');
        ['cvDropZone','linkedinDropZone'].forEach(id => document.getElementById(id).className = 'upload-area');
        document.getElementById('cvFile').value = '';
        document.getElementById('linkedinFile').value = '';
        document.getElementById('modalTitle').textContent = 'New Mentee';
        fileData = { cv: null, cvExt: null, linkedin: null, linkedinExt: null };
        textData = { cvText: '', linkedinText: '' };
        generatedProfile = null;
    }

    async function handleFile(type, input) {
        const file = input.files[0];
        if (!file) return;
        const ext = file.name.split('.').pop().toLowerCase();
        const nameEl = document.getElementById(type === 'cv' ? 'cvFileName' : 'linkedinFileName');
        const zoneEl = document.getElementById(type === 'cv' ? 'cvDropZone' : 'linkedinDropZone');

        nameEl.textContent = file.name;
        zoneEl.className = 'upload-area has-file';

        // Read as base64 — needed to save the actual file later
        const base64 = await readAsBase64(file);
        if (type === 'cv') { fileData.cv = base64; fileData.cvExt = ext; }
        else { fileData.linkedin = base64; fileData.linkedinExt = ext; }

        if (type === 'cv') {
            const overlay = document.getElementById('extractOverlay');
            overlay.classList.add('active');
            try {
                const text = await extractTextFromFile(file, ext);
                textData.cvText = text;
                if (text.trim()) {
                    const r = await fetch(BASE + '/api/admin/cv-extract', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ cvText: text })
                    });
                    const ct = r.headers.get('content-type') || '';
                    if (r.ok && ct.includes('application/json')) {
                        const data = await r.json();
                        const f = data.fields || {};
                        if (f.leadName)         document.getElementById('inputName').value  = f.leadName;
                        if (f.email)            document.getElementById('inputEmail').value = f.email;
                        if (f.phone)            document.getElementById('inputPhone').value = f.phone;
                        if (f.shortDescription) document.getElementById('inputDesc').value  = f.shortDescription;
                        document.getElementById('autofillBadge').classList.add('visible');
                    }
                }
            } catch (e) {
                console.error('CV extract error:', e);
            } finally {
                overlay.classList.remove('active');
            }
        } else {
            try {
                const text = await extractTextFromFile(file, ext);
                textData.linkedinText = text;
            } catch (e) {
                console.error('LinkedIn CV parse error:', e);
            }
        }
    }

    async function extractTextFromFile(file, ext) {
        const mime = file.type || '';
        if (ext === 'pdf' || mime === 'application/pdf') return extractTextFromPDF(file);
        if (ext === 'docx' || mime === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document') return extractTextFromDOCX(file);
        throw new Error('Unsupported file type. Please use PDF or DOCX.');
    }

    async function extractTextFromPDF(file) {
        const arrayBuffer = await file.arrayBuffer();
        const typedArray = new Uint8Array(arrayBuffer);
        const pdf = await pdfjsLib.getDocument({ data: typedArray }).promise;
        const pagePromises = [];
        for (let i = 1; i <= pdf.numPages; i++) {
            pagePromises.push(pdf.getPage(i).then(async page => {
                const content = await page.getTextContent();
                return content.items.map(item => item.str).join(' ');
            }));
        }
        const pages = await Promise.all(pagePromises);
        const text = pages.join('\n\n');
        if (!text.trim()) throw new Error('PDF contains no extractable text (possibly a scanned image)');
        return text;
    }

    async function extractTextFromDOCX(file) {
        const arrayBuffer = await file.arrayBuffer();
        const result = await mammoth.extractRawText({ arrayBuffer });
        if (!result.value || !result.value.trim()) throw new Error('No text content found in DOCX file');
        // Normalize whitespace like DocuRead
        return result.value.replace(/\r\n/g, '\n').replace(/\r/g, '\n').replace(/[ \t]+/g, ' ');
    }

    function readAsBase64(file) {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.onload = e => resolve(e.target.result.split(',')[1]);
            reader.onerror = reject;
            reader.readAsDataURL(file);
        });
    }

    function showError(msg) {
        const box = document.getElementById('errorBox');
        box.textContent = msg;
        box.classList.add('active');
        box.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
    }

    function hideError() { document.getElementById('errorBox').classList.remove('active'); }

    async function generateProfile() {
        hideError();
        const name  = document.getElementById('inputName').value.trim();
        const email = document.getElementById('inputEmail').value.trim();
        const phone = document.getElementById('inputPhone').value.trim();
        const plan  = document.getElementById('inputPlan').value;
        const desc  = document.getElementById('inputDesc').value.trim();

        if (!name)  return showError('Full name is required.');
        if (!email) return showError('Email is required.');
        if (!phone) return showError('Phone is required.');
        if (!plan)  return showError('Please select a plan.');
        if (!desc)  return showError('Brief description is required.');

        document.getElementById('step1').style.display = 'none';
        document.getElementById('loadingSection').classList.add('active');
        document.getElementById('loadingMsg').textContent = fileData.cv
            ? 'AI is analysing the CV and building the full profile…'
            : 'Creating profile…';

        try {
            const body = { name, email, phone, description: desc, plan };
            if (textData.cvText) body.cvText = textData.cvText;
            if (textData.linkedinText) body.linkedinText = textData.linkedinText;

            const r = await fetch(BASE + '/api/admin/profile-preview', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(body)
            });
            const data = await r.json();
            if (!r.ok) throw new Error(data.error || 'Server error');

            generatedProfile = data.profile;
            fillPreview(data.profile, data.aiGenerated, plan);
            document.getElementById('loadingSection').classList.remove('active');
            document.getElementById('step2').style.display = '';
            document.getElementById('modalTitle').textContent = 'Review Profile';
        } catch (e) {
            document.getElementById('loadingSection').classList.remove('active');
            document.getElementById('step1').style.display = '';
            showError('Error: ' + e.message);
        }
    }

    function fillPreview(p, aiGenerated, plan) {
        document.getElementById('pvName').value      = p.leadName || '';
        document.getElementById('pvEmail').value     = p.email || '';
        document.getElementById('pvPhone').value     = p.phone || '';
        document.getElementById('pvLinkedin').value  = p.linkedin || '';
        document.getElementById('pvLocation').value  = p.location || '';
        document.getElementById('pvSeniority').value = p.seniority || '';
        document.getElementById('pvSalary').value    = p.salaryTarget || '';
        document.getElementById('pvDesc').value      = p.shortDescription || '';
        document.getElementById('pvPlan').value      = p.plan || plan || '';
        document.getElementById('pvRoles').value     = (p.primaryRoles || []).join(', ');
        document.getElementById('pvSectors').value   = (p.targetSectors || []).join(', ');
        document.getElementById('pvCities').value    = (p.priorityCities || []).join(', ');
        document.getElementById('pvLanguages').value = (p.languages || []).map(l => `${l.language} (${l.level})`).join(', ');
        document.getElementById('pvStrengths').value = ((p.gapAnalysis && p.gapAnalysis.strengths) || []).join('\n');

        const badge = document.getElementById('aiBadge');
        badge.classList.toggle('visible', !!aiGenerated);
    }

    function collectPreview() {
        const toArray = s => s.split(',').map(x => x.trim()).filter(Boolean);
        const toLines = s => s.split('\n').map(x => x.trim()).filter(Boolean);
        return {
            ...generatedProfile,
            leadName:         document.getElementById('pvName').value.trim(),
            email:            document.getElementById('pvEmail').value.trim(),
            phone:            document.getElementById('pvPhone').value.trim(),
            linkedin:         document.getElementById('pvLinkedin').value.trim(),
            location:         document.getElementById('pvLocation').value.trim(),
            seniority:        document.getElementById('pvSeniority').value.trim(),
            salaryTarget:     document.getElementById('pvSalary').value.trim(),
            shortDescription: document.getElementById('pvDesc').value.trim(),
            plan:             document.getElementById('pvPlan').value,
            primaryRoles:     toArray(document.getElementById('pvRoles').value),
            targetSectors:    toArray(document.getElementById('pvSectors').value),
            priorityCities:   toArray(document.getElementById('pvCities').value),
            gapAnalysis: {
                ...(generatedProfile && generatedProfile.gapAnalysis || {}),
                strengths: toLines(document.getElementById('pvStrengths').value)
            }
        };
    }

    function goBack() {
        document.getElementById('step2').style.display = 'none';
        document.getElementById('step1').style.display = '';
        document.getElementById('modalTitle').textContent = 'New Mentee';
    }

    async function confirmCreate() {
        const profile = collectPreview();
        if (!profile.leadName) return alert('Full name is required.');
        if (!profile.email)    return alert('Email is required.');

        const btn = document.getElementById('btnConfirm');
        btn.disabled = true;
        btn.innerHTML = '<span class="material-icons" style="font-size:16px;">hourglass_empty</span> Creating…';

        const cvFiles = [];
        if (fileData.cv)      cvFiles.push({ data: fileData.cv,      ext: fileData.cvExt,      type: 'cv' });
        if (fileData.linkedin) cvFiles.push({ data: fileData.linkedin, ext: fileData.linkedinExt, type: 'linkedin' });

        try {
            const r = await fetch(BASE + '/api/admin/mentee/create', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ profile, cvFiles, cvText: textData.cvText || '' })
            });
            const data = await r.json();
            if (!r.ok) throw new Error(data.error || 'Failed to create profile');
            closeModal();
            window.location.href = BASE + '/profile/' + data.slug;
        } catch (e) {
            btn.disabled = false;
            btn.innerHTML = '<span class="material-icons" style="font-size:16px;">check_circle</span> Create Profile';
            alert('Error: ' + e.message);
        }
    }

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