import {
  initDb,
  getJobs,
  getJobBySlug,
  getJobById,
  createJob,
  updateJob,
  deleteJob,
  reorderJobs,
  getQuestions,
  getQuestionById,
  createQuestion,
  updateQuestion,
  deleteQuestion,
  reorderQuestions,
  getApplications,
  getApplicationById,
  getApplicationCountByJob,
  createApplication,
  updateApplicationStatus,
  updateApplicationNotes,
  getDashboardStats,
  getSetting,
  db,
} from "./db.ts";
import type { Job, Application } from "./db.ts";

await initDb();

const sessionStore = new Map<string, { expiresAt: number }>();

function createSession(): string {
  const id = crypto.randomUUID();
  sessionStore.set(id, { expiresAt: Date.now() + 86400000 });
  return id;
}

function validateSession(id: string): boolean {
  const s = sessionStore.get(id);
  if (!s) { console.log("[session] validateSession: NOT FOUND for", id, "store keys:", Array.from(sessionStore.keys())); return false; }
  if (Date.now() > s.expiresAt) { console.log("[session] validateSession: EXPIRED for", id); sessionStore.delete(id); return false; }
  console.log("[session] validateSession: VALID for", id);
  return true;
}

function deleteSession(id: string): void {
  sessionStore.delete(id);
}

const PUBLIC_URL = Deno.env.get("OPENPIECES_SERVICE_PUBLIC_URL") || "https://e226c94f-6308-4663-822d-a4f041cb4a75.amen.matikiti.com";

const CSS = `
*{margin:0;padding:0;box-sizing:border-box}
body{font-family:'Inter',system-ui,-apple-system,sans-serif;background:#050505;background-image:radial-gradient(ellipse 80% 50% at 50% 0%,rgba(201,168,76,0.04) 0%,transparent 60%),radial-gradient(ellipse 50% 40% at 50% 100%,rgba(201,168,76,0.02) 0%,transparent 50%);color:#F5F5F5;min-height:100vh;line-height:1.6;-webkit-backface-visibility:hidden;backface-visibility:hidden}
a{color:#C9A84C;text-decoration:none}
a:hover{color:#BD9838}
.container{max-width:1200px;margin:0 auto;padding:0 20px}
.btn{display:inline-block;padding:12px 32px;border-radius:6px;font-weight:600;font-size:15px;cursor:pointer;border:none;transition:all .3s ease}
.btn-gold{background:linear-gradient(135deg,#C9A84C,#A68A2A);color:#0A0A0A;box-shadow:0 0 25px rgba(201,168,76,.25);transition:all .3s ease}
.btn-gold:hover{box-shadow:0 0 40px rgba(201,168,76,.5);transform:translateY(-1px)}
.btn-outline{background:transparent;border:1px solid #C9A84C;color:#C9A84C;transition:all .3s ease}
.btn-outline:hover{background:rgba(201,168,76,.1);box-shadow:0 0 15px rgba(201,168,76,.2)}
.btn-sm{padding:8px 16px;font-size:13px}
.badge{display:inline-block;padding:4px 12px;border-radius:4px;font-size:12px;font-weight:600}
.badge-gold{background:#C9A84C;color:#0A0A0A}
.badge-dept{background:rgba(201,168,76,.15);color:#C9A84C;border:1px solid rgba(201,168,76,.3)}
.badge-loc{background:rgba(255,255,255,.08);color:#aaa}
.badge-type{background:rgba(255,255,255,.08);color:#aaa}
.card{background:#111;border:1px solid rgba(201,168,76,0.08);border-radius:12px;padding:24px;transition:all .3s ease;box-shadow:0 0 30px rgba(201,168,76,0.02)}
.gold-glow:focus,.gold-glow:focus-within{border-color:#C9A84C;box-shadow:0 0 15px rgba(201,168,76,.3);outline:none}
input,select,textarea{-webkit-appearance:none;appearance:none;background:#1A1A1A;border:1px solid #2A2A2A;border-radius:6px;color:#F5F5F5;padding:14px 16px;font-size:15px;width:100%;font-family:inherit;transition:all .3s ease}
input:focus,select:focus,textarea:focus{border-color:#C9A84C;box-shadow:0 0 15px rgba(201,168,76,.3);outline:none}
label{font-size:14px;font-weight:500;color:#aaa;margin-bottom:6px;display:block}
.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(320px,1fr));gap:20px}
.section-title{font-size:28px;font-weight:700;margin-bottom:8px;color:#F5F5F5}
.section-subtitle{font-size:16px;color:#888;margin-bottom:32px}
.status-new{background:#2563eb20;color:#60a5fa;border:1px solid #2563eb40}
.status-reviewed{background:#d9770620;color:#fbbf24;border:1px solid #d9770640}
.status-shortlisted{background:#7c3aed20;color:#a78bfa;border:1px solid #7c3aed40}
.status-rejected{background:#dc262620;color:#f87171;border:1px solid #dc262640}
.status-hired{background:#16a34a20;color:#4ade80;border:1px solid #16a34a40}
table{width:100%;border-collapse:collapse}
th{text-align:left;padding:12px 16px;font-size:13px;font-weight:600;color:#888;border-bottom:1px solid #2A2A2A;text-transform:uppercase;letter-spacing:.5px}
td{padding:12px 16px;border-bottom:1px solid #1A1A1A;font-size:14px}
tr:nth-child(even){background:rgba(255,255,255,.02)}
tr:hover{background:rgba(201,168,76,.05)}
.admin-nav{background:#111;border-bottom:1px solid #2A2A2A;padding:0 20px}
.admin-nav-inner{display:flex;align-items:center;gap:24px;max-width:1400px;margin:0 auto;height:56px}
.admin-nav a{color:#888;font-size:14px;font-weight:500;padding:16px 0;border-bottom:2px solid transparent;transition:all .3s ease}
.admin-nav a:hover,.admin-nav a.active{color:#C9A84C;border-bottom-color:#C9A84C}
.admin-layout{display:flex;min-height:calc(100vh - 56px)}
.admin-sidebar{width:240px;background:#111;border-right:1px solid #2A2A2A;padding:20px 0;flex-shrink:0}
.admin-sidebar a{display:block;padding:10px 24px;color:#888;font-size:14px;transition:all .2s ease}
.admin-sidebar a:hover,.admin-sidebar a.active{color:#C9A84C;background:rgba(201,168,76,.05)}
.admin-main{flex:1;padding:32px;overflow-x:auto}
.stats-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:20px;margin-bottom:32px}
.stat-card{background:#111;border:1px solid rgba(201,168,76,0.08);border-radius:12px;padding:24px;transition:all .3s ease;box-shadow:0 0 30px rgba(201,168,76,0.02)}
.stat-card:hover{box-shadow:0 0 40px rgba(201,168,76,.1);transform:translateY(-1px)}
.stat-card .value{font-size:36px;font-weight:700;color:#C9A84C;margin-bottom:4px}
.stat-card .label{font-size:14px;color:#888}
.modal-overlay{position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,.8);z-index:1000;display:none;justify-content:center;align-items:center}
.modal-content{background:#1A1A1A;border:1px solid #2A2A2A;border-radius:12px;padding:32px;max-width:600px;width:90%;max-height:80vh;overflow-y:auto;animation:fadeIn .3s ease}
.modal-content h2{color:#C9A84C;margin-bottom:20px}
.form-group{margin-bottom:16px}
.form-group label{display:block;margin-bottom:4px}
.form-actions{display:flex;gap:12px;justify-content:flex-end;margin-top:24px}
.toast{position:fixed;top:20px;right:20px;padding:12px 24px;border-radius:6px;font-size:14px;z-index:2000;display:none;animation:fadeIn .3s ease}
.toast-success{background:#16a34a;color:#fff}
.toast-error{background:#dc2626;color:#fff}
@keyframes fadeIn{from{opacity:0;transform:translateY(-10px)}to{opacity:1;transform:translateY(0)}}
.hero{padding:80px 0;text-align:center}
.hero h1{font-size:52px;font-weight:800;margin-bottom:16px;letter-spacing:-1px}
.hero h1 span{color:#C9A84C}
.hero p{font-size:20px;color:#888;max-width:600px;margin:0 auto 40px}
.job-card{cursor:pointer;transition:all .3s ease}
.job-card:hover{border-color:#C9A84C;box-shadow:0 0 25px rgba(201,168,76,.3),0 0 60px rgba(201,168,76,.1);transform:translateY(-2px)}
.job-card h3{font-size:18px;font-weight:600;margin-bottom:12px}
.job-card .meta{display:flex;gap:8px;flex-wrap:wrap;margin-bottom:16px}
.job-card .desc{color:#888;font-size:14px;line-height:1.6;margin-bottom:16px}
.job-card .btn{width:100%;text-align:center}
.job-detail{padding:40px 0;max-width:800px;margin:0 auto}
.job-detail h1{font-size:36px;font-weight:700;margin-bottom:16px}
.job-detail .meta{display:flex;gap:10px;flex-wrap:wrap;margin-bottom:32px}
.job-detail section{margin-bottom:32px}
.job-detail h2{font-size:22px;font-weight:600;color:#C9A84C;margin-bottom:16px}
.job-detail ul{padding-left:20px}
.job-detail li{margin-bottom:8px;color:#ccc;font-size:15px;line-height:1.6}
.job-detail .salary{background:rgba(201,168,76,.1);border:1px solid rgba(201,168,76,.3);border-radius:8px;padding:16px 20px;margin-bottom:32px;display:inline-block}
.job-detail .salary span{color:#C9A84C;font-weight:600;font-size:18px}
.job-detail .cta{text-align:center;padding:40px 0}
.job-detail .cta .btn{font-size:18px;padding:16px 48px}
.typeform-screen{position:fixed;top:0;left:0;right:0;bottom:0;background:#050505;background-image:radial-gradient(ellipse 80% 50% at 50% 0%,rgba(201,168,76,0.04) 0%,transparent 60%),radial-gradient(ellipse 50% 40% at 50% 100%,rgba(201,168,76,0.02) 0%,transparent 50%);z-index:100;display:flex;flex-direction:column;overflow:hidden}
.typeform-progress{height:4px;background:#2A2A2A;position:relative}
.typeform-progress-fill{height:100%;background:linear-gradient(90deg,#C9A84C,#BD9838);transition:width .4s ease;border-radius:0 2px 2px 0}
.typeform-header{padding:16px 32px;display:flex;align-items:center;justify-content:space-between}
.typeform-counter{font-size:14px;color:#888}
.typeform-body{flex:1;display:flex;align-items:center;justify-content:center;padding:40px 32px;overflow:hidden}
.typeform-step{width:100%;max-width:640px;transition:all .35s cubic-bezier(.4,0,.2,1);position:absolute;opacity:0;transform:translateX(60px);pointer-events:none}
.typeform-step.active{opacity:1;transform:translateX(0);position:relative;pointer-events:auto}
.typeform-step.exiting{opacity:0;transform:translateX(-60px)}
.typeform-label{font-size:13px;color:#C9A84C;text-transform:uppercase;letter-spacing:1px;margin-bottom:8px;font-weight:600}
.typeform-question{font-size:28px;font-weight:700;margin-bottom:32px;line-height:1.3}
.typeform-input{background:#1A1A1A;border:1px solid #333;border-radius:8px;color:#F5F5F5;padding:16px 20px;font-size:17px;width:100%;transition:all .3s ease}
.typeform-input:focus{border-color:#C9A84C;box-shadow:0 0 20px rgba(201,168,76,.25);outline:none}
.typeform-textarea{min-height:140px;resize:vertical}
.typeform-select{-webkit-appearance:none;appearance:none;background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='8' fill='%23888'%3E%3Cpath d='M1 1l5 5 5-5'/%3E%3C/svg%3E");background-repeat:no-repeat;background-position:right 16px center;padding-right:44px}
.typeform-btn{padding:16px 40px;font-size:16px;font-weight:600;border-radius:8px;border:none;cursor:pointer;transition:all .3s ease;display:inline-flex;align-items:center;gap:8px}
.typeform-btn-primary{background:linear-gradient(135deg,#C9A84C,#A68A2A);color:#0A0A0A;box-shadow:0 0 25px rgba(201,168,76,.25)}
.typeform-btn-primary:hover{box-shadow:0 0 40px rgba(201,168,76,.5);transform:translateY(-1px)}
.typeform-btn-primary:disabled{opacity:.5;cursor:not-allowed;transform:none}
.typeform-buttons{display:flex;justify-content:flex-end;margin-top:32px}
.typeform-error{color:#f87171;font-size:13px;margin-top:8px;display:none}
.typeform-confirm{text-align:center;padding:60px 0}
.typeform-confirm h2{font-size:32px;color:#C9A84C;margin-bottom:16px}
.typeform-confirm p{font-size:18px;color:#888;margin-bottom:8px}
.auth-card{max-width:400px;margin:120px auto;background:#111;border:1px solid rgba(201,168,76,0.08);border-radius:16px;padding:40px;text-align:center;box-shadow:0 0 30px rgba(201,168,76,0.02)}
.auth-card h1{font-size:28px;margin-bottom:8px}
.auth-card .sub{color:#888;margin-bottom:32px}
.auth-card .form-group{text-align:left}
.auth-card .btn{width:100%;margin-top:8px}
.auth-error{background:#dc262620;border:1px solid #dc262640;color:#f87171;padding:12px;border-radius:6px;margin-bottom:20px;display:none}
.question-card{background:#111;border:1px solid rgba(201,168,76,0.08);border-radius:12px;padding:20px;margin-bottom:12px;transition:all .3s ease;box-shadow:0 0 30px rgba(201,168,76,0.02)}
.question-card:hover{border-color:rgba(201,168,76,.2)}
.question-card .header{display:flex;justify-content:space-between;align-items:start;margin-bottom:8px}
.question-card .text{font-size:15px;font-weight:500;margin-bottom:4px}
.question-card .meta{display:flex;gap:6px;flex-wrap:wrap;margin-top:8px}
.question-card .actions{display:flex;gap:6px;margin-top:12px}
.section-group{margin-bottom:32px}
.section-group h3{color:#C9A84C;font-size:18px;font-weight:600;margin-bottom:12px;padding-bottom:8px;border-bottom:1px solid #2A2A2A}
.app-detail{max-width:800px}
.app-detail .header{margin-bottom:32px}
.app-detail .header h1{font-size:28px;margin-bottom:8px}
.app-detail .info{display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:16px;margin-bottom:32px}
.app-detail .info-item{background:#111;border:1px solid rgba(201,168,76,0.08);border-radius:8px;padding:16px;transition:all .3s ease;box-shadow:0 0 30px rgba(201,168,76,0.02)}
.app-detail .info-item:hover{border-color:rgba(201,168,76,.15)}
.app-detail .info-item .l{font-size:12px;color:#888;text-transform:uppercase;letter-spacing:.5px;margin-bottom:4px}
.app-detail .info-item .v{font-size:16px;font-weight:500}
.app-detail .qa-section{margin-bottom:24px}
.app-detail .qa-section h3{color:#C9A84C;font-size:16px;font-weight:600;margin-bottom:16px;padding-bottom:8px;border-bottom:1px solid #2A2A2A}
.app-detail .qa-item{margin-bottom:16px}
.app-detail .qa-item .q{font-size:13px;color:#888;margin-bottom:4px}
.app-detail .qa-item .a{font-size:15px;line-height:1.5;padding:12px 16px;background:#1A1A1A;border-radius:6px;border:1px solid #2A2A2A}
.app-detail .admin-tools{background:#111;border:1px solid rgba(201,168,76,0.08);border-radius:12px;padding:24px;margin-top:32px;transition:all .3s ease;box-shadow:0 0 30px rgba(201,168,76,0.02)}
.app-detail .admin-tools h3{color:#C9A84C;margin-bottom:16px}
.app-detail .admin-tools .form-group{margin-bottom:16px}
.filter-bar{display:flex;gap:12px;align-items:center;flex-wrap:wrap;margin-bottom:24px}
.filter-bar select,.filter-bar .search-input{max-width:240px}
.filter-tabs{display:flex;gap:4px;margin-bottom:20px;flex-wrap:wrap}
.filter-tab{padding:8px 16px;border-radius:6px;font-size:13px;font-weight:500;cursor:pointer;border:1px solid #2A2A2A;background:transparent;color:#888;transition:all .2s ease}
.filter-tab:hover,.filter-tab.active{border-color:#C9A84C;color:#C9A84C}
.filter-tab.active{background:rgba(201,168,76,.1)}
@media(max-width:768px){
  .hero h1{font-size:32px}
  .grid{grid-template-columns:1fr}
  .admin-sidebar{display:none}
  .admin-main{padding:16px}
  .typeform-header{padding:12px 16px}
  .typeform-body{padding:24px 16px}
  .typeform-question{font-size:22px}
}
`;

const ADMIN_CSS = `
*{margin:0;padding:0;box-sizing:border-box}
body{font-family:system-ui,-apple-system,sans-serif;background:#050505;color:#F5F5F5;min-height:100vh;line-height:1.6;-webkit-backface-visibility:hidden;backface-visibility:hidden}
a{color:#C9A84C;text-decoration:none}
a:hover{color:#BD9838}
.container{max-width:1200px;margin:0 auto;padding:0 20px}
.btn{display:inline-block;padding:12px 32px;border-radius:6px;font-weight:600;font-size:15px;cursor:pointer;border:none}
.btn-gold{background:linear-gradient(135deg,#C9A84C,#A68A2A);color:#0A0A0A}
.btn-gold:hover{}
.btn-outline{background:transparent;border:1px solid #C9A84C;color:#C9A84C}
.btn-outline:hover{background:rgba(201,168,76,.1)}
.btn-sm{padding:8px 16px;font-size:13px}
.badge{display:inline-block;padding:4px 12px;border-radius:4px;font-size:12px;font-weight:600}
.badge-gold{background:#C9A84C;color:#0A0A0A}
.badge-dept{background:rgba(201,168,76,.15);color:#C9A84C;border:1px solid rgba(201,168,76,.3)}
.badge-loc{background:rgba(255,255,255,.08);color:#aaa}
.badge-type{background:rgba(255,255,255,.08);color:#aaa}
.card{background:#111;border:1px solid rgba(201,168,76,0.08);border-radius:12px;padding:24px}
.gold-glow:focus,.gold-glow:focus-within{border-color:#C9A84C;outline:none}
input,select,textarea{-webkit-appearance:none;appearance:none;background:#1A1A1A;border:1px solid #2A2A2A;border-radius:6px;color:#F5F5F5;padding:14px 16px;font-size:15px;width:100%;font-family:inherit}
input:focus,select:focus,textarea:focus{border-color:#C9A84C;outline:none}
label{font-size:14px;font-weight:500;color:#aaa;margin-bottom:6px;display:block}
.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(320px,1fr));gap:20px}
.section-title{font-size:28px;font-weight:700;margin-bottom:8px;color:#F5F5F5}
.section-subtitle{font-size:16px;color:#888;margin-bottom:32px}
.status-new{background:#2563eb20;color:#60a5fa;border:1px solid #2563eb40}
.status-reviewed{background:#d9770620;color:#fbbf24;border:1px solid #d9770640}
.status-shortlisted{background:#7c3aed20;color:#a78bfa;border:1px solid #7c3aed40}
.status-rejected{background:#dc262620;color:#f87171;border:1px solid #dc262640}
.status-hired{background:#16a34a20;color:#4ade80;border:1px solid #16a34a40}
table{width:100%;border-collapse:collapse}
th{text-align:left;padding:12px 16px;font-size:13px;font-weight:600;color:#888;border-bottom:1px solid #2A2A2A;text-transform:uppercase;letter-spacing:.5px}
td{padding:12px 16px;border-bottom:1px solid #1A1A1A;font-size:14px}
tr:nth-child(even){background:rgba(255,255,255,.02)}
tr:hover{background:rgba(201,168,76,.05)}
.admin-nav{background:#111;border-bottom:1px solid #2A2A2A;padding:0 20px}
.admin-nav-inner{display:flex;align-items:center;gap:24px;max-width:1400px;margin:0 auto;height:56px}
.admin-nav a{color:#888;font-size:14px;font-weight:500;padding:16px 0;border-bottom:2px solid transparent}
.admin-nav a:hover,.admin-nav a.active{color:#C9A84C;border-bottom-color:#C9A84C}
.admin-layout{display:flex;min-height:calc(100vh - 56px)}
.admin-sidebar{width:240px;background:#111;border-right:1px solid #2A2A2A;padding:20px 0;flex-shrink:0}
.admin-sidebar a{display:block;padding:10px 24px;color:#888;font-size:14px}
.admin-sidebar a:hover,.admin-sidebar a.active{color:#C9A84C;background:rgba(201,168,76,.05)}
.admin-main{flex:1;padding:32px;overflow-x:auto}
.stats-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:20px;margin-bottom:32px}
.stat-card{background:#111;border:1px solid rgba(201,168,76,0.08);border-radius:12px;padding:24px}
.stat-card:hover{}
.stat-card .value{font-size:36px;font-weight:700;color:#C9A84C;margin-bottom:4px}
.stat-card .label{font-size:14px;color:#888}
.modal-overlay{position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,.8);z-index:1000;display:none;justify-content:center;align-items:center}
.modal-content{background:#1A1A1A;border:1px solid #2A2A2A;border-radius:12px;padding:32px;max-width:600px;width:90%;max-height:80vh;overflow-y:auto}
.modal-content h2{color:#C9A84C;margin-bottom:20px}
.form-group{margin-bottom:16px}
.form-group label{display:block;margin-bottom:4px}
.form-actions{display:flex;gap:12px;justify-content:flex-end;margin-top:24px}
.toast{position:fixed;top:20px;right:20px;padding:12px 24px;border-radius:6px;font-size:14px;z-index:2000;display:none}
.toast-success{background:#16a34a;color:#fff}
.toast-error{background:#dc2626;color:#fff}
.hero{padding:80px 0;text-align:center}
.hero h1{font-size:52px;font-weight:800;margin-bottom:16px;letter-spacing:-1px}
.hero h1 span{color:#C9A84C}
.hero p{font-size:20px;color:#888;max-width:600px;margin:0 auto 40px}
.job-card{cursor:pointer}
.job-card:hover{border-color:#C9A84C}
.job-card h3{font-size:18px;font-weight:600;margin-bottom:12px}
.job-card .meta{display:flex;gap:8px;flex-wrap:wrap;margin-bottom:16px}
.job-card .desc{color:#888;font-size:14px;line-height:1.6;margin-bottom:16px}
.job-card .btn{width:100%;text-align:center}
.job-detail{padding:40px 0;max-width:800px;margin:0 auto}
.job-detail h1{font-size:36px;font-weight:700;margin-bottom:16px}
.job-detail .meta{display:flex;gap:10px;flex-wrap:wrap;margin-bottom:32px}
.job-detail section{margin-bottom:32px}
.job-detail h2{font-size:22px;font-weight:600;color:#C9A84C;margin-bottom:16px}
.job-detail ul{padding-left:20px}
.job-detail li{margin-bottom:8px;color:#ccc;font-size:15px;line-height:1.6}
.job-detail .salary{background:rgba(201,168,76,.1);border:1px solid rgba(201,168,76,.3);border-radius:8px;padding:16px 20px;margin-bottom:32px;display:inline-block}
.job-detail .salary span{color:#C9A84C;font-weight:600;font-size:18px}
.job-detail .cta{text-align:center;padding:40px 0}
.job-detail .cta .btn{font-size:18px;padding:16px 48px}
.typeform-screen{position:fixed;top:0;left:0;right:0;bottom:0;background:#050505;z-index:100;display:flex;flex-direction:column;overflow:hidden}
.typeform-progress{height:4px;background:#2A2A2A;position:relative}
.typeform-progress-fill{height:100%;background:linear-gradient(90deg,#C9A84C,#BD9838);border-radius:0 2px 2px 0}
.typeform-header{padding:16px 32px;display:flex;align-items:center;justify-content:space-between}
.typeform-counter{font-size:14px;color:#888}
.typeform-body{flex:1;display:flex;align-items:center;justify-content:center;padding:40px 32px;overflow:hidden}
.typeform-step{width:100%;max-width:640px;position:absolute;opacity:0;pointer-events:none}
.typeform-step.active{opacity:1;position:relative;pointer-events:auto}
.typeform-step.exiting{opacity:0}
.typeform-label{font-size:13px;color:#C9A84C;text-transform:uppercase;letter-spacing:1px;margin-bottom:8px;font-weight:600}
.typeform-question{font-size:28px;font-weight:700;margin-bottom:32px;line-height:1.3}
.typeform-input{background:#1A1A1A;border:1px solid #333;border-radius:8px;color:#F5F5F5;padding:16px 20px;font-size:17px;width:100%}
.typeform-input:focus{border-color:#C9A84C;outline:none}
.typeform-textarea{min-height:140px;resize:vertical}
.typeform-select{-webkit-appearance:none;appearance:none;background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='8' fill='%23888'%3E%3Cpath d='M1 1l5 5 5-5'/%3E%3C/svg%3E");background-repeat:no-repeat;background-position:right 16px center;padding-right:44px}
.typeform-btn{padding:16px 40px;font-size:16px;font-weight:600;border-radius:8px;border:none;cursor:pointer;display:inline-flex;align-items:center;gap:8px}
.typeform-btn-primary{background:linear-gradient(135deg,#C9A84C,#A68A2A);color:#0A0A0A}
.typeform-btn-primary:hover{}
.typeform-btn-primary:disabled{opacity:.5;cursor:not-allowed}
.typeform-buttons{display:flex;justify-content:flex-end;margin-top:32px}
.typeform-error{color:#f87171;font-size:13px;margin-top:8px;display:none}
.typeform-confirm{text-align:center;padding:60px 0}
.typeform-confirm h2{font-size:32px;color:#C9A84C;margin-bottom:16px}
.typeform-confirm p{font-size:18px;color:#888;margin-bottom:8px}
.auth-card{max-width:400px;margin:120px auto;background:#111;border:1px solid rgba(201,168,76,0.08);border-radius:16px;padding:40px;text-align:center}
.auth-card h1{font-size:28px;margin-bottom:8px}
.auth-card .sub{color:#888;margin-bottom:32px}
.auth-card .form-group{text-align:left}
.auth-card .btn{width:100%;margin-top:8px}
.auth-error{background:#dc262620;border:1px solid #dc262640;color:#f87171;padding:12px;border-radius:6px;margin-bottom:20px;display:none}
.question-card{background:#111;border:1px solid rgba(201,168,76,0.08);border-radius:12px;padding:20px;margin-bottom:12px}
.question-card:hover{border-color:rgba(201,168,76,.2)}
.question-card .header{display:flex;justify-content:space-between;align-items:start;margin-bottom:8px}
.question-card .text{font-size:15px;font-weight:500;margin-bottom:4px}
.question-card .meta{display:flex;gap:6px;flex-wrap:wrap;margin-top:8px}
.question-card .actions{display:flex;gap:6px;margin-top:12px}
.section-group{margin-bottom:32px}
.section-group h3{color:#C9A84C;font-size:18px;font-weight:600;margin-bottom:12px;padding-bottom:8px;border-bottom:1px solid #2A2A2A}
.app-detail{max-width:800px}
.app-detail .header{margin-bottom:32px}
.app-detail .header h1{font-size:28px;margin-bottom:8px}
.app-detail .info{display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:16px;margin-bottom:32px}
.app-detail .info-item{background:#111;border:1px solid rgba(201,168,76,0.08);border-radius:8px;padding:16px}
.app-detail .info-item:hover{border-color:rgba(201,168,76,.15)}
.app-detail .info-item .l{font-size:12px;color:#888;text-transform:uppercase;letter-spacing:.5px;margin-bottom:4px}
.app-detail .info-item .v{font-size:16px;font-weight:500}
.app-detail .qa-section{margin-bottom:24px}
.app-detail .qa-section h3{color:#C9A84C;font-size:16px;font-weight:600;margin-bottom:16px;padding-bottom:8px;border-bottom:1px solid #2A2A2A}
.app-detail .qa-item{margin-bottom:16px}
.app-detail .qa-item .q{font-size:13px;color:#888;margin-bottom:4px}
.app-detail .qa-item .a{font-size:15px;line-height:1.5;padding:12px 16px;background:#1A1A1A;border-radius:6px;border:1px solid #2A2A2A}
.app-detail .admin-tools{background:#111;border:1px solid rgba(201,168,76,0.08);border-radius:12px;padding:24px;margin-top:32px}
.app-detail .admin-tools h3{color:#C9A84C;margin-bottom:16px}
.app-detail .admin-tools .form-group{margin-bottom:16px}
.filter-bar{display:flex;gap:12px;align-items:center;flex-wrap:wrap;margin-bottom:24px}
.filter-bar select,.filter-bar .search-input{max-width:240px}
.filter-tabs{display:flex;gap:4px;margin-bottom:20px;flex-wrap:wrap}
.filter-tab{padding:8px 16px;border-radius:6px;font-size:13px;font-weight:500;cursor:pointer;border:1px solid #2A2A2A;background:transparent;color:#888}
.filter-tab:hover,.filter-tab.active{border-color:#C9A84C;color:#C9A84C}
.filter-tab.active{background:rgba(201,168,76,.1)}
@media(max-width:768px){
  .hero h1{font-size:32px}
  .grid{grid-template-columns:1fr}
  .admin-sidebar{display:none}
  .admin-main{padding:16px}
  .typeform-header{padding:12px 16px}
  .typeform-body{padding:24px 16px}
  .typeform-question{font-size:22px}
}
`;

async function sha256(input: string): Promise<string> {
  const hash = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(input));
  return Array.from(new Uint8Array(hash)).map(b => b.toString(16).padStart(2, "0")).join("");
}

function getCookie(req: Request, name: string): string | null {
  const cookie = req.headers.get("Cookie");
  if (!cookie) return null;
  for (const part of cookie.split(";")) {
    const [k, v] = part.trim().split("=");
    if (k === name) return v;
  }
  return null;
}

function json(data: unknown, status = 200): Response {
  return new Response(JSON.stringify(data), {
    status,
    headers: { "content-type": "application/json" },
  });
}

function html(content: string): Response {
  return new Response(content, {
    status: 200,
    headers: {
      "Content-Type": "text/html; charset=utf-8",
      "Cache-Control": "no-cache, no-store, must-revalidate",
      "Pragma": "no-cache",
      "Expires": "0",
    },
  });
}

function redirect(url: string, status = 302): Response {
  return new Response(null, { status, headers: { "Location": url } });
}

function layout(title: string, body: string, extraHead = ""): string {
  return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>${title}</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<style>${CSS}</style>
${extraHead}
</head>
<body>${body}</body>
</html>`;
}

function adminLayout(title: string, body: string, extraHead = "", token = ""): string {
  const t = token ? `?token=${token}` : "";
  return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>${title}</title>
<style>${ADMIN_CSS}</style>
${extraHead}
</head>
<body>
<nav class="admin-nav">
  <div class="admin-nav-inner">
    <a href="/admin/dashboard${t}" style="font-weight:700;color:#C9A84C;font-size:16px">MarqueLead</a>
    <a href="/admin/dashboard${t}" class="active">Dashboard</a>
    <a href="/admin/jobs${t}">Jobs</a>
    <a href="/admin/questions${t}">Questions</a>
    <a href="/admin/applications${t}">Applications</a>
    <a href="/admin/logout${t}" style="margin-left:auto;color:#f87171">Logout</a>
  </div>
</nav>
<div class="admin-layout">
  <div class="admin-sidebar">
    <a href="/admin/dashboard${t}">Dashboard</a>
    <a href="/admin/jobs${t}">Jobs</a>
    <a href="/admin/questions${t}">Questions</a>
    <a href="/admin/applications${t}">Applications</a>
    <a href="/admin/logout${t}" style="color:#f87171">Logout</a>
  </div>
  <div class="admin-main">${body}</div>
</div>
</body>
</html>`;
}

function getSessionId(req: Request): string | null {
  const url = new URL(req.url);
  return url.searchParams.get("token") || getCookie(req, "ml_session") || null;
}

async function adminGuard(req: Request): Promise<Response | null> {
  const url = new URL(req.url);
  const token = url.searchParams.get("token");
  if (token && validateSession(token)) return null;
  const cookie = getCookie(req, "ml_session");
  if (cookie && validateSession(cookie)) return null;
  const isApi = !req.method?.startsWith("GET") || url.pathname.startsWith("/admin/api/");
  if (isApi) return json({ error: "Unauthorized" }, 401);
  return html(`<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1.0"><title>Admin Login — MarqueLead Careers</title><style>*{margin:0;padding:0;box-sizing:border-box}body{font-family:system-ui,sans-serif;background:#050505;color:#F5F5F5;min-height:100vh;line-height:1.6;display:flex;align-items:center;justify-content:center}.card{max-width:400px;width:90%;background:#111;border:1px solid rgba(201,168,76,0.08);border-radius:16px;padding:40px;text-align:center}.card h1{font-size:28px;margin-bottom:8px}.card .sub{color:#888;margin-bottom:32px}.fg{margin-bottom:16px;text-align:left}.fg label{font-size:14px;font-weight:500;color:#aaa;margin-bottom:6px;display:block}input{background:#1A1A1A;border:1px solid #2A2A2A;border-radius:6px;color:#F5F5F5;padding:14px 16px;font-size:15px;width:100%;font-family:inherit;box-sizing:border-box}input:focus{border-color:#C9A84C;outline:none}.btn{display:block;padding:12px;border-radius:6px;font-weight:600;font-size:15px;cursor:pointer;border:none;width:100%;background:linear-gradient(135deg,#C9A84C,#A68A2A);color:#0A0A0A}</style></head><body><div class="card"><h1>MarqueLead <span style="color:#C9A84C">Admin</span></h1><p class="sub">Sign in to manage careers & applications</p><form action="/admin/login" method="POST"><div class="fg"><label>Password</label><input type="password" name="password" placeholder="Enter admin password..." autofocus/></div><button type="submit" class="btn">Sign In</button></form></div></body></html>`);
}

function renderCareersPage(): string {
  const jobs = getJobs(true);
  const jobCards = jobs.map(j => {
    const desc = j.description.length > 150 ? j.description.substring(0, 150) + "..." : j.description;
    return `<a href="/jobs/${j.slug}" class="card job-card" style="display:block;text-decoration:none;color:inherit">
      <div style="margin-bottom:12px"><span class="badge badge-dept">${escHtml(j.department)}</span></div>
      <h3>${escHtml(j.title)}</h3>
      <div class="meta">
        <span class="badge badge-loc">${escHtml(j.location)}</span>
        <span class="badge badge-type">${escHtml(j.type)}</span>
      </div>
      <div class="desc">${escHtml(desc)}</div>
      <span class="btn btn-gold btn-sm" style="display:inline-block;width:auto">Apply Now</span>
    </a>`;
  }).join("");

  return layout("MarqueLead Careers — Join the Elite", `
<div class="container">
  <div class="hero">
    <h1>Join the <span>MarqueLead</span> Team</h1>
    <p>We're building the future of high-performance lead generation. If you're elite, dominant, and ready to make an impact — you belong here.</p>
    <div style="display:flex;gap:8px;justify-content:center;flex-wrap:wrap;margin-top:24px">
      <span class="badge badge-dept">Real Estate</span>
      <span class="badge badge-dept">SaaS</span>
      <span class="badge badge-dept">Remote</span>
    </div>
  </div>

  <div style="margin-top:40px;position:relative">
    <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:24px">
      <div>
        <h2 class="section-title">Open Positions</h2>
        <p class="section-subtitle" style="margin-bottom:0">${jobs.length} active role${jobs.length !== 1 ? "s" : ""} — find your next challenge</p>
      </div>
      <button onclick="window.location.href='#openings'" class="btn btn-outline btn-sm">View All</button>
    </div>
    <div class="grid" id="openings">${jobCards || "<p style='color:#888;padding:40px;text-align:center'>No positions open right now. Check back soon.</p>"}</div>
  </div>

  <div style="padding:60px 0;text-align:center;margin-top:40px;border-top:1px solid #1A1A1A">
    <h2 style="font-size:24px;font-weight:600;margin-bottom:12px">Don't see the right role?</h2>
    <p style="color:#888;margin-bottom:20px;font-size:16px">We're always looking for exceptional talent. Send us your resume.</p>
    <a href="mailto:careers@marquelead.com" class="btn btn-outline">Email Us</a>
  </div>
  <div style="padding:20px 0;text-align:center;border-top:1px solid rgba(201,168,76,0.08);margin-top:20px">
    <a href="/admin" style="color:rgba(201,168,76,0.3);font-size:12px;letter-spacing:1px;text-transform:uppercase" onmouseover="this.style.color='rgba(201,168,76,0.6)'" onmouseout="this.style.color='rgba(201,168,76,0.3)'">Admin</a>
  </div>
</div>`);
}

function renderJobDetailPage(slug: string): string {
  const job = getJobBySlug(slug);
  if (!job) {
    return layout("Job Not Found — MarqueLead Careers", `<div class="container" style="text-align:center;padding:100px 0"><h1>Position Not Found</h1><p style="color:#888;margin:16px 0">This role may have been filled or removed.</p><a href="/" class="btn btn-gold">View All Positions</a></div>`);
  }

  let responsibilities = "";
  try { const r = JSON.parse(job.responsibilities); if (Array.isArray(r)) responsibilities = r.map((li: string) => `<li>${escHtml(li)}</li>`).join(""); } catch {}

  let requirements = "";
  try { const r = JSON.parse(job.requirements); if (Array.isArray(r)) requirements = r.map((li: string) => `<li>${escHtml(li)}</li>`).join(""); } catch {}

  const salaryHtml = job.salary_range ? `<div class="salary"><span>${escHtml(job.salary_range)}</span></div>` : "";

  return layout(`${escHtml(job.title)} — MarqueLead Careers`, `
<div class="container">
  <a href="/" style="display:inline-flex;align-items:center;gap:6px;margin:24px 0;color:#888;font-size:14px">
    <svg width="16" height="16" viewBox="0 0 16 16" fill="none"><path d="M10 12L6 8l4-4" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>
    Back to all positions
  </a>
  <div class="job-detail">
    <div style="margin-bottom:12px"><span class="badge badge-dept">${escHtml(job.department)}</span></div>
    <h1>${escHtml(job.title)}</h1>
    <div class="meta">
      <span class="badge badge-loc">${escHtml(job.location)}</span>
      <span class="badge badge-type">${escHtml(job.type)}</span>
    </div>
    ${salaryHtml}
    <section>
      <h2>About the Role</h2>
      <p style="color:#ccc;font-size:15px;line-height:1.8">${escHtml(job.description)}</p>
    </section>
    ${responsibilities ? `<section><h2>What You'll Do</h2><ul>${responsibilities}</ul></section>` : ""}
    ${requirements ? `<section><h2>The Ideal Candidate</h2><ul>${requirements}</ul></section>` : ""}
    <section>
      <h2>Why MarqueLead?</h2>
      <ul>
        <li>Work with elite clients in high-stakes, high-reward environments</li>
        <li>Remote-first culture with a global team of top performers</li>
        <li>Performance-driven compensation with uncapped upside</li>
        <li>Continuous learning and professional development budget</li>
      </ul>
    </section>
    <div class="cta">
      <h2 style="font-size:24px;margin-bottom:8px">Ready to join the team?</h2>
      <p style="color:#888;margin-bottom:24px">Take the first step — we can't wait to hear from you.</p>
      <a href="/apply/${job.slug}" class="btn btn-gold" style="font-size:18px;padding:16px 48px">Apply for This Position</a>
    </div>
  </div>
</div>`);
}

function renderApplyPage(job: Job): string {

  const questions = getQuestions(job.id);
  const questionsJson = JSON.stringify(questions.map(q => ({
    id: q.id,
    question_text: q.question_text,
    question_type: q.question_type,
    options: q.options ? JSON.parse(q.options) : null,
    required: q.required === 1,
    section_label: q.section_label,
  })));

  return layout("Apply — MarqueLead Careers", `
<div class="typeform-screen" id="typeform">
  <div class="typeform-progress"><div class="typeform-progress-fill" id="progress-fill" style="width:0%"></div></div>
  <div class="typeform-header">
    <div style="display:flex;align-items:center;gap:12px">
      <a href="/jobs/${job.slug}" style="color:#888;font-size:14px;display:flex;align-items:center;gap:4px">
        <svg width="16" height="16" viewBox="0 0 16 16" fill="none"><path d="M10 12L6 8l4-4" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>
        Back
      </a>
      <span style="color:#444">|</span>
      <span style="color:#C9A84C;font-weight:600">${escHtml(job.title)}</span>
    </div>
    <div class="typeform-counter" id="step-counter">Question 1 of ${questions.length}</div>
  </div>
  <div class="typeform-body" id="typeform-body">
    <div id="steps-container" style="width:100%;max-width:640px;position:relative;min-height:300px"></div>
  </div>
  <div style="padding:0 32px 24px;display:flex;justify-content:flex-end;max-width:704px;margin:0 auto;width:100%">
    <button class="typeform-btn typeform-btn-primary" id="next-btn">Next <svg width="16" height="16" viewBox="0 0 16 16" fill="none"><path d="M6 4l4 4-4 4" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg></button>
    <button class="typeform-btn typeform-btn-primary" id="submit-btn" style="display:none">Submit Application</button>
  </div>
</div>
<div id="confirmation" style="display:none;padding:80px 20px;text-align:center">
  <h2 style="font-size:36px;color:#C9A84C;margin-bottom:16px">Application Received</h2>
  <p style="font-size:18px;color:#888;margin-bottom:8px">Thank you for applying to MarqueLead.</p>
  <p style="font-size:16px;color:#666;margin-bottom:32px">Our team will review your application and reach out within 5 business days.</p>
  <a href="/" class="btn btn-gold">Back to Careers</a>
</div>
<script>
const questions = ${questionsJson};
let currentStep = 0;
let answers = {};
let applicationId = null;
const stepsContainer = document.getElementById('steps-container');
const nextBtn = document.getElementById('next-btn');
const submitBtn = document.getElementById('submit-btn');
const counter = document.getElementById('step-counter');
const progressFill = document.getElementById('progress-fill');
const typeform = document.getElementById('typeform');
const confirmation = document.getElementById('confirmation');

function renderSteps() {
  let html = '';
  let currentSection = '';
  questions.forEach((q, i) => {
    const section = q.section_label || '';
    let sectionHtml = '';
    if (section && section !== currentSection) {
      currentSection = section;
      sectionHtml = '<div class="typeform-label">' + section + '</div>';
    }
    let inputHtml = '';
    const val = answers[q.id] || '';
    if (q.question_type === 'textarea') {
      inputHtml = '<textarea class="typeform-input typeform-textarea" id="input-' + i + '" data-id="' + q.id + '" data-required="' + q.required + '" placeholder="Your answer...">' + escHtml(val) + '</textarea>';
    } else if (q.question_type === 'select' && q.options) {
      let opts = '<option value="">Select...</option>';
      q.options.forEach(o => { opts += '<option value="' + escHtml(o) + '"' + (val === o ? ' selected' : '') + '>' + escHtml(o) + '</option>'; });
      inputHtml = '<select class="typeform-input typeform-select" id="input-' + i + '" data-id="' + q.id + '" data-required="' + q.required + '">' + opts + '</select>';
    } else {
      inputHtml = '<input class="typeform-input" type="' + q.question_type + '" id="input-' + i + '" data-id="' + q.id + '" data-required="' + q.required + '" placeholder="Your answer..." value="' + escHtml(val) + '" />';
    }
    html += '<div class="typeform-step" data-step="' + i + '">' + sectionHtml + '<div class="typeform-question">' + escHtml(q.question_text) + (q.required ? '' : ' <span style="font-size:16px;color:#888;font-weight:400">(optional)</span>') + '</div>' + inputHtml + '<div class="typeform-error" id="error-' + i + '">This field is required</div></div>';
  });
  stepsContainer.innerHTML = html;
  showStep(0);
}

function showStep(index) {
  const steps = document.querySelectorAll('.typeform-step');
  steps.forEach(s => { s.classList.remove('active', 'exiting'); });
  if (steps[index]) {
    steps[index].classList.add('active');
    updateNav(index);
    const input = document.getElementById('input-' + index);
    if (input) setTimeout(() => input.focus(), 350);
  }
}

function goToStep(index) {
  const currentEl = document.querySelector('.typeform-step.active');
  if (currentEl) currentEl.classList.add('exiting');
  showStep(index);
}

function updateNav(index) {
  const total = questions.length;
  counter.textContent = 'Question ' + (index + 1) + ' of ' + total;
  progressFill.style.width = ((index + 1) / total * 100) + '%';
  if (index === total - 1) {
    nextBtn.style.display = 'none';
    submitBtn.style.display = 'inline-flex';
  } else {
    nextBtn.style.display = 'inline-flex';
    submitBtn.style.display = 'none';
  }
}

function getInputValue(index) {
  const el = document.getElementById('input-' + index);
  if (!el) return '';
  return el.value.trim();
}

function validateStep(index) {
  const el = document.getElementById('input-' + index);
  const err = document.getElementById('error-' + index);
  if (!el) return true;
  const required = el.dataset.required === 'true';
  if (required && !el.value.trim()) {
    if (err) err.style.display = 'block';
    el.style.borderColor = '#dc2626';
    return false;
  }
  if (err) err.style.display = 'none';
  el.style.borderColor = '';
  return true;
}

nextBtn.addEventListener('click', function() {
  if (!validateStep(currentStep)) return;
  const el = document.getElementById('input-' + currentStep);
  if (el) answers[el.dataset.id] = el.value.trim();
  currentStep++;
  if (currentStep < questions.length) goToStep(currentStep);
});

submitBtn.addEventListener('click', async function() {
  if (!validateStep(currentStep)) return;
  const el = document.getElementById('input-' + currentStep);
  if (el) answers[el.dataset.id] = el.value.trim();
  submitBtn.disabled = true;
  submitBtn.textContent = 'Submitting...';
  try {
    const res = await fetch('/api/applications', {
      method: 'POST',
      headers: { 'content-type': 'application/json' },
      body: JSON.stringify({ jobId: '${job.id}', answers: answers })
    });
    const data = await res.json();
    if (data.success) {
      typeform.style.display = 'none';
      confirmation.style.display = 'block';
    } else {
      alert(data.error || 'Submission failed. Please try again.');
      submitBtn.disabled = false;
      submitBtn.textContent = 'Submit Application';
    }
  } catch(e) {
    alert('Network error. Please try again.');
    submitBtn.disabled = false;
    submitBtn.textContent = 'Submit Application';
  }
});

document.addEventListener('keydown', function(e) {
  if (e.key === 'Enter') {
    const active = document.querySelector('.typeform-step.active');
    if (active) {
      if (currentStep === questions.length - 1) submitBtn.click();
      else nextBtn.click();
    }
  }
});

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

function renderAdminLoginPage(error = false): string {
  return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Admin Login — MarqueLead Careers</title>
<style>${ADMIN_CSS}</style>
</head>
<body>
<div class="auth-card">
  <h1>MarqueLead <span style="color:#C9A84C">Admin</span></h1>
  <p class="sub">Sign in to manage careers & applications</p>
  ${error ? '<div class="auth-error" style="display:block">Invalid password</div>' : ''}
  <form action="/admin/login" method="POST">
    <div class="form-group">
      <label>Password</label>
      <input type="password" name="password" class="gold-glow" placeholder="Enter admin password..." style="margin-bottom:16px" autofocus />
    </div>
    <button type="submit" class="btn btn-gold">Sign In</button>
  </form>
</div>
</body>
</html>`;
}

function renderDashboardPage(token: string, passwordChanged = false, passwordError = false): string {
  const t = token ? `?token=${token}` : "";
  const stats = getDashboardStats();
  const bannerHtml = passwordChanged
    ? '<div style="background:#16a34a20;border:1px solid #16a34a40;color:#4ade80;padding:12px 16px;border-radius:8px;margin-bottom:20px;font-size:14px">Password changed successfully.</div>'
    : passwordError
    ? '<div style="background:#dc262620;border:1px solid #dc262640;color:#f87171;padding:12px 16px;border-radius:8px;margin-bottom:20px;font-size:14px">Password change failed. Check your current password and try again.</div>'
    : "";
  return adminLayout("Dashboard — MarqueLead Admin", `
<div style="margin-bottom:24px">
  <h1 style="font-size:28px;font-weight:700">Dashboard</h1>
  <p style="color:#888;font-size:14px">Overview of your careers portal</p>
</div>
${bannerHtml}
<div class="stats-grid">
  <div class="stat-card"><div class="value">${stats.totalJobs}</div><div class="label">Total Jobs</div></div>
  <div class="stat-card"><div class="value">${stats.totalApplications}</div><div class="label">Total Applications</div></div>
  <div class="stat-card"><div class="value">${stats.appsThisWeek}</div><div class="label">Applications This Week</div></div>
  <div class="stat-card"><div class="value">${stats.newApps}</div><div class="label">New Applications</div></div>
</div>
<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(240px,1fr));gap:16px">
  <a href="/admin/jobs${t}" class="card" style="display:block;cursor:pointer;text-decoration:none;color:inherit">
    <h3 style="color:#C9A84C;font-size:18px;margin-bottom:8px">Jobs Manager</h3>
    <p style="color:#888;font-size:14px">Create, edit, and manage job listings</p>
  </a>
  <a href="/admin/questions${t}" class="card" style="display:block;cursor:pointer;text-decoration:none;color:inherit">
    <h3 style="color:#C9A84C;font-size:18px;margin-bottom:8px">Questions Manager</h3>
    <p style="color:#888;font-size:14px">Customize application form questions</p>
  </a>
  <a href="/admin/applications${t}" class="card" style="display:block;cursor:pointer;text-decoration:none;color:inherit">
    <h3 style="color:#C9A84C;font-size:18px;margin-bottom:8px">Applications</h3>
    <p style="color:#888;font-size:14px">Review and manage incoming applications</p>
  </a>
</div>
<div style="margin-top:32px">
  <div class="card" style="max-width:480px">
    <h3 style="color:#C9A84C;font-size:18px;margin-bottom:16px">Change Password</h3>
    <form action="/admin/api/change-password${t}" method="POST" autocomplete="off">
      <div class="form-group">
        <label>Current Password</label>
        <input type="password" name="current_password" required class="gold-glow" autocomplete="current-password">
      </div>
      <div class="form-group">
        <label>New Password</label>
        <input type="password" name="new_password" required class="gold-glow" minlength="4" autocomplete="new-password">
      </div>
      <div class="form-group">
        <label>Confirm New Password</label>
        <input type="password" name="confirm_password" required class="gold-glow" autocomplete="new-password">
      </div>
      <button type="submit" class="btn btn-gold" style="width:100%;margin-top:8px">Update Password</button>
    </form>
  </div>
</div>`, "", token);
}

function renderAdminJobsPage(token: string): string {
  const t = token ? `?token=${token}` : "";
  const jobs = getJobs();
  const rows = jobs.map(j => {
    const appCount = getApplicationCountByJob(j.id);
    return `<tr>
      <td style="font-weight:500">${escHtml(j.title)}</td>
      <td><span class="badge badge-dept">${escHtml(j.department)}</span></td>
      <td>${j.is_active ? '<span style="color:#4ade80">●</span> Active' : '<span style="color:#888">●</span> Inactive'}</td>
      <td>${appCount}</td>
      <td>
        <button class="btn btn-outline btn-sm" onclick="editJob('${j.id}')">Edit</button>
        <button class="btn btn-outline btn-sm" style="border-color:#dc2626;color:#f87171" onclick="deleteJob('${j.id}','${escHtml(j.title)}')">Delete</button>
      </td>
    </tr>`;
  }).join("");

  return adminLayout("Jobs — MarqueLead Admin", `
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:24px">
  <div>
    <h1 style="font-size:28px;font-weight:700">Jobs</h1>
    <p style="color:#888;font-size:14px">${jobs.length} total positions</p>
  </div>
  <button class="btn btn-gold" onclick="showAddModal()">+ Add Job</button>
</div>
<div class="card" style="padding:0;overflow-x:auto">
  <table>
    <thead><tr><th>Title</th><th>Department</th><th>Status</th><th>Applications</th><th>Actions</th></tr></thead>
    <tbody>${rows || '<tr><td colspan="5" style="text-align:center;color:#888;padding:40px">No jobs yet</td></tr>'}</tbody>
  </table>
</div>

<div class="modal-overlay" id="job-modal">
  <div class="modal-content">
    <h2 id="modal-title">Add Job</h2>
    <form id="job-form" onsubmit="return saveJob(event)">
      <input type="hidden" id="job-id">
      <div class="form-group">
        <label>Title *</label>
        <input type="text" id="job-title" required class="gold-glow">
      </div>
      <div class="form-group">
        <label>Department *</label>
        <input type="text" id="job-dept" required class="gold-glow">
      </div>
      <div class="form-group">
        <label>Location</label>
        <input type="text" id="job-location" value="Remote" class="gold-glow">
      </div>
      <div class="form-group">
        <label>Type</label>
        <select id="job-type" class="gold-glow">
          <option>Full-time</option>
          <option>Part-time</option>
          <option>Contract</option>
          <option>Internship</option>
        </select>
      </div>
      <div class="form-group">
        <label>Salary Range</label>
        <input type="text" id="job-salary" placeholder="e.g. $60,000 - $85,000" class="gold-glow">
      </div>
      <div class="form-group">
        <label>Description *</label>
        <textarea id="job-desc" required rows="4" class="gold-glow"></textarea>
      </div>
      <div class="form-group">
        <label>Responsibilities (one per line)</label>
        <textarea id="job-resp" rows="4" placeholder="Lead outbound campaigns&#10;Develop strategies..." class="gold-glow"></textarea>
      </div>
      <div class="form-group">
        <label>Requirements (one per line)</label>
        <textarea id="job-req" rows="4" placeholder="2+ years experience&#10;Proven track record..." class="gold-glow"></textarea>
      </div>
      <div class="form-group">
        <label><input type="checkbox" id="job-active" checked> Active</label>
      </div>
      <div class="form-actions">
        <button type="button" class="btn btn-outline" onclick="closeModal()">Cancel</button>
        <button type="submit" class="btn btn-gold">Save</button>
      </div>
    </form>
  </div>
</div>

<script>
const TOKEN = '${token}';
const Q = TOKEN ? '?token=' + TOKEN : '';

async function saveJob(e) {
  e.preventDefault();
  const id = document.getElementById('job-id').value;
  const data = {
    title: document.getElementById('job-title').value,
    department: document.getElementById('job-dept').value,
    location: document.getElementById('job-location').value,
    type: document.getElementById('job-type').value,
    description: document.getElementById('job-desc').value,
    salary_range: document.getElementById('job-salary').value,
    responsibilities: JSON.stringify(document.getElementById('job-resp').value.split('\\n').filter(l=>l.trim())),
    requirements: JSON.stringify(document.getElementById('job-req').value.split('\\n').filter(l=>l.trim())),
    is_active: document.getElementById('job-active').checked ? 1 : 0,
  };
  const url = (id ? '/admin/api/jobs/' + id : '/admin/api/jobs') + Q;
  const method = id ? 'PUT' : 'POST';
  const res = await fetch(url, { method, headers: {'content-type':'application/json'}, body: JSON.stringify(data) });
  if (res.ok) window.location.reload();
  else { const r = await res.json(); alert(r.error || 'Error saving job'); }
  return false;
}

async function deleteJob(id, title) {
  if (!confirm('Delete "' + title + '"? This cannot be undone.')) return;
  const res = await fetch('/admin/api/jobs/' + id + Q, { method: 'DELETE' });
  if (res.ok) window.location.reload();
  else { const r = await res.json(); alert(r.error || 'Error deleting job'); }
}

async function editJob(id) {
  const res = await fetch('/admin/api/jobs/' + id + Q);
  const job = await res.json();
  document.getElementById('modal-title').textContent = 'Edit Job';
  document.getElementById('job-id').value = job.id;
  document.getElementById('job-title').value = job.title;
  document.getElementById('job-dept').value = job.department;
  document.getElementById('job-location').value = job.location;
  document.getElementById('job-type').value = job.type;
  document.getElementById('job-salary').value = job.salary_range || '';
  document.getElementById('job-desc').value = job.description;
  let resp = '';
  try { const r = JSON.parse(job.responsibilities); if (Array.isArray(r)) resp = r.join('\\n'); } catch {}
  document.getElementById('job-resp').value = resp;
  let req = '';
  try { const r = JSON.parse(job.requirements); if (Array.isArray(r)) req = r.join('\\n'); } catch {}
  document.getElementById('job-req').value = req;
  document.getElementById('job-active').checked = job.is_active === 1;
  document.getElementById('job-modal').style.display = 'flex';
}

function showAddModal() {
  document.getElementById('modal-title').textContent = 'Add Job';
  document.getElementById('job-id').value = '';
  document.getElementById('job-form').reset();
  document.getElementById('job-location').value = 'Remote';
  document.getElementById('job-active').checked = true;
  document.getElementById('job-modal').style.display = 'flex';
}

function closeModal() {
  document.getElementById('job-modal').style.display = 'none';
}
</script>`, "", token);
}

function renderAdminQuestionsPage(token: string): string {
  const t = token ? `?token=${token}` : "";
  const questions = getQuestions();
  const grouped: Record<string, typeof questions> = {};
  for (const q of questions) {
    const section = q.section_label || "General";
    if (!grouped[section]) grouped[section] = [];
    grouped[section].push(q);
  }

  const sectionHtml = Object.entries(grouped).map(([section, qs]) => {
    const cards = qs.map(q => {
      const typeLabel = q.question_type.charAt(0).toUpperCase() + q.question_type.slice(1);
      const hasOptions = q.options ? JSON.parse(q.options) : null;
      return `<div class="question-card" data-id="${q.id}">
        <div class="header">
          <div><div class="text">${escHtml(q.question_text)}</div>
          <div class="meta">
            <span class="badge badge-dept">${typeLabel}</span>
            ${q.required ? '<span class="badge badge-gold" style="color:#0A0A0A">Required</span>' : '<span class="badge badge-loc">Optional</span>'}
            ${hasOptions ? '<span class="badge badge-loc">' + hasOptions.length + ' options</span>' : ''}
          </div></div>
          <div class="actions">
            <button class="btn btn-outline btn-sm" onclick="editQuestion('${q.id}')">Edit</button>
            <button class="btn btn-outline btn-sm" style="border-color:#dc2626;color:#f87171" onclick="deleteQuestion('${q.id}')">Delete</button>
          </div>
        </div>
      </div>`;
    }).join("");
    return `<div class="section-group"><h3>${escHtml(section)} (${qs.length})</h3>${cards}</div>`;
  }).join("");

  return adminLayout("Questions — MarqueLead Admin", `
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:24px">
  <div>
    <h1 style="font-size:28px;font-weight:700">Application Questions</h1>
    <p style="color:#888;font-size:14px">${questions.length} total questions</p>
  </div>
  <button class="btn btn-gold" onclick="showAddQuestionModal()">+ Add Question</button>
</div>
${sectionHtml}

<div class="modal-overlay" id="question-modal">
  <div class="modal-content">
    <h2 id="q-modal-title">Add Question</h2>
    <form id="question-form" onsubmit="return saveQuestion(event)">
      <input type="hidden" id="question-id">
      <div class="form-group">
        <label>Section Label</label>
        <input type="text" id="q-section" placeholder="e.g. About You, Experience" class="gold-glow">
      </div>
      <div class="form-group">
        <label>Question Text *</label>
        <textarea id="q-text" required rows="2" class="gold-glow"></textarea>
      </div>
      <div class="form-group">
        <label>Question Type</label>
        <select id="q-type" class="gold-glow" onchange="toggleOptionsField()">
          <option value="text">Text</option>
          <option value="textarea">Textarea</option>
          <option value="email">Email</option>
          <option value="phone">Phone</option>
          <option value="select">Select (Dropdown)</option>
          <option value="file">File</option>
        </select>
      </div>
      <div class="form-group" id="options-group" style="display:none">
        <label>Options (one per line)</label>
        <textarea id="q-options" rows="4" class="gold-glow" placeholder="Option 1&#10;Option 2&#10;Option 3"></textarea>
      </div>
      <div class="form-group" id="file-types-group" style="display:none">
        <label>Allowed File Types (comma-separated)</label>
        <input type="text" id="q-file-types" value="pdf,jpg,png,doc,docx,zip" class="gold-glow" placeholder="pdf,jpg,png,doc,docx,zip">
      </div>
      <div class="form-group">
        <label><input type="checkbox" id="q-required" checked> Required</label>
      </div>
      <div class="form-actions">
        <button type="button" class="btn btn-outline" onclick="closeQuestionModal()">Cancel</button>
        <button type="submit" class="btn btn-gold">Save</button>
      </div>
    </form>
  </div>
</div>

<script>
const TOKEN = '${token}';
const Q = TOKEN ? '?token=' + TOKEN : '';

function toggleOptionsField() {
  const type = document.getElementById('q-type').value;
  document.getElementById('options-group').style.display = type === 'select' ? 'block' : 'none';
  document.getElementById('file-types-group').style.display = type === 'file' ? 'block' : 'none';
}

async function saveQuestion(e) {
  e.preventDefault();
  const id = document.getElementById('question-id').value;
  const data = {
    question_text: document.getElementById('q-text').value,
    question_type: document.getElementById('q-type').value,
    section_label: document.getElementById('q-section').value,
    required: document.getElementById('q-required').checked ? 1 : 0,
  };
  if (data.question_type === 'select') {
    data.options = JSON.stringify(document.getElementById('q-options').value.split('\\n').filter(l=>l.trim()));
  }
  if (data.question_type === 'file') {
    data.file_types = document.getElementById('q-file-types').value.trim() || 'pdf,jpg,png,doc,docx,zip';
  }
  const url = (id ? '/admin/api/questions/' + id : '/admin/api/questions') + Q;
  const method = id ? 'PUT' : 'POST';
  const res = await fetch(url, { method, headers: {'content-type':'application/json'}, body: JSON.stringify(data) });
  if (res.ok) window.location.reload();
  else { const r = await res.json(); alert(r.error || 'Error saving question'); }
  return false;
}

async function deleteQuestion(id) {
  if (!confirm('Delete this question?')) return;
  const res = await fetch('/admin/api/questions/' + id + Q, { method: 'DELETE' });
  if (res.ok) window.location.reload();
}

async function editQuestion(id) {
  const res = await fetch('/admin/api/questions/' + id + Q);
  const q = await res.json();
  document.getElementById('q-modal-title').textContent = 'Edit Question';
  document.getElementById('question-id').value = q.id;
  document.getElementById('q-text').value = q.question_text;
  document.getElementById('q-type').value = q.question_type;
  document.getElementById('q-section').value = q.section_label || '';
  document.getElementById('q-required').checked = q.required === 1;
  if (q.question_type === 'select' && q.options) {
    let opts = '';
    try { const o = JSON.parse(q.options); if (Array.isArray(o)) opts = o.join('\\n'); } catch {}
    document.getElementById('q-options').value = opts;
  }
  if (q.question_type === 'file') {
    document.getElementById('q-file-types').value = q.file_types || 'pdf,jpg,png,doc,docx,zip';
  }
  toggleOptionsField();
  document.getElementById('question-modal').style.display = 'flex';
}

function showAddQuestionModal() {
  document.getElementById('q-modal-title').textContent = 'Add Question';
  document.getElementById('question-id').value = '';
  document.getElementById('question-form').reset();
  document.getElementById('q-required').checked = true;
  document.getElementById('options-group').style.display = 'none';
  document.getElementById('file-types-group').style.display = 'none';
  document.getElementById('question-modal').style.display = 'flex';
}

function closeQuestionModal() { document.getElementById('question-modal').style.display = 'none'; }
</script>`, "", token);
}

function renderAdminApplicationsPage(token: string, apps?: Application[], jobs?: Job[]): string {
  const t = token ? `?token=${token}` : "";
  apps = apps || getApplications();
  jobs = jobs || getJobs();
  const jobOptions = jobs.map(j => `<option value="${j.id}">${escHtml(j.title)}</option>`).join("");
  const statuses = ["all", "new", "reviewed", "shortlisted", "rejected", "hired"];

  const rows = apps.map(a => {
    const job = jobs.find(j => j.id === a.job_id);
    const statusClass = `status-${a.status}`;
    return `<tr onclick="window.location.href='/admin/applications/${a.id}${t}'" style="cursor:pointer">
      <td>${escHtml(a.applicant_name)}</td>
      <td>${escHtml(a.applicant_email)}</td>
      <td>${job ? escHtml(job.title) : '<span style="color:#888">Unknown</span>'}</td>
      <td><span class="badge ${statusClass}">${escHtml(a.status)}</span></td>
      <td style="color:#888;font-size:13px">${new Date(a.created_at).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })}</td>
    </tr>`;
  }).join("");

  return adminLayout("Applications — MarqueLead Admin", `
<div style="margin-bottom:24px">
  <h1 style="font-size:28px;font-weight:700">Applications</h1>
  <p style="color:#888;font-size:14px">${apps.length} total applications</p>
</div>
<div class="filter-bar">
  <select id="filter-job" onchange="applyFilters()" class="gold-glow">
    <option value="">All Jobs</option>
    ${jobOptions}
  </select>
</div>
<div class="filter-tabs">
  ${statuses.map(s => `<button class="filter-tab ${s === "all" ? "active" : ""}" onclick="setStatus('${s}')">${s.charAt(0).toUpperCase() + s.slice(1)}</button>`).join("")}
</div>
<div class="card" style="padding:0;overflow-x:auto">
  <table>
    <thead><tr><th>Name</th><th>Email</th><th>Job</th><th>Status</th><th>Submitted</th></tr></thead>
    <tbody>${rows || '<tr><td colspan="5" style="text-align:center;color:#888;padding:40px">No applications yet</td></tr>'}</tbody>
  </table>
</div>
<script>
function applyFilters() {
  const job = document.getElementById('filter-job').value;
  const params = new URLSearchParams(window.location.search);
  if (job) params.set('job', job);
  else params.delete('job');
  window.location.search = params.toString();
}
function setStatus(s) {
  const params = new URLSearchParams(window.location.search);
  if (s && s !== 'all') params.set('status', s);
  else params.delete('status');
  window.location.search = params.toString();
}
</script>`, "", token);
}

function renderAdminApplicationDetailPage(token: string, id: string): string {
  const t = token ? `?token=${token}` : "";
  const app = getApplicationById(id);
  if (!app) return adminLayout("Not Found", `<p>Application not found.</p>`, "", token);

  const job = getJobById(app.job_id);
  const questions = getQuestions(app.job_id);

  const answers: Record<string, string> = {};
  try { Object.assign(answers, JSON.parse(app.answers)); } catch {}

  const grouped: Record<string, { q: string; a: string }[]> = {};
  for (const q of questions) {
    const section = q.section_label || "General";
    if (!grouped[section]) grouped[section] = [];
    grouped[section].push({ q: q.question_text, a: answers[q.id] || "(not answered)" });
  }

  const qaHtml = Object.entries(grouped).map(([section, items]) => {
    const itemsHtml = items.map(i =>
      `<div class="qa-item"><div class="q">${escHtml(i.q)}</div><div class="a">${escHtml(i.a)}</div></div>`
    ).join("");
    return `<div class="qa-section"><h3>${escHtml(section)}</h3>${itemsHtml}</div>`;
  }).join("");

  const statusClass = `status-${app.status}`;
  const statusOptions = ["new", "reviewed", "shortlisted", "rejected", "hired"]
    .map(s => `<option value="${s}" ${s === app.status ? "selected" : ""}>${s.charAt(0).toUpperCase() + s.slice(1)}</option>`).join("");

  return adminLayout("Application Detail — MarqueLead Admin", `
<div class="app-detail">
  <div class="header">
    <a href="/admin/applications${t}" style="color:#888;font-size:14px;display:flex;align-items:center;gap:4px;margin-bottom:16px">
      <svg width="16" height="16" viewBox="0 0 16 16" fill="none"><path d="M10 12L6 8l4-4" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>
      Back to Applications
    </a>
    <h1>${escHtml(app.applicant_name)}</h1>
    <span class="badge ${statusClass}" style="font-size:14px;padding:6px 16px">${escHtml(app.status)}</span>
  </div>

  <div class="info">
    <div class="info-item"><div class="l">Email</div><div class="v">${escHtml(app.applicant_email)}</div></div>
    <div class="info-item"><div class="l">Position</div><div class="v">${job ? escHtml(job.title) : "Unknown"}</div></div>
    <div class="info-item"><div class="l">Submitted</div><div class="v">${new Date(app.created_at).toLocaleDateString("en-US", { month: "long", day: "numeric", year: "numeric", hour: "2-digit", minute: "2-digit" })}</div></div>
  </div>

  ${qaHtml}

  <div class="admin-tools">
    <h3>Admin Tools</h3>
    <div class="form-group">
      <label>Status</label>
      <div style="display:flex;gap:8px;align-items:center">
        <select id="app-status" class="gold-glow" style="max-width:200px">${statusOptions}</select>
        <button class="btn btn-gold btn-sm" onclick="saveStatus()">Save</button>
      </div>
    </div>
    <div class="form-group">
      <label>Notes</label>
      <textarea id="app-notes" rows="4" class="gold-glow">${escHtml(app.admin_notes)}</textarea>
      <button class="btn btn-gold btn-sm" style="margin-top:8px" onclick="saveNotes()">Save Notes</button>
    </div>
  </div>
</div>
<script>
const TOKEN = '${token}';
const Q = TOKEN ? '?token=' + TOKEN : '';

async function saveStatus() {
  const status = document.getElementById('app-status').value;
  const res = await fetch('/admin/api/applications/${id}/status' + Q, {
    method: 'PUT',
    headers: {'content-type':'application/json'},
    body: JSON.stringify({ status })
  });
  if (res.ok) window.location.reload();
  else alert('Error updating status');
}
async function saveNotes() {
  const notes = document.getElementById('app-notes').value;
  const res = await fetch('/admin/api/applications/${id}/notes' + Q, {
    method: 'PUT',
    headers: {'content-type':'application/json'},
    body: JSON.stringify({ notes })
  });
  if (res.ok) { showToast('Notes saved', 'success'); }
  else alert('Error saving notes');
}
function showToast(msg, type) {
  const t = document.createElement('div');
  t.className = 'toast toast-' + type;
  t.textContent = msg;
  t.style.display = 'block';
  document.body.appendChild(t);
  setTimeout(() => t.remove(), 3000);
}
</script>`, "", token);
}

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

const port = parseInt(Deno.args[0]);
if (!port) throw new Error("Port must be passed as first argument");

Deno.serve({ port }, async (req) => {
  try {
    const url = new URL(req.url);
    const pathname = url.pathname;
    const method = req.method;

    // Health
    if (pathname === "/health") {
      return json({ status: "ok" });
    }

    // Public API: Get jobs list (GET /api/jobs)
    if (pathname === "/api/jobs" && method === "GET") {
      const jobs = getJobs(true);
      return json({ jobs: jobs.map(j => ({
        id: j.id,
        title: j.title,
        slug: j.slug,
        department: j.department,
        location: j.location,
        type: j.type,
        description_short: j.description.length > 200 ? j.description.substring(0, 200) + "..." : j.description,
      })) });
    }

    // Public API: Get questions for a job (GET /api/jobs/:slug/questions)
    const apiJobQuestionsMatch = pathname.match(/^\/api\/jobs\/([^\/]+)\/questions$/);
    if (apiJobQuestionsMatch && method === "GET") {
      const slug = apiJobQuestionsMatch[1];
      const job = getJobBySlug(slug);
      if (!job) return json({ error: "Job not found" }, 404);
      const questions = getQuestions(job.id);
      return json({
        job: { id: job.id, title: job.title },
        questions: questions.map(q => ({
          id: q.id,
          question_text: q.question_text,
          question_type: q.question_type,
          options: q.options ? JSON.parse(q.options) : null,
          required: q.required === 1,
          section_label: q.section_label,
        })),
      });
    }

    // Public API: Submit application (POST /api/applications)
    if (pathname === "/api/applications" && method === "POST") {
      const body = await req.json();
      const { jobId, answers } = body;
      if (!jobId || !answers) return json({ error: "jobId and answers are required" }, 400);

      const job = getJobById(jobId);
      if (!job) return json({ error: "Job not found" }, 404);

      const questions = getQuestions(jobId);
      const nameQ = questions.find(q => q.question_text.toLowerCase().includes("full name"));
      const emailQ = questions.find(q => q.question_text.toLowerCase().includes("email address"));

      const applicantName = nameQ ? (answers[nameQ.id] || "") : "";
      const applicantEmail = emailQ ? (answers[emailQ.id] || "") : "";

      if (!applicantName || !applicantEmail) return json({ error: "Name and email are required" }, 400);

      // Validate required fields
      for (const q of questions) {
        if (q.required && (!answers[q.id] || !answers[q.id].trim())) {
          return json({ error: `"${q.question_text}" is required` }, 400);
        }
      }

      const app = createApplication({
        job_id: jobId,
        applicant_name: applicantName,
        applicant_email: applicantEmail,
        answers: JSON.stringify(answers),
      });

      const phoneQ = questions.find(q => q.question_text.toLowerCase().includes("phone number"));
      const applicantPhone = phoneQ ? (answers[phoneQ.id] || "") : "";

      let qaHtml = "";
      let currentSection = "";
      for (const q of questions) {
        const section = q.section_label || "General";
        if (section !== currentSection) {
          currentSection = section;
          qaHtml += `<tr><td colspan="2" style="padding:16px 0 8px;font-size:13px;color:#C9A84C;text-transform:uppercase;letter-spacing:1px;font-weight:600">${escHtml(section)}</td></tr>`;
        }
        const answer = answers[q.id] || "(not answered)";
        qaHtml += `<tr><td style="padding:8px 16px 8px 0;vertical-align:top;color:#aaa;font-size:13px;width:40%">${escHtml(q.question_text)}</td><td style="padding:8px 0;color:#F5F5F5;font-size:14px">${escHtml(answer)}</td></tr>`;
      }

      const emailBody = `<!DOCTYPE html>
<html>
<head><meta charset="utf-8"></head>
<body style="margin:0;padding:0;background:#0A0A0A;font-family:Inter,system-ui,sans-serif">
<table width="100%" cellpadding="0" cellspacing="0"><tr><td align="center" style="padding:40px 20px">
<table width="600" cellpadding="0" cellspacing="0" style="background:#111;border-radius:12px;border:1px solid #2A2A2A">
<tr><td style="padding:32px">
<table width="100%" cellpadding="0" cellspacing="0">
<tr><td style="text-align:center;padding-bottom:24px;border-bottom:1px solid #2A2A2A">
<h1 style="margin:0;font-size:24px;color:#C9A84C;font-weight:700">New Application</h1>
<p style="margin:8px 0 0;color:#888;font-size:14px">${escHtml(job.title)}</p>
</td></tr>
<tr><td style="padding:24px 0">
<table width="100%" cellpadding="0" cellspacing="0">
<tr><td style="padding:8px 16px 8px 0;color:#aaa;font-size:13px;width:40%">Name</td><td style="padding:8px 0;color:#F5F5F5;font-size:14px">${escHtml(applicantName)}</td></tr>
<tr><td style="padding:8px 16px 8px 0;color:#aaa;font-size:13px">Email</td><td style="padding:8px 0;color:#F5F5F5;font-size:14px">${escHtml(applicantEmail)}</td></tr>
${applicantPhone ? `<tr><td style="padding:8px 16px 8px 0;color:#aaa;font-size:13px">Phone</td><td style="padding:8px 0;color:#F5F5F5;font-size:14px">${escHtml(applicantPhone)}</td></tr>` : ""}
</table>
</td></tr>
<tr><td style="padding:0 0 24px;border-bottom:1px solid #2A2A2A">
<table width="100%" cellpadding="0" cellspacing="0">${qaHtml}</table>
</td></tr>
<tr><td style="padding:24px 0 0;text-align:center">
<a href="https://e226c94f-6308-4663-822d-a4f041cb4a75.amen.matikiti.com/admin/applications/${app.id}" style="display:inline-block;padding:12px 32px;background:linear-gradient(135deg,#C9A84C,#A68A2A);color:#0A0A0A;text-decoration:none;border-radius:6px;font-weight:600;font-size:14px">Review in Admin Panel</a>
</td></tr>
</table>
</td></tr></table>
</td></tr></table>
</body>
</html>`;

      fetch("https://5bc994cd-fda8-451f-a0db-ced71c17b9f4.amen.matikiti.com/send", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({
          to: "careers@marquelead.com",
          subject: `New Application: ${job.title} — ${applicantName}`,
          body: emailBody,
        }),
      }).catch(e => console.error("[marquelead-careers] Email notification failed:", e));

      return json({ success: true, applicationId: app.id });
    }

    // Public API: Upload file for application (POST /api/applications/:id/upload)
    const uploadMatch = pathname.match(/^\/api\/applications\/([^\/]+)\/upload$/);
    if (uploadMatch && method === "POST") {
      return json({ error: "File uploads are disabled" }, 400);
    }

    // Admin API: Get job by ID (GET /admin/api/jobs/:id)
    const adminGetJobMatch = pathname.match(/^\/admin\/api\/jobs\/([^\/]+)$/);
    if (adminGetJobMatch && method === "GET") {
      const guard = await adminGuard(req);
      if (guard) return guard;
      const job = getJobById(adminGetJobMatch[1]);
      if (!job) return json({ error: "Job not found" }, 404);
      return json(job);
    }

    // Admin API: Get question by ID (GET /admin/api/questions/:id)
    const adminGetQuestionMatch = pathname.match(/^\/admin\/api\/questions\/([^\/]+)$/);
    if (adminGetQuestionMatch && method === "GET") {
      const guard = await adminGuard(req);
      if (guard) return guard;
      const q = getQuestionById(adminGetQuestionMatch[1]);
      if (!q) return json({ error: "Question not found" }, 404);
      return json(q);
    }

    // Admin API: Create job (POST /admin/api/jobs)
    if (pathname === "/admin/api/jobs" && method === "POST") {
      const guard = await adminGuard(req);
      if (guard) return guard;
      const body = await req.json();
      if (!body.title || !body.department || !body.description) {
        return json({ error: "title, department, and description are required" }, 400);
      }
      const job = createJob(body);
      return json(job, 201);
    }

    // Admin API: Update job (PUT /admin/api/jobs/:id)
    if (adminGetJobMatch && method === "PUT") {
      const guard = await adminGuard(req);
      if (guard) return guard;
      const body = await req.json();
      const job = updateJob(adminGetJobMatch[1], body);
      if (!job) return json({ error: "Job not found" }, 404);
      return json(job);
    }

    // Admin API: Delete job (DELETE /admin/api/jobs/:id)
    if (adminGetJobMatch && method === "DELETE") {
      const guard = await adminGuard(req);
      if (guard) return guard;
      deleteJob(adminGetJobMatch[1]);
      return json({ success: true });
    }

    // Admin API: Reorder jobs (POST /admin/api/jobs/reorder)
    if (pathname === "/admin/api/jobs/reorder" && method === "POST") {
      const guard = await adminGuard(req);
      if (guard) return guard;
      const body = await req.json();
      if (!body.orderedIds || !Array.isArray(body.orderedIds)) {
        return json({ error: "orderedIds array required" }, 400);
      }
      reorderJobs(body.orderedIds);
      return json({ success: true });
    }

    // Admin API: Create question (POST /admin/api/questions)
    if (pathname === "/admin/api/questions" && method === "POST") {
      const guard = await adminGuard(req);
      if (guard) return guard;
      const body = await req.json();
      if (!body.question_text) return json({ error: "question_text is required" }, 400);
      const q = createQuestion(body);
      return json(q, 201);
    }

    // Admin API: Update question (PUT /admin/api/questions/:id)
    const adminQuestionMatch = pathname.match(/^\/admin\/api\/questions\/([^\/]+)$/);
    if (adminQuestionMatch && method === "PUT") {
      const guard = await adminGuard(req);
      if (guard) return guard;
      const body = await req.json();
      const q = updateQuestion(adminQuestionMatch[1], body);
      if (!q) return json({ error: "Question not found" }, 404);
      return json(q);
    }

    // Admin API: Delete question (DELETE /admin/api/questions/:id)
    if (adminQuestionMatch && method === "DELETE") {
      const guard = await adminGuard(req);
      if (guard) return guard;
      deleteQuestion(adminQuestionMatch[1]);
      return json({ success: true });
    }

    // Admin API: Reorder questions (POST /admin/api/questions/reorder)
    if (pathname === "/admin/api/questions/reorder" && method === "POST") {
      const guard = await adminGuard(req);
      if (guard) return guard;
      const body = await req.json();
      if (!body.orderedIds || !Array.isArray(body.orderedIds)) {
        return json({ error: "orderedIds array required" }, 400);
      }
      reorderQuestions(body.orderedIds);
      return json({ success: true });
    }

    // Admin API: Update application status (PUT /admin/api/applications/:id/status)
    const appStatusMatch = pathname.match(/^\/admin\/api\/applications\/([^\/]+)\/status$/);
    if (appStatusMatch && method === "PUT") {
      const guard = await adminGuard(req);
      if (guard) return guard;
      const body = await req.json();
      if (!body.status) return json({ error: "status is required" }, 400);
      const app = updateApplicationStatus(appStatusMatch[1], body.status);
      if (!app) return json({ error: "Application not found" }, 404);
      return json({ success: true });
    }

    // Admin API: Update application notes (PUT /admin/api/applications/:id/notes)
    const appNotesMatch = pathname.match(/^\/admin\/api\/applications\/([^\/]+)\/notes$/);
    if (appNotesMatch && method === "PUT") {
      const guard = await adminGuard(req);
      if (guard) return guard;
      const body = await req.json();
      const app = updateApplicationNotes(appNotesMatch[1], body.notes || "");
      if (!app) return json({ error: "Application not found" }, 404);
      return json({ success: true });
    }

    // ===== AUTH ROUTES (token-based, no cookies, no redirects) =====

    // POST /admin/login — render dashboard on success, login page with error on failure
    if (pathname === "/admin/login" && method === "POST") {
      try {
        const body = await req.clone().text();
        const params = new URLSearchParams(body);
        const password = params.get("password") || "";
        const storedHash = getSetting("admin_password");
        if (!storedHash) return html(renderAdminLoginPage(false));
        const inputHash = await sha256(password);
        if (inputHash !== storedHash) {
          return html(renderAdminLoginPage(true));
        }
        const sessionId = createSession();
        const totalJobs = (db.queryEntries("SELECT COUNT(*) as c FROM jobs")[0]?.c as number) || 0;
        const activeJobs = (db.queryEntries("SELECT COUNT(*) as c FROM jobs WHERE is_active = 1")[0]?.c as number) || 0;
        const totalApps = (db.queryEntries("SELECT COUNT(*) as c FROM applications")[0]?.c as number) || 0;
        const newApps = (db.queryEntries("SELECT COUNT(*) as c FROM applications WHERE status = 'new'")[0]?.c as number) || 0;

        return new Response(`<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1.0"><title>Dashboard — MarqueLead Admin</title><style>*{margin:0;padding:0;box-sizing:border-box}body{font-family:system-ui,sans-serif;background:#050505;color:#F5F5F5;line-height:1.6}a{color:#C9A84C;text-decoration:none}a:hover{background:rgba(201,168,76,.05)}.topnav{background:#111;border-bottom:1px solid #2A2A2A;padding:0 20px;display:flex;align-items:center;height:56px;gap:24px;max-width:1400px;margin:0 auto}.topnav a{padding:16px 0;border-bottom:2px solid transparent;color:#888;font-weight:500;font-size:14px}.topnav a.active,.topnav a:hover{color:#C9A84C;border-bottom-color:#C9A84C}.logout{color:#f87171 !important;margin-left:auto}.layout{display:flex;min-height:calc(100vh - 56px)}.side{width:240px;background:#111;border-right:1px solid #2A2A2A;padding:20px 0;flex-shrink:0}.side a{display:block;padding:10px 24px;color:#888;font-size:14px}.side a.active{color:#C9A84C;background:rgba(201,168,76,.05)}.main{flex:1;padding:32px}.main h1{font-size:28px;font-weight:700;margin-bottom:8px}.sub{color:#888;margin-bottom:32px}.sg{display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:20px;margin-bottom:32px}.cd{background:#111;border:1px solid rgba(201,168,76,0.08);border-radius:12px;padding:24px}.cd .v{font-size:36px;font-weight:700;color:#C9A84C;margin-bottom:4px}.cd .l{font-size:14px;color:#888}.ql{display:grid;grid-template-columns:repeat(auto-fit,minmax(240px,1fr));gap:16px}.ql .cd{cursor:pointer;display:block;text-decoration:none;color:inherit}.ql .cd:hover{border-color:#C9A84C}.ql .cd h3{color:#C9A84C;margin-bottom:8px}.ql .cd p{color:#888;font-size:14px}</style></head><body><div style="background:#111;border-bottom:1px solid #2A2A2A"><div class="topnav"><a href="/admin/dashboard?token=`+sessionId+`" class="active">Dashboard</a><a href="/admin/jobs?token=`+sessionId+`">Jobs</a><a href="/admin/questions?token=`+sessionId+`">Questions</a><a href="/admin/applications?token=`+sessionId+`">Applications</a><a href="/admin/logout?token=`+sessionId+`" class="logout">Logout</a></div></div><div class="layout"><div class="side"><a href="/admin/dashboard?token=`+sessionId+`" class="active">Dashboard</a><a href="/admin/jobs?token=`+sessionId+`">Jobs</a><a href="/admin/questions?token=`+sessionId+`">Questions</a><a href="/admin/applications?token=`+sessionId+`">Applications</a></div><div class="main"><h1>Dashboard</h1><p class="sub">Welcome to the MarqueLead admin panel</p><div class="sg"><div class="cd"><div class="v">`+totalJobs+`</div><div class="l">Total Jobs</div></div><div class="cd"><div class="v">`+activeJobs+`</div><div class="l">Active Jobs</div></div><div class="cd"><div class="v">`+totalApps+`</div><div class="l">Total Applications</div></div><div class="cd"><div class="v">`+newApps+`</div><div class="l">New Applications</div></div></div><div class="ql"><a href="/admin/jobs?token=`+sessionId+`" class="cd"><h3>Manage Jobs</h3><p>Create, edit, and manage job listings</p></a><a href="/admin/questions?token=`+sessionId+`" class="cd"><h3>Manage Questions</h3><p>Customize application questions</p></a><a href="/admin/applications?token=`+sessionId+`" class="cd"><h3>View Applications</h3><p>Review, shortlist, and manage applicants</p></a></div></div></div></body></html>`, { status: 200, headers: { "Content-Type": "text/html; charset=utf-8" } });
      } catch (err) {
        console.error("[admin-login]", err);
        return json({ error: "Login failed" }, 500);
      }
    }

    // POST /admin — duplicate guard, render inline login or dashboard
    if (pathname === "/admin" && method === "POST") {
      const body = await req.text();
      const params = new URLSearchParams(body);
      const password = params.get("password") || "";
      const storedHash = getSetting("admin_password");
      if (!storedHash) return html(renderAdminLoginPage(false));
      const inputHash = await sha256(password);
      if (inputHash !== storedHash) return html(renderAdminLoginPage(true));
      const sessionId = createSession();
      return html(renderDashboardPage(sessionId));
    }

    // GET /admin — check token/cookie, render dashboard if logged in, else login page
    if (pathname === "/admin") {
      const sessionId = getSessionId(req);
      if (sessionId && validateSession(sessionId)) {
        return html(renderDashboardPage(sessionId));
      }
      const hasError = url.searchParams.get("error") === "1";
      return html(renderAdminLoginPage(hasError));
    }

    // Admin page handlers — all pass token through
    if (pathname === "/admin/dashboard") {
      const guard = await adminGuard(req);
      if (guard) return guard;
      const sessionId = getSessionId(req) || "";
      const pwChanged = url.searchParams.get("password_changed") === "1";
      const pwError = url.searchParams.get("password_error") === "1";
      return html(renderDashboardPage(sessionId, pwChanged, pwError));
    }

    if (pathname === "/admin/jobs") {
      const guard = await adminGuard(req);
      if (guard) return guard;
      const sessionId = getSessionId(req) || "";
      return html(renderAdminJobsPage(sessionId));
    }

    if (pathname === "/admin/questions") {
      const guard = await adminGuard(req);
      if (guard) return guard;
      const sessionId = getSessionId(req) || "";
      return html(renderAdminQuestionsPage(sessionId));
    }

    if (pathname === "/admin/applications") {
      const guard = await adminGuard(req);
      if (guard) return guard;
      const sessionId = getSessionId(req) || "";
      const jobFilter = url.searchParams.get("job") || undefined;
      const statusFilter = url.searchParams.get("status") || undefined;
      const apps = getApplications({ jobId: jobFilter, status: statusFilter });
      const jobs = getJobs();
      return html(renderAdminApplicationsPage(sessionId, apps, jobs));
    }

    const adminAppDetailMatch = pathname.match(/^\/admin\/applications\/([^\/]+)$/);
    if (adminAppDetailMatch) {
      const guard = await adminGuard(req);
      if (guard) return guard;
      const sessionId = getSessionId(req) || "";
      return html(renderAdminApplicationDetailPage(sessionId, adminAppDetailMatch[1]));
    }

    // GET /admin/logout — clear session by token or cookie, redirect to login
    if (pathname === "/admin/logout") {
      const token = url.searchParams.get("token");
      const cookie = getCookie(req, "ml_session");
      if (token) sessionStore.delete(token);
      if (cookie) sessionStore.delete(cookie);
      return new Response(null, { status: 302, headers: { "Location": "/admin" } });
    }

    // Public pages
    if (pathname === "/" || pathname === "/careers") {
      return html(renderCareersPage());
    }

    const jobDetailMatch = pathname.match(/^\/jobs\/([^\/]+)$/);
    if (jobDetailMatch) {
      return html(renderJobDetailPage(jobDetailMatch[1]));
    }

    const applyMatch = pathname.match(/^\/apply\/([^\/]+)$/);
    if (applyMatch) {
      const job = getJobBySlug(applyMatch[1]);
      if (!job) return redirect("/");
      return html(renderApplyPage(job));
    }

    return new Response("Not Found", { status: 404 });
  } catch (err) {
    console.error("[marquelead-careers] Error:", err);
    return json({ error: "Internal server error" }, 500);
  }
});
