<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>Hammer Head — Onboarding</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<style>
:root{--navy:#0f2038;--navy2:#1b3357;--steel:#2f5d8a;--accent:#3b82f6;--accent2:#6366f1;--ok:#16a34a;--warn:#d97706;--crit:#dc2626;--muted:#64748b;--bg:#f4f6f9;--card:#fff;--line:#e2e8f0;--text:#1e293b;}
*{box-sizing:border-box}
body{margin:0;font-family:'Inter',-apple-system,'Segoe UI',Roboto,Arial,sans-serif;background:linear-gradient(180deg,#f7f9fc 0%,#eef1f7 100%);color:var(--text);-webkit-font-smoothing:antialiased;}
header{background:linear-gradient(120deg,#0b1930 0%,#132a4d 55%,#1b3357 100%);color:#fff;padding:14px 24px;display:flex;align-items:center;gap:12px;flex-wrap:wrap;box-shadow:0 2px 14px rgba(3,10,22,.35);position:relative;z-index:5;}
#backToWorkspaceBtn,#docsNavBtn,#deletedNavBtn,#i9hrNavBtn{color:#eef4ff;border-color:rgba(255,255,255,0.55);font-size:13px;}
#backToWorkspaceBtn:hover,#docsNavBtn:hover,#deletedNavBtn:hover,#i9hrNavBtn:hover{background:rgba(255,255,255,0.14);}
header .logo{width:26px;height:26px;background:var(--accent);border-radius:6px;display:flex;align-items:center;justify-content:center;font-weight:800;transform:rotate(45deg);}
header .logo span{transform:rotate(-45deg);}
header .brand-logo-chip{background:#fff;border-radius:8px;padding:4px 10px;display:flex;align-items:center;box-shadow:0 1px 3px rgba(0,0,0,.25);}
header .brand-logo{height:26px;width:auto;display:block;}
header h1{font-size:15px;margin:0;letter-spacing:.3px;}
header .sub{font-size:11px;color:#9fb3cc;}
.modepill{margin-left:auto;font-size:11px;background:rgba(255,255,255,.08);border:1px solid rgba(255,255,255,.16);padding:5px 12px;border-radius:20px;backdrop-filter:blur(2px);}
.viewswitch{display:flex;gap:6px;background:#081527;padding:8px 24px;border-bottom:1px solid #16283f;flex-wrap:wrap;}
.viewswitch .lbl{font-size:11px;color:#546b86;align-self:center;margin-right:4px;}
.viewswitch button{background:rgba(255,255,255,.03);border:1px solid #24405f;color:#9fb3cc;padding:6px 13px;border-radius:7px;font-size:12px;cursor:pointer;transition:all .18s ease;}
.viewswitch button:hover{background:rgba(255,255,255,.08);color:#e2edff;border-color:#3a5c85;}
.viewswitch button.active{background:linear-gradient(135deg,var(--accent),var(--accent2));color:#fff;border-color:transparent;box-shadow:0 3px 10px -2px rgba(59,130,246,.5);}
.wrap{max-width:900px;margin:22px auto;padding:0 18px;}
.wrap.wide{max-width:1300px;}
.banner{background:#fff7ed;border:1px solid #fed7aa;color:#9a3412;padding:10px 14px;border-radius:10px;font-size:12px;margin-bottom:16px;box-shadow:0 1px 3px rgba(0,0,0,.03);}
.banner.info{background:linear-gradient(120deg,#eff6ff,#f0f7ff);border-color:#bfdbfe;color:#1e40af;}
.card{background:linear-gradient(160deg,#ffffff 0%,#fbfcfe 100%);border:1px solid var(--line);border-radius:14px;padding:22px 24px;margin-bottom:18px;box-shadow:0 1px 2px rgba(15,23,42,.03),0 8px 24px -12px rgba(15,23,42,.06);transition:box-shadow .25s ease;}
h2{font-size:18px;margin:0 0 3px;letter-spacing:.1px;} .muted{color:var(--muted);font-size:12.5px;}
label{display:block;font-size:12px;font-weight:600;margin:10px 0 4px;color:#334155;}
input,select,textarea{width:100%;padding:9px 11px;border:1px solid #cbd5e1;border-radius:8px;font-size:13px;font-family:inherit;background:#fff;transition:border-color .15s ease,box-shadow .15s ease;}
input:focus,select:focus{outline:none;border-color:var(--accent);box-shadow:0 0 0 3px rgba(59,130,246,.14);}
input[readonly]{background:#f1f5f9;}
.prefilled{background:#e5e7eb!important;border-color:#9ca3af!important;color:#374151;}
.fi-opt{background:#fef9c3!important;border-color:#fde047!important;}
.fi-req{background:#dcfce7!important;border-color:#22c55e!important;}
.req-choice{background:#dcfce7;border-left:3px solid #16a34a;padding:5px 9px;border-radius:5px;display:block;margin:5px 0;}
.opt-choice{background:#fef9c3;border-left:3px solid #eab308;padding:5px 9px;border-radius:5px;display:block;margin:5px 0;}
.legend-chip{display:inline-flex;align-items:center;gap:7px;font-size:12.5px;margin-right:18px;}
.legend-swatch{width:15px;height:15px;border-radius:4px;display:inline-block;border:1px solid rgba(0,0,0,.15);vertical-align:middle;}
.modal-overlay{position:fixed;inset:0;background:rgba(9,17,32,.6);backdrop-filter:blur(2px);z-index:100;display:flex;align-items:center;justify-content:center;padding:20px;}
.modal-box{background:#fff;border-radius:16px;padding:24px 26px;max-width:460px;box-shadow:0 24px 60px -12px rgba(2,8,23,.45),0 0 0 1px rgba(15,23,42,.04);}
.next-req-btn{position:fixed;bottom:76px;right:22px;z-index:56;box-shadow:0 8px 22px -4px rgba(37,99,235,.45);}
.legend-link{cursor:pointer;color:var(--accent);font-size:12px;text-decoration:underline;background:none;border:none;padding:0;}
.wizbar{max-width:900px;margin:0 auto 14px;padding:0 18px;}
.wizprog{height:8px;background:#e2e8f0;border-radius:6px;overflow:hidden;margin-bottom:6px;}
.wizprog-fill{height:100%;background:linear-gradient(90deg,var(--accent),var(--accent2));width:0;transition:width .3s;}
.wiznav{max-width:900px;margin:8px auto 40px;padding:12px 18px;display:flex;justify-content:space-between;gap:12px;position:sticky;bottom:0;background:linear-gradient(to top,var(--bg) 70%,transparent);}
.wiznav .btn{min-width:130px;}
.sig-tabs{display:flex;gap:8px;margin-bottom:10px;}
.sig-preview,.typed-sig{font-family:'Segoe Script','Brush Script MT',cursive;font-size:30px;color:var(--navy);}
.sig-preview{min-height:44px;padding:6px 2px;border-bottom:1px solid var(--line);margin-top:8px;display:none;}
.sign-card{border:2px solid #fdba74;background:#fffdf9;}
.sign-card.done{border-color:#86efac;background:#f2fdf5;}
.signed-box{background:#ecfdf5;border:1px solid #86efac;border-radius:8px;padding:10px 13px;font-size:13px;color:#065f46;}
.signed-box img{margin-top:6px;background:#fff;border:1px solid var(--line);border-radius:6px;padding:2px;}
.sig-apply-preview{margin:8px 0;}
.schedrow{display:flex;align-items:center;gap:10px;margin:5px 0;flex-wrap:wrap;}
.schedrow .schedday{display:flex;align-items:center;gap:6px;min-width:110px;font-weight:600;font-size:12.5px;margin:0;}
.schedrow .schedday input{width:auto;}
.schedrow input[type=time]{width:130px;}
.schedrow .schedto{color:var(--muted);font-size:12px;}
.schedrow.off input[type=time]{opacity:.4;}
.row{display:grid;grid-template-columns:1fr 1fr;gap:12px;}
.row3{display:grid;grid-template-columns:1fr 1fr 1fr;gap:12px;}
.row3-compact{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:12px;}
.btn{background:linear-gradient(135deg,var(--accent),var(--accent2));color:#fff;border:none;padding:9px 17px;border-radius:9px;font-size:13px;font-weight:600;cursor:pointer;box-shadow:0 2px 6px -1px rgba(59,130,246,.4);transition:transform .15s ease,box-shadow .15s ease,filter .15s ease;}
.btn:hover{filter:brightness(1.06);transform:translateY(-1px);box-shadow:0 6px 14px -3px rgba(59,130,246,.5);} .btn:active{transform:translateY(0);}
.btn.secondary{background:#e9edf3;color:#334155;box-shadow:none;} .btn.secondary:hover{background:#dde3ec;}
.btn.ghost{background:transparent;color:var(--steel);border:1px solid #cbd5e1;box-shadow:none;} .btn.ghost:hover{background:#f1f5f9;}
.btn.sm{padding:5px 11px;font-size:12px;}
.actions{display:flex;gap:10px;margin-top:20px;justify-content:space-between;flex-wrap:wrap;}
.badge{display:inline-block;padding:3px 10px;border-radius:20px;font-size:10.5px;font-weight:700;background:#e2e8f0;color:#475569;white-space:nowrap;letter-spacing:.2px;}
table{width:100%;border-collapse:collapse;font-size:12.5px;} th{text-align:left;color:var(--muted);font-size:10.5px;text-transform:uppercase;letter-spacing:.5px;padding:9px 8px;border-bottom:2px solid var(--line);background:#f8fafc;} td{padding:11px 8px;border-bottom:1px solid var(--line);}
table.doclist{table-layout:fixed;}
table.doclist td:first-child,table.doclist th:first-child{width:auto;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}
table.doclist td:last-child,table.doclist th:last-child{width:110px;}
tr{transition:background-color .12s ease;}
.doc{background:linear-gradient(160deg,#ffffff,#fbfcfe);border:1px solid var(--line);border-radius:12px;padding:18px 20px;margin-bottom:14px;box-shadow:0 6px 18px -12px rgba(15,23,42,.08);}
.doc>h3.dt{font-size:14px;color:var(--navy);border-bottom:2px solid var(--navy);padding-bottom:7px;margin:0 0 12px;}
.sh{font-weight:700;font-size:12px;color:var(--navy);margin:14px 0 8px;border-bottom:1px solid var(--line);padding-bottom:4px;text-transform:uppercase;letter-spacing:.4px;}
.sub{font-weight:700;font-size:11px;color:#555;margin:10px 0 6px;text-transform:uppercase;}
.pbox{margin:10px 0;} .pbox h4{font-size:12px;color:var(--steel);margin:0 0 3px;text-transform:uppercase;letter-spacing:.4px;} .pbox p{margin:0;font-size:13px;line-height:1.55;}
.notice{background:#f8fafc;border-left:3px solid var(--navy);padding:9px 13px;margin:11px 0;font-size:12.5px;line-height:1.5;font-style:italic;}
.infob,.i9-cert-box{background:linear-gradient(120deg,#eef4ff,#f2f7ff);border:1px solid #cfe0ff;padding:9px 13px;margin:10px 0;font-size:12px;line-height:1.5;border-radius:7px;}
.i9-panel{display:none;}
.bl{margin:8px 0;padding-left:22px;font-size:13px;line-height:1.55;}
.i9-section-header{font-weight:700;font-size:12px;color:var(--navy);margin:14px 0 8px;border-bottom:1px solid var(--line);padding-bottom:4px;}
.fld{display:inline-flex;flex-direction:column;margin:5px 14px 5px 0;vertical-align:top;min-width:210px;}
.fld label{font-size:10px;text-transform:uppercase;letter-spacing:.3px;color:var(--muted);margin:0 0 3px;font-weight:600;}
.fld .fi{min-width:200px;}
.ck{display:block;font-size:12.5px;margin:6px 0;font-weight:400;} .ck input{width:auto;margin-right:6px;} .ck label{display:inline-block;margin-right:14px;}
.rg label{font-size:12.5px;margin-right:14px;display:inline-block;font-weight:400;} .rg input{width:auto;}
.sigpad{border:2px solid #cbd5e1;border-radius:8px;background:#fff;width:100%;height:120px;display:block;touch-action:none;}
input[type=time]::-webkit-calendar-picker-indicator{display:none;-webkit-appearance:none;}
input[type=time]{-moz-appearance:textfield;}
.toast{position:fixed;bottom:22px;left:50%;transform:translateX(-50%);background:var(--navy);color:#fff;padding:11px 20px;border-radius:9px;font-size:13px;opacity:0;transition:.3s;pointer-events:none;z-index:60;max-width:90%;text-align:center;box-shadow:0 10px 24px -6px rgba(0,0,0,.4);}
.toast.show{opacity:1;} .hide{display:none;}
</style></head><body>
<header><span class="brand-logo-chip"><img src="/assets/img/hh_logo.png" alt="Hammer Head Security" class="brand-logo"></span><div class="sub" style="margin-left:2px;">Employee Onboarding</div><a id="backToWorkspaceBtn" href="/workspace" class="btn sm ghost" style="display:none;margin-left:12px;text-decoration:none;">&larr; Workspace</a><button id="docsNavBtn" class="btn sm ghost" style="display:none;margin-left:8px;" onclick="setView('forms')">📁 Documents</button><button id="deletedNavBtn" class="btn sm ghost" style="display:none;margin-left:8px;" onclick="setView('deleted')">🗑️ Deleted</button><button id="i9hrNavBtn" class="btn sm ghost" style="display:none;margin-left:8px;" onclick="setView('i9hr')">🪪 I-9 HR</button><div class="modepill" id="modePill" style="margin-left:auto;">Demo mode</div></header>
<?php if (!empty($notifications)): ?>
<div class="wrap" style="margin-bottom:0;">
  <?php foreach ($notifications as $n): ?>
    <div class="banner info" id="notif-<?= (int)$n['id'] ?>" style="display:flex;justify-content:space-between;align-items:center;">
      <span><strong><?= htmlspecialchars($n['title']) ?></strong> — <?= htmlspecialchars($n['message']) ?></span>
      <button class="btn sm ghost" onclick="onbDismissNotif(<?= (int)$n['id'] ?>)">Mark as read →</button>
    </div>
  <?php endforeach; ?>
</div>
<script>
function onbDismissNotif(id){
  fetch('/onboarding/notif-read', {method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify({id:id})})
    .then(()=>{ const el = document.getElementById('notif-'+id); if(el) el.remove(); });
}
</script>
<?php endif; ?>
<div class="wrap" id="wrapEl"><div id="legendBar" class="hide" style="margin-top:14px;padding:9px 13px;border:1px solid var(--line);border-radius:8px;font-size:12px;background:#fff;"><span style="background:#dcfce7;border:1px solid #22c55e;padding:2px 8px;border-radius:5px;font-weight:600;">Green = Mandatory</span> &nbsp; <span style="background:#fef9c3;border:1px solid #fde047;padding:2px 8px;border-radius:5px;font-weight:600;">Yellow = Optional</span></div><div id="app"></div></div><div class="toast" id="toast"></div>
<div id="hire-modal-backdrop" style="display:none;position:fixed;inset:0;z-index:1000;background:rgba(15,23,42,0.55);backdrop-filter:blur(3px);align-items:center;justify-content:center;padding:28px 16px;">
  <div id="hire-modal" style="background:#fff;border-radius:20px;width:100%;max-width:680px;max-height:85vh;box-shadow:0 24px 80px rgba(0,0,0,0.22);position:relative;display:flex;flex-direction:column;overflow:hidden;">
    <div style="display:flex;justify-content:space-between;align-items:center;padding:16px 24px 12px;border-bottom:1px solid var(--line);flex-shrink:0;">
      <h2 id="hire-modal-title" style="margin:0;font-size:17px;">New Hire</h2>
      <button type="button" onclick="closeHireModal()" style="background:none;border:none;cursor:pointer;font-size:22px;color:var(--muted);line-height:1;padding:4px 8px;border-radius:8px;">✕</button>
    </div>
    <div id="hire-modal-body" style="padding:14px 24px 20px;overflow-y:auto;overflow-x:hidden;flex:1;"></div>
  </div>
</div>
<script>
function openHireModal(title){
  document.getElementById('hire-modal-title').textContent=title||'New Hire';
  document.getElementById('hire-modal-backdrop').style.display='flex';
  document.body.style.overflow='hidden';
}
function closeHireModal(){
  document.getElementById('hire-modal-backdrop').style.display='none';
  document.getElementById('hire-modal-body').innerHTML='';
  document.body.style.overflow='';
}
</script>
<script>
/* ===== CONFIG: auto-filled by Apps Script when served via doGet(). ===== */
const APPS_SCRIPT_URL = "/onboarding/api";
/* location.search does not work here — HtmlService serves this page inside
   a sandboxed iframe whose own URL never contains the exec URL's query
   string. The server injects these values directly instead. */
const APPLICANT_TOKEN = "<?php echo htmlspecialchars($applicantToken ?? '', ENT_QUOTES); ?>";
const APPLICANT_PHASE = "<?php echo htmlspecialchars($applicantPhase ?? 'A', ENT_QUOTES); ?>";
const APPLICANT_HIRE = <?php echo $applicantHireJson ?? 'null'; ?>;
const SITES = <?php echo $sitesJson ?? '[]'; ?>;
const COMPANIES = {
  "Hammer Head Protection Inc": {ein:"45-4415633", stateTaxId:"3432707", address:"4551 S B St Ste A, Stockton, CA 95206"},
  "Hammer Head Security Service Inc": {ein:"86-2631618", stateTaxId:"4315972", address:"4551 S B St Ste A, Stockton, CA 95206"},
  "Hammer Head Security Inc": {ein:"61-1818820", stateTaxId:"3922058", address:"4551 S B St Ste A, Stockton, CA 95206"}
};

const FORMS = {"offer21b": {"title": "Form 21B — Employment Terms (Full-Time / Part-Time)", "body": "<div class=\"infob\">4551 South B Street, Stockton, CA 95206 · (877) 505-6463 · www.hammerheadsecurity.com</div><div class=\"offer-banner offer-ft\">📄 Form 21B — Employment Terms Acknowledgment (New Hire / Transfer / Status Change)</div><div class=\"sh\">Employee Information</div><div class=\"row\"><div class=\"fld\"><label>Employee Name</label><input type=\"text\" name=\"f[employee_name]\" class=\"fi\"></div><div class=\"fld\"><label>Phone Number</label><input type=\"text\" name=\"f[phone_number]\" class=\"fi\"></div><div class=\"fld\"><label>Email Address</label><input type=\"text\" name=\"f[email_address]\" class=\"fi\"></div><div class=\"fld\"><label>BSIS Guard Registration #</label><input type=\"text\" name=\"f[bsis_guard_card]\" class=\"fi\"></div><div class=\"fld\"><label>Guard Card Expiration</label><input type=\"text\" name=\"f[guard_card_expiry]\" class=\"fi\"></div><div class=\"fld\"><label>Firearms Permit</label><input type=\"text\" name=\"f[firearms_permit_status]\" class=\"fi\" readonly></div></div><div class=\"sh\">Position Offered</div><div class=\"row\"><div class=\"fld\"><label>Job Title</label><input type=\"text\" name=\"f[position]\" class=\"fi\" readonly></div><div class=\"fld\"><label>Employment Status</label><input type=\"text\" name=\"f[employment_status]\" class=\"fi\" readonly></div><div class=\"fld\"><label>Date of Hire</label><input type=\"text\" name=\"f[date_of_hire]\" class=\"fi\" readonly></div><div class=\"fld\"><label>Job Site</label><input type=\"text\" name=\"f[work_location_site]\" class=\"fi\" readonly></div></div><div class=\"notice\">Employment Classification: Non-Exempt, At-Will. Reporting To: Field Supervisor / Scheduling Manager. This document confirms the terms of employment for the above position with Hammer Head Security, whether as a new hire, transfer, or change in employment status. The Employee will be assigned to a designated post or client account and scheduled based on operational needs. Schedules may vary by location, client contract, or business necessity. Nothing in this agreement guarantees a fixed schedule, specific shift assignment, minimum number of hours, or permanent post location.</div><div class=\"sh\">At-Will Employment</div><div class=\"pbox\"><p>Employment with Hammer Head Security is at-will. Either the Employee or the Company may terminate employment at any time, with or without cause or notice, in accordance with California law. No manager or representative has authority to modify the at-will relationship except in a written agreement signed by Company ownership. Nothing in this document or in any Company policy, statement, or communication creates a contract of employment or guarantees employment for any specific duration.</p></div><div class=\"sh\">Work Schedule <span style=\"font-weight:400;text-transform:none;\">(set by HR — not required for On-Call / At-Will employees)</span></div><div class=\"pbox\"><p>Full-Time employees are generally scheduled 30–40 hours per week; Part-Time employees generally less than 30 hours per week, subject to operational needs. Employment status does not guarantee a specific number of hours. Schedules may include weekends, holidays, nights, or variable shifts. Employees are expected to report to all scheduled shifts on time.</p></div><div class=\"row3\"><div class=\"fld\"><label>Saturday</label><input type=\"text\" name=\"f[sched_sat]\" class=\"fi\" readonly></div><div class=\"fld\"><label>Sunday</label><input type=\"text\" name=\"f[sched_sun]\" class=\"fi\" readonly></div><div class=\"fld\"><label>Monday</label><input type=\"text\" name=\"f[sched_mon]\" class=\"fi\" readonly></div><div class=\"fld\"><label>Tuesday</label><input type=\"text\" name=\"f[sched_tue]\" class=\"fi\" readonly></div><div class=\"fld\"><label>Wednesday</label><input type=\"text\" name=\"f[sched_wed]\" class=\"fi\" readonly></div><div class=\"fld\"><label>Thursday</label><input type=\"text\" name=\"f[sched_thu]\" class=\"fi\" readonly></div><div class=\"fld\"><label>Friday</label><input type=\"text\" name=\"f[sched_fri]\" class=\"fi\" readonly></div></div><div class=\"notice\">Scheduled hours may vary from week to week based on operational needs and are not guaranteed. Failure to report for a scheduled shift without proper notice may result in disciplinary action, up to and including termination.</div><div class=\"sh\">Compensation</div><div class=\"row\"><div class=\"fld\"><label>Regular Rate of Pay ($ / hour)</label><input type=\"text\" name=\"f[pay_rate_amt]\" class=\"fi\" readonly></div><div class=\"fld\"><label>Paydays</label><input type=\"text\" name=\"f[pay_frequency]\" class=\"fi\" readonly></div></div><div class=\"pbox\"><p>Overtime (California law): 1.5× after 8 hours in a workday or 40 hours in a workweek; 2× after 12 hours in a workday; 1.5× for the first 8 hours on the 7th consecutive day worked; 2× after 8 hours on the 7th consecutive day. Paydays: Weekly, paid every Friday. No allowances, credits, or offsets are applied toward minimum wage.</p></div><div class=\"sh\">Job Assignments &amp; Transfers</div><div class=\"pbox\"><p>The Employee may be assigned to different client sites, posts, or locations as required by business needs. At the request of management, the Employee may be temporarily reassigned to another site and will be paid the approved rate for that assignment unless otherwise authorized in writing.</p></div><div class=\"sh\">Paid Sick Leave</div><div class=\"pbox\"><p>Employees will accrue and may use paid sick leave in accordance with the California Healthy Workplaces, Healthy Families Act and Company policy.</p></div><div class=\"sh\">Meal Periods, Rest Periods &amp; Wage Order 4 Compliance</div><ul class=\"bl\"><li>Uninterrupted, duty-free meal periods as required by law</li><li>Paid rest periods as required by law</li><li>Meal and rest period premium pay when legally required</li><li>On-duty meal periods only when legally permitted and agreed to in a separate written agreement, which may be revoked by the Employee at any time</li></ul><div class=\"sh\">Licensing &amp; Training Requirements</div><div class=\"pbox\"><p>Continued employment is contingent upon maintaining a valid BSIS Guard Registration, maintaining any required permits (including firearms permits, if applicable), and completing required training and compliance documentation. Failure to maintain required licensing or eligibility may result in removal from duty or termination.</p></div><div class=\"sh\">Policies &amp; Standards</div><div class=\"pbox\"><p>This agreement is intended to comply with all applicable California labor laws and BSIS regulations. In the event of a conflict, applicable law shall control. The Employee agrees to comply with all Company policies, including conduct and professionalism standards, uniform and appearance requirements, and safety procedures and client-specific post orders. The Company reserves the right to bypass progressive discipline and take immediate corrective action, up to and including termination, based on the severity of any violation, in accordance with applicable law.</p></div><div class=\"sh\">Arbitration Notice</div><div class=\"pbox\"><p>This job offer does not constitute an agreement to arbitrate. Any arbitration agreement, if applicable, will be provided in a separate document for review and voluntary execution in accordance with California law.</p></div><div class=\"notice\">Electronic Signature Acknowledgment: I agree that my electronic signature is legally equivalent to my handwritten signature under applicable federal and California law, including the ESIGN Act and the California Uniform Electronic Transactions Act (UETA). By signing electronically, I confirm that I have read, understood, and agreed to the terms of this document, and that this acknowledgment is binding and enforceable to the same extent as a physical signature. I understand that I may request a paper copy of this document at any time.</div><div class=\"sh\">Acknowledgment and Acceptance of Employment Terms <span class=\"req\">*</span></div><label class=\"ck\"><input type=\"checkbox\" name=\"f[offer_accept]\" required value=\"accept\"> I ACKNOWLEDGE AND ACCEPT THESE EMPLOYMENT TERMS</label>"}, "i9": {"title": "Form I-9 — Employment Eligibility Verification (USCIS)", "body": "\n    <div class=\"infob\">USCIS Form I-9 · OMB No. 1615-0047 · Expires 05/31/2027 · <strong>Employee completes Section 1. Rachel completes Section 2 within 3 business days of your first day.</strong></div>\n    \n    <div class=\"i9-section-header\">🟦 Section 1 — Employee Information and Attestation <span style=\"background:rgba(255,255,255,0.15);padding:2px 8px;border-radius:4px;font-size:10px\">You complete this</span></div>\n    <div class=\"i9-cert-box\">\n      <strong>USCIS Legal Attestation — Section 1</strong>\n      \"I am aware that federal law provides for imprisonment and/or fines for false statements, or the use of false documents, in connection with the completion of this form. I attest, under penalty of perjury, that this information is true and correct.\"\n    </div>\n    <div class=\"row\">\n      <div class=\"fld\"><label>Last Name (Family Name)</label><input type=\"text\" name=\"f[last_name_family_name]\" class=\"fi\" required></div> <div class=\"fld\"><label>First Name (Given Name)</label><input type=\"text\" name=\"f[first_name_given_name]\" class=\"fi\" required></div>\n      <div class=\"fld\"><label>Middle Initial (if any)</label><input type=\"text\" name=\"f[middle_initial_if_any]\" class=\"fi\"></div> <div class=\"fld\"><label>Other Last Names Used (if any)</label><input type=\"text\" name=\"f[other_last_names_used_if_any]\" class=\"fi\"></div>\n      <div class=\"fld\"><label>Address (Street Number and Name)</label><input type=\"text\" name=\"f[address_street_number_and_name]\" class=\"fi\" required></div>\n      <div class=\"fld\"><label>Apt. Number (if any)</label><input type=\"text\" name=\"f[apt_number_if_any]\" class=\"fi\"></div>\n      <div class=\"fld\"><label>City or Town</label><input type=\"text\" name=\"f[city_or_town]\" class=\"fi\" required></div> <div class=\"fld\"><label>State</label><input type=\"text\" name=\"f[state]\" class=\"fi\" required></div>\n      <div class=\"fld\"><label>ZIP Code</label><input type=\"text\" name=\"f[zip_code]\" class=\"fi\" required></div> <div class=\"fld\"><label>Date of Birth (mm/dd/yyyy)</label><input type=\"text\" name=\"f[date_of_birth_mm_dd_yyyy]\" class=\"fi\" data-mirror=\"dob\" required></div>\n      <div class=\"fld\"><label>U.S. Social Security Number</label><input type=\"text\" name=\"f[u_s_social_security_number]\" class=\"fi\" data-mirror=\"ssn\" required></div> <div class=\"fld\"><label>Email Address</label><input type=\"text\" name=\"f[email_address]\" class=\"fi\" required></div>\n <div class=\"fld\"><label>Telephone Number</label><input type=\"text\" name=\"f[phone_number]\" class=\"fi\" required></div>\n    </div>\n    \n    <div style=\"font-size:11px;font-weight:700;color:#555;margin-bottom:6px;text-transform:uppercase;margin-top:10px\">Citizenship / Immigration Status — check one <span class=\"tag-app\">Required</span></div>\n    <div class=\"rg\">\n      <label><input type=\"radio\" name=\"f[i9cit]\" required value=\"us\" onchange=\"i9Switch(this.value)\"> 1. A citizen of the United States</label>\n      <label><input type=\"radio\" name=\"f[i9cit]\" required value=\"natl\" onchange=\"i9Switch(this.value)\"> 2. A noncitizen national of the United States (See Instructions)</label>\n      <label><input type=\"radio\" name=\"f[i9cit]\" required value=\"lpr\" onchange=\"i9Switch(this.value)\"> 3. A lawful permanent resident — Enter USCIS or A-Number:</label>\n      <label><input type=\"radio\" name=\"f[i9cit]\" required value=\"alien\" onchange=\"i9Switch(this.value)\"> 4. An alien authorized to work — Authorization Expiration Date:</label>\n    </div>\n    <div class=\"i9-panel\" id=\"i9p-us\"><div class=\"infob\" style=\"margin:0\">✅ No additional fields required for U.S. Citizens in Section 1.</div></div>\n    <div class=\"i9-panel\" id=\"i9p-natl\"><div class=\"infob\" style=\"margin:0\">Noncitizen nationals — no additional number fields required in Section 1.</div></div>\n    <div class=\"i9-panel\" id=\"i9p-lpr\">\n      <div class=\"alertb\">🟢 <strong>Lawful Permanent Resident</strong> — Enter your USCIS A-Number below.</div>\n      <div class=\"row\">\n        <div class=\"f\"><label>USCIS A-Number / Alien Registration Number <span class=\"req\">*</span> <span class=\"tag-app\">Required</span></label><input type=\"text\" name=\"f[uscis_a_number_if_applicable]\" class=\"fapp fi\" placeholder=\"A-000000000\"></div>\n      </div>\n      <div class=\"i9-back-note\">🏢 <strong>Rachel</strong> will physically examine your Green Card and complete Section 2 (Step 4).</div>\n    </div>\n    <div class=\"i9-panel\" id=\"i9p-alien\">\n      <div class=\"alertb\">🛂 <strong>Alien Authorized to Work</strong> — Complete all fields that apply to you.</div>\n      <div class=\"row\">\n        <div class=\"f h\"><label>Work Authorization Expiration Date <span class=\"req\">*</span> <span class=\"tag-app\">Required</span></label><input type=\"date\" name=\"f[i9_exp_date]\" class=\"fapp fi\" placeholder=\"MM/DD/YYYY\"></div>\n        <div class=\"fld\"><label>USCIS A-Number (if applicable)</label><input type=\"text\" name=\"f[uscis_a_number_if_applicable]\" class=\"fi\"></div>\n        <div class=\"fld\"><label>Form I-94 Admission Number (if applicable)</label><input type=\"text\" name=\"f[form_i_94_admission_number_if_applicable]\" class=\"fi\"></div> <div class=\"fld\"><label>EAD Number / Form I-766 Number (if applicable)</label><input type=\"text\" name=\"f[ead_number_form_i_766_number_if_applicable]\" class=\"fi\"></div>\n        <div class=\"fld\"><label>Foreign Passport Number (if applicable)</label><input type=\"text\" name=\"f[foreign_passport_number_if_applicable]\" class=\"fi\"></div> <div class=\"fld\"><label>Country of Issuance (if passport used)</label><input type=\"text\" name=\"f[country_of_issuance_if_passport_used]\" class=\"fi\"></div>\n      </div>\n      <div class=\"i9-back-note\">🏢 <strong>Rachel</strong> will verify work authorization documents and complete Section 2 (Step 4) within 3 business days.</div>\n    </div>\n\n    <div class=\"i9-section-header\" style=\"margin-top:14px\">🟩 Section 2 — Employer Review and Verification <span style=\"background:rgba(255,255,255,0.15);padding:2px 8px;border-radius:4px;font-size:10px\">Rachel completes after you submit</span></div>\n    <div class=\"infob\"><strong>For HR Only:</strong> Section 2 will be completed by Rachel in Step 4 after you submit your package. She must physically examine original documents and sign within 3 business days of your first day of employment. See USCIS Form I-9 instructions for acceptable documents (List A or List B + List C).</div>\n    \n    <div class=\"i9-section-header\" style=\"margin-top:14px\">📋 Supplement A — Preparer / Translator Certification <span style=\"background:rgba(255,255,255,0.15);padding:2px 8px;border-radius:4px;font-size:10px\">Only if someone helped you fill Section 1</span></div>\n    <div class=\"notice\">Complete this section ONLY if a preparer or translator assisted you in completing Section 1. If you completed Section 1 yourself, leave blank.</div>\n    <div class=\"row\">\n      <div class=\"fld\"><label>Preparer/Translator Last Name</label><input type=\"text\" name=\"f[preparer_translator_last_name]\" class=\"fi\"></div> <div class=\"fld\"><label>Preparer/Translator First Name</label><input type=\"text\" name=\"f[preparer_translator_first_name]\" class=\"fi\"></div>\n      <div class=\"fld\"><label>Preparer/Translator Address</label><input type=\"text\" name=\"f[preparer_translator_address]\" class=\"fi\"></div> <div class=\"fld\"><label>City, State, ZIP</label><input type=\"text\" name=\"f[city_state_zip]\" class=\"fi\"></div>\n    </div>\n    <div class=\"notice\" style=\"margin-top:0\">If a preparer/translator assisted you, they must sign separately on the paper I-9 Supplement A. This digital form captures the information; the physical signature and full Supplement A must be retained per USCIS requirements.</div>\n  "}, "emp_info": {"title": "Employee Information Form — Personal & Licensing", "body": "<div class=\"row\"><div class=\"fld\"><label>Employee Name</label><input type=\"text\" name=\"f[employee_name]\" class=\"fi\" required></div> <div class=\"fld\"><label>Date of Birth</label><input type=\"text\" name=\"f[date_of_birth]\" class=\"fi\" data-mirror=\"dob\" required></div> <div class=\"fld\"><label>Address</label><input type=\"text\" name=\"f[address]\" class=\"fi\" required></div> <div class=\"fld\"><label>City</label><input type=\"text\" name=\"f[city]\" class=\"fi\" required></div> <div class=\"fld\"><label>State</label><input type=\"text\" name=\"f[state]\" class=\"fi\" required></div> <div class=\"fld\"><label>ZIP</label><input type=\"text\" name=\"f[zip]\" class=\"fi\" required></div> <div class=\"fld\"><label>Primary Phone</label><input type=\"text\" name=\"f[primary_phone]\" class=\"fi\" required></div> <div class=\"fld\"><label>Email Address</label><input type=\"text\" name=\"f[email_address]\" class=\"fi\" required></div> <div class=\"fld\"><label>BSIS Guard Card #</label><input type=\"text\" name=\"f[bsis_guard_card]\" class=\"fi\"></div> <div class=\"fld\"><label>Guard Card Expiry</label><input type=\"text\" name=\"f[guard_card_expiry]\" class=\"fi\"></div> <div class=\"fld\"><label>Driver's License #</label><input type=\"text\" name=\"f[s_license_e_dln_e_dln]\" class=\"fi\"></div> <div class=\"fld\"><label>DL Expiry</label><input type=\"text\" name=\"f[dl_expiry]\" class=\"fi\"></div></div><div style=\"font-weight:700;font-size:11px;color:var(--navy);margin:10px 0 6px;text-transform:uppercase\">Firearms Permit (if applicable) <span class=\"tag-app\">You fill</span></div><div class=\"rg\" style=\"margin-bottom:8px\"><label><input type=\"radio\" name=\"firearms_emp\" onchange=\"document.getElementById('firearms-fields-emp').style.display='block'\"> Yes — I hold a valid BSIS Firearms Permit</label><label><input type=\"radio\" name=\"firearms_emp\" onchange=\"document.getElementById('firearms-fields-emp').style.display='none'\" checked> No — Not applicable</label></div><div id=\"firearms-fields-emp\" style=\"display:none\"><div class=\"row\"><div class=\"fld\"><label>Firearms Permit #</label><input type=\"text\" name=\"f[firearms_permit]\" class=\"fi\"></div> <div class=\"fld\"><label>Permit Expiration Date</label><input type=\"text\" name=\"f[permit_expiration_date]\" class=\"fi\"></div> <div class=\"fld\"><label>Permit Issuing Authority</label><input type=\"text\" name=\"f[permit_issuing_authority]\" class=\"fi\"></div></div></div><div class=\"notice\">I certify that I am responsible for notifying the Company promptly if any of the information provided on this form changes. I understand that providing false, incomplete, or misleading information may result in disciplinary action, up to and including termination of employment, to the extent permitted by law.</div>"}, "direct_dep": {"title": "Direct Deposit Authorization", "body": "<div class=\"row\"><div class=\"fld\"><label>Employee Name</label><input type=\"text\" name=\"f[employee_name]\" class=\"fi\" required></div> <div class=\"fld\"><label>Employee ID</label><input type=\"text\" name=\"f[employee_id]\" class=\"fi\" required></div> <div class=\"fld\"><label>Position</label><input type=\"text\" name=\"f[position]\" class=\"fi\" required></div> <div class=\"fld\"><label>Date</label><input type=\"text\" name=\"f[date]\" class=\"fi\" required></div> <div class=\"fld\"><label>Phone</label><input type=\"text\" name=\"f[phone]\" class=\"fi\" required></div> <div class=\"fld\"><label>Email</label><input type=\"text\" name=\"f[email]\" class=\"fi\" required></div></div><div class=\"infob\"><strong>Direct Deposit Authorization</strong><br>I voluntarily authorize Hammer Head Security, and its payroll processing provider if applicable, to deposit my wages electronically into the financial institution listed below. I understand that participation in direct deposit is voluntary and that I may choose to receive my wages by another lawful method if I do not authorize direct deposit. I authorize Hammer Head Security to make corrections to my account in the event of a payroll processing error by initiating debit or credit entries as permitted by applicable banking regulations. This authorization will remain in effect until: I submit written notice requesting cancellation or modification of this authorization; or my employment with Hammer Head Security ends.</div><div style=\"font-size:11px;font-weight:700;color:var(--navy);margin:10px 0 6px;text-transform:uppercase\">Enroll in Direct Deposit? <span class=\"req\">*</span> <span class=\"tag-app\">You fill</span></div><div class=\"rg\"><label><input type=\"radio\" name=\"f[dd_enroll]\" required value=\"yes\" onchange=\"ddToggle(this.value)\"> Yes — deposit my pay to my bank account</label><label><input type=\"radio\" name=\"f[dd_enroll]\" required value=\"no\" onchange=\"ddToggle(this.value)\"> No — I will receive pay another lawful way</label></div><div style=\"font-size:11px;font-weight:700;color:var(--navy);margin:10px 0 6px;text-transform:uppercase\">Account Type <span class=\"req\">*</span> <span class=\"tag-app\">You fill</span></div><div class=\"rg\"><label><input type=\"radio\" name=\"f[accttype]\" required value=\"checking\" > Checking</label><label><input type=\"radio\" name=\"f[accttype]\" required value=\"savings\" > Savings</label></div><div class=\"row\" style=\"margin-top:10px\"><div class=\"fld\"><label>Bank Name</label><input type=\"text\" name=\"f[bank_name]\" class=\"fi\" required></div> <div class=\"fld\"><label>Routing Number</label><input type=\"text\" name=\"f[routing_number]\" class=\"fi\" required></div> <div class=\"fld\"><label>Account Number</label><input type=\"text\" name=\"f[account_number]\" class=\"fi\" required></div></div><div class=\"notice\" style=\"margin-top:8px\">I agree to notify Hammer Head Security immediately if my banking information changes. Providing incorrect banking information may delay payment processing.</div>"}, "bsis_lic": {"title": "BSIS Licensing & Compliance Acknowledgment", "body": "<div class=\"row\"><div class=\"fld\"><label>Employee Name</label><input type=\"text\" name=\"f[employee_name]\" class=\"fi\" required></div> <div class=\"fld\"><label>Employee ID</label><input type=\"text\" name=\"f[employee_id]\" class=\"fi\" required></div> <div class=\"fld\"><label>Position</label><input type=\"text\" name=\"f[position]\" class=\"fi\" required></div> <div class=\"fld\"><label>Date</label><input type=\"text\" name=\"f[date]\" class=\"fi\" required></div></div><div class=\"pbox\"><h4>1. Guard Registration Requirement</h4><p>I understand that I must possess and maintain a valid and active BSIS Guard Registration (\"Guard Card\") at all times while employed in a security capacity. I am strictly prohibited from performing any security duties without a valid and active Guard Card. There are no exceptions, including pending renewals or applications. Failure to maintain a valid Guard Card may result in immediate removal from duty, suspension, or termination of employment.</p></div><div class=\"pbox\"><h4>2. Training Requirements</h4><p>I understand that BSIS requires completion of mandatory training, including: Power to Arrest Training prior to assignment; completion of the initial 32 hours of training within required timeframes; and ongoing continuing education as required by BSIS. Failure to complete required training within mandated timeframes may result in removal from assignments or termination.</p></div><div class=\"pbox\"><h4>3. License Status Reporting</h4><p>I agree to immediately notify Hammer Head Security if: my Guard Card expires; my license is suspended, revoked, or restricted; or I am arrested, charged, or convicted of any offense that may impact my eligibility under BSIS regulations. Failure to report such changes may result in disciplinary action, up to and including termination.</p></div><div class=\"pbox\"><h4>4. Professional Conduct & Compliance</h4><p>While employed, I agree to: comply with all applicable BSIS laws and regulations; maintain professional conduct while on duty and in uniform; and follow all Company policies, procedures, and client post orders.</p></div><div class=\"pbox\"><h4>5. License Verification Authorization</h4><p>I authorize Hammer Head Security to: verify my BSIS Guard Registration and any related permits; and conduct periodic or ongoing checks of my license status through the California Department of Consumer Affairs or other official sources.</p></div><div class=\"pbox\"><h4>6. Firearm Permit Requirement (If Applicable)</h4><p>If assigned to an armed position, I understand that I must possess and maintain a valid BSIS Firearm Permit and comply with all applicable training and qualification requirements. I understand that I may not perform armed duties without a valid and active firearm permit.</p></div><div class=\"pbox\"><h4>7. Condition of Employment</h4><p>I understand that compliance with BSIS licensing, training, and regulatory requirements is a condition of my employment. Failure to meet or maintain these requirements may result in removal from duty or termination, to the extent permitted by law.</p></div><div class=\"notice\">I certify that I have read, understand, and agree to comply with the requirements outlined in this acknowledgment. I confirm that this information was provided to me during orientation and explained by the Company.</div>"}, "bsis_tr": {"title": "BSIS Training Compliance Acknowledgment", "body": "<div class=\"row\"><div class=\"fld\"><label>Employee Name</label><input type=\"text\" name=\"f[employee_name]\" class=\"fi\" required></div> <div class=\"fld\"><label>Employee ID</label><input type=\"text\" name=\"f[employee_id]\" class=\"fi\" required></div> <div class=\"fld\"><label>Position</label><input type=\"text\" name=\"f[position]\" class=\"fi\" required></div> <div class=\"fld\"><label>Date</label><input type=\"text\" name=\"f[date]\" class=\"fi\" required></div></div><div class=\"pbox\"><h4>1. Acknowledgment of Legal Training Requirements</h4><p>I understand that, under the California Bureau of Security and Investigative Services (BSIS) regulations, including applicable provisions of the California Business and Professions Code and Title 16 of the California Code of Regulations, I am required to complete mandatory training as a condition of employment as a security officer.</p></div><div class=\"pbox\"><h4>2. Required Training and Timeframes</h4><p>I understand and agree that I must complete the following: Powers to Arrest Training prior to assignment; 16 hours within the first 30 days; additional 16 hours within 6 months; and continuing education as required.</p></div><div class=\"pbox\"><h4>3. Strict Compliance with Training Deadlines</h4><p>I understand that: I may not continue working beyond BSIS-allowed timeframes if required training is incomplete; and I will be removed from duty immediately if I fail to meet BSIS-required training deadlines or if my training status cannot be verified.</p></div><div class=\"pbox\"><h4>4. No Assignment Without Required Training</h4><p>I understand that I will not be assigned to any post unless required training (including Powers to Arrest) has been completed and verified by the Company.</p></div><div class=\"pbox\"><h4>5. Employee Responsibility</h4><p>I understand that I am personally responsible for completing all required training within mandated timeframes. Failure to do so may result in: removal from assignments, suspension, or termination of employment.</p></div><div class=\"pbox\"><h4>6. Training Verification & Recordkeeping Authorization</h4><p>I authorize Hammer Head Security to: verify my training completion; maintain records of my training certifications; and provide such records to regulatory agencies, auditors, or clients as required for compliance purposes.</p></div><div class=\"notice\">I certify that I have read, understand, and agree to comply with the requirements outlined above. I confirm that this information was provided to me during orientation and explained by the Company.</div>"}, "safety_ob": {"title": "Employee Safety Onboarding Acknowledgment", "body": "\n    <div class=\"infob\">Form: <strong>SAFETY-OB-001</strong> · Rev. July 1, 2025 · Cal. Labor Code §6401.9 / Cal/OSHA Title 8 §3203 & §3395/3396 · Retain 5 years</div><div class=\"infob\"><strong>Hammer Head Security</strong> · 4551 South B Street, Stockton, CA 95206 · 209-227-6566</div>\n    <div class=\"row\"><div class=\"fld\"><label>Employee Name</label><input type=\"text\" name=\"f[employee_name]\" class=\"fi\" required></div> <div class=\"fld\"><label>Employee ID</label><input type=\"text\" name=\"f[employee_id]\" class=\"fi\" required></div> <div class=\"fld\"><label>Job Title</label><input type=\"text\" name=\"f[job_title]\" class=\"fi\" required></div> <div class=\"fld\"><label>Work Location / Site</label><input type=\"text\" name=\"f[work_location_site]\" class=\"fi\" required></div> <div class=\"fld\"><label>Start Date</label><input type=\"text\" name=\"f[start_date]\" class=\"fi\" required></div></div>\n    <div class=\"row\">\n      <div class=\"f h\"><label>Direct Supervisor <span class=\"tag-hr\">HR</span></label><input type=\"text\" class=\"fhr\" value=\"\" readonly></div>\n      <div class=\"f h\"><label>HR Coordinator <span class=\"tag-hr\">HR</span></label><input type=\"text\" class=\"fhr\" value=\"\" readonly></div>\n    </div>\n    <div style=\"font-size:11px;font-weight:700;color:#555;margin:8px 0 6px;text-transform:uppercase\">Work Environment <span class=\"tag-app\">Check all that apply</span></div>\n    <div style=\"display:flex;gap:12px;flex-wrap:wrap;margin-bottom:14px\">\n      <label class=\"ck\"><input type=\"checkbox\" checked> Outdoor work</label>\n      <label class=\"ck\"><input type=\"checkbox\" checked> Indoor work</label>\n      <label class=\"ck\"><input type=\"checkbox\"> Both</label>\n    </div>\n\n    <div class=\"i9-section-header\">1. Workplace Violence Prevention Plan (WVPP) — Cal. Labor Code §6401.9 / SB 553</div>\n    <div class=\"pbox\"><h4>WVPP Acknowledgment</h4><p>I have received access to the company's WVPP and understand its requirements. I acknowledge that the WVPP is accessible to me at all times upon request and that this is my initial onboarding training. Annual refresher training will be documented on a separate form.</p></div>\n    <label class=\"ck\"><input type=\"checkbox\" checked required> I understand the definitions and four types of workplace violence (Type I–IV).</label>\n    <label class=\"ck\"><input type=\"checkbox\" checked required> I know how to report workplace violence incidents, threats, or concerning behavior to my supervisor.</label>\n    <label class=\"ck\"><input type=\"checkbox\" checked required> I am aware of the Violent Incident Log and my right to review it (retained 5 years).</label>\n    <label class=\"ck\"><input type=\"checkbox\" checked required> I understand that retaliation for reporting workplace violence is prohibited under Labor Code §6310.</label>\n    <label class=\"ck\"><input type=\"checkbox\" checked required> I know the emergency response procedures for a violent incident at this worksite.</label>\n    <div class=\"row\" style=\"margin-top:10px\">\n      <div class=\"f h\"><label>WVPP Effective Date <span class=\"tag-hr\">HR fills</span></label><input type=\"text\" class=\"fhr\" placeholder=\"e.g. July 1, 2025\"></div>\n      <div class=\"f h\"><label>WVPP Version No. <span class=\"tag-hr\">HR fills</span></label><input type=\"text\" class=\"fhr\" placeholder=\"e.g. v1.0\"></div>\n    </div>\n\n    <div class=\"i9-section-header\" style=\"margin-top:14px\">2. Heat Illness Prevention — Cal/OSHA Title 8 §3395 (Outdoor) / §3396 (Indoor, eff. June 2024)</div>\n    <div class=\"pbox\"><h4>Heat Illness Prevention Acknowledgment</h4><p>I have received training on heat illness prevention applicable to my work environment. I understand that this is my initial onboarding training and that annual refresher training will be documented separately.</p></div>\n    <label class=\"ck\"><input type=\"checkbox\" checked required> <strong>Water:</strong> I am entitled to at least 1 quart/hour of cool, clean, fresh drinking water at no cost.</label>\n    <label class=\"ck\"><input type=\"checkbox\" checked required> <strong>Shade:</strong> I may access shade at any time and take a minimum 5-minute cool-down rest — this cannot be denied.</label>\n    <label class=\"ck\"><input type=\"checkbox\" checked required> <strong>Temps:</strong> Shade required ≥80°F (outdoor); high-heat procedures required ≥95°F outdoor / 87°F indoor.</label>\n    <label class=\"ck\"><input type=\"checkbox\" checked required> <strong>Symptoms:</strong> I can identify signs of heat cramps, heat exhaustion, and heat stroke and know to call 911 for heat stroke.</label>\n    <label class=\"ck\"><input type=\"checkbox\" checked required> <strong>Acclimatization:</strong> I understand the schedule for my first 14 days working in heat — I will follow it and report any symptoms.</label>\n    <label class=\"ck\"><input type=\"checkbox\" checked required> <strong>Buddy System:</strong> I will monitor coworkers for symptoms and report to my supervisor immediately if I feel unwell.</label>\n    <div class=\"row\" style=\"margin-top:10px\">\n      <div class=\"fld\"><label>Training Date <span class=\"tag-app\">Auto: date signed</span></label><input type=\"date\" name=\"f[training_date]\" class=\"fi\" data-today=\"1\"></div>\n      <div class=\"f h\"><label>Trainer Name <span class=\"tag-hr\">HR fills</span></label><input type=\"text\" class=\"fhr\" value=\"\" placeholder=\"Trainer name\"></div>\n    </div>\n\n    <div class=\"i9-section-header\" style=\"margin-top:14px\">3. Injury & Illness Prevention Program (IIPP) — Cal/OSHA Title 8, §3203</div>\n    <div class=\"pbox\"><h4>IIPP Acknowledgment</h4><p>I have received access to the company's IIPP and completed the safety orientation covering the topics below. I understand that the IIPP is available for review at any time upon request.</p></div>\n    <label class=\"ck\"><input type=\"checkbox\" checked required> I will follow all safety rules, safe work practices, and PPE requirements for my job.</label>\n    <label class=\"ck\"><input type=\"checkbox\" checked required> I will immediately report ALL injuries, illnesses, near-misses, and unsafe conditions to my supervisor.</label>\n    <label class=\"ck\"><input type=\"checkbox\" checked required> <strong>HazCom / GHS:</strong> I have been informed of chemicals I may encounter, how to read SDS, and where SDS are located.</label>\n    <label class=\"ck\"><input type=\"checkbox\" checked required> I understand the emergency action plan, evacuation routes, and assembly points for this worksite.</label>\n    <label class=\"ck\"><input type=\"checkbox\" checked required> <strong>Workers' Comp:</strong> I understand my right to file a claim and that retaliation for doing so is unlawful under Labor Code §132a.</label>\n    <label class=\"ck\"><input type=\"checkbox\" checked required> I understand that safety violations may result in disciplinary action up to and including termination.</label>\n    <div class=\"row\" style=\"margin-top:10px\">\n      <div class=\"fld\"><label>Orientation Date <span class=\"tag-app\">Auto: date signed</span></label><input type=\"date\" name=\"f[orientation_date]\" class=\"fi\" data-today=\"1\" id=\"safety_orient_date\"></div>\n      <div class=\"f h\"><label>Safety Officer / Trainer <span class=\"tag-hr\">HR fills</span></label><input type=\"text\" class=\"fhr\" value=\"\"></div>\n      <div class=\"f\"><label>Hazardous Materials / Substances Applicable to Assignment <span class=\"tag-hr\">HR fills</span></label><input type=\"text\" class=\"fhr\" placeholder=\"e.g. OC spray, first aid supplies, cleaning agents at post\" value=\"First aid kit supplies, post-specific cleaning materials\"></div>\n      <div class=\"f\"><label>SDS Location <span class=\"tag-hr\">HR fills</span></label><input type=\"text\" class=\"fhr\" value=\"Hammer Head Security — 4551 South B Street, Stockton, CA 95206 / Company HR Portal\"></div>\n    </div>\n\n    <div class=\"pbox red\" style=\"margin-top:12px\"><h4>Employee Rights & Anti-Retaliation — Cal/OSHA (Labor Code §6310)</h4><p>All employees have the right to report unsafe working conditions, workplace hazards, or safety violations without fear of retaliation. Complaints may be filed confidentially with Cal/OSHA at <strong>1-800-963-9424</strong> or online at <strong>dir.ca.gov/dosh</strong>. Hammer Head Security strictly prohibits retaliation of any kind against any employee who reports a safety concern, files a complaint, or exercises any right under California labor law. Violations of this policy will result in disciplinary action up to and including termination.</p></div>\n    <div class=\"notice\">By signing, I confirm that: (1) I have received onboarding training on all three programs listed above; (2) I have had the opportunity to ask questions; (3) I understand my responsibilities and rights; and (4) I agree to comply with all company safety policies. This form does not constitute a contract of employment or alter my at-will employment status.</div>\n    <div class=\"infob\" style=\"margin-top:8px\"><strong>Supervisor / HR Attestation:</strong> I certify that the above employee received onboarding training on all programs documented on this form. HR Coordinator: <strong>—</strong> · Orientation By: <strong>—</strong></div>\n    "}, "meal1": {"title": "California Meal & Rest Break Policy Acknowledgment", "body": "<div class=\"row\"><div class=\"fld\"><label>Employee Name</label><input type=\"text\" name=\"f[employee_name]\" class=\"fi\" required></div> <div class=\"fld\"><label>Employee ID</label><input type=\"text\" name=\"f[employee_id]\" class=\"fi\" required></div> <div class=\"fld\"><label>Position</label><input type=\"text\" name=\"f[position]\" class=\"fi\" required></div> <div class=\"fld\"><label>Date</label><input type=\"text\" name=\"f[date]\" class=\"fi\" required></div></div><div class=\"pbox\"><h4>Meal Periods</h4><p>Employees working more than five (5) hours in a workday are entitled to an uninterrupted, duty-free 30-minute meal period that must begin before the end of the fifth (5th) hour of work. Employees working more than ten (10) hours in a workday are entitled to a second meal period in accordance with California law. Meal periods must be: duty-free, uninterrupted, and at least 30 minutes. Employees are relieved of all duty during off-duty meal periods and are free to leave the premises subject to site restrictions.</p></div><div class=\"pbox\"><h4>On-Duty Meal Periods</h4><p>When the nature of the work prevents an employee from being fully relieved of all duties, California law permits an on-duty meal period only if a voluntary written agreement is entered into between the employee and Hammer Head Security. The Company does not require, coerce, or pressure employees to waive or skip meal periods. Entering into an on-duty meal period agreement is voluntary and not a condition of employment.</p></div><div class=\"pbox\"><h4>Rest Breaks</h4><p>Employees are entitled to one paid ten (10) minute rest break for every four (4) hours worked or major fraction thereof. Rest breaks must be: duty-free, uninterrupted, and free from work responsibilities. Employees are not required to remain on-call or perform any work duties during rest breaks.</p></div><div class=\"pbox\"><h4>Timekeeping and Off-the-Clock Work</h4><p>Hammer Head Security strictly prohibits off-the-clock work. Employees must: accurately record all time worked; record meal periods when required; and not perform any work before clocking in or after clocking out.</p></div><div class=\"pbox\"><h4>Reporting Requirement</h4><p>Employees must immediately notify a supervisor, dispatch, SOC, or management if they are unable to take a compliant meal or rest break. Reporting a missed, delayed, or interrupted break will not result in discipline. Hammer Head Security strictly prohibits retaliation against any employee who reports missed, delayed, interrupted, or shortened meal or rest breaks.</p></div><div class=\"pbox\"><h4>Premium Pay</h4><p>Premium pay is provided as a legal remedy when a compliant meal or rest break is not provided and does not excuse or replace the Company's obligation to provide compliant meal and rest breaks in accordance with California law.</p></div><div class=\"notice\">I acknowledge that I have received, read, and understand Hammer Head Security\\'s Meal & Rest Break Policy. I am authorized and permitted to take all legally required meal periods and rest breaks.</div>"}, "meal2": {"title": "Meal & Rest Break Compliance Policy — Signed Copy", "body": "<div class=\"row\"><div class=\"fld\"><label>Employee Name</label><input type=\"text\" name=\"f[employee_name]\" class=\"fi\" required></div> <div class=\"fld\"><label>Employee ID</label><input type=\"text\" name=\"f[employee_id]\" class=\"fi\" required></div> <div class=\"fld\"><label>Position</label><input type=\"text\" name=\"f[position]\" class=\"fi\" required></div> <div class=\"fld\"><label>Date</label><input type=\"text\" name=\"f[date]\" class=\"fi\" required></div></div><div class=\"pbox\"><h4>Break Monitoring and Documentation</h4><p>Hammer Head Security utilizes scheduling, dispatch, and/or SOC systems to support compliance with meal period timing requirements. The use of such systems is intended to: assist employees in taking timely meal periods; provide reminders when appropriate; and document communication and compliance efforts. These systems are support tools only and do not replace the Company's obligation to provide compliant breaks or the employee's responsibility to take and report breaks.</p></div><div class=\"pbox\"><h4>Reporting Requirement</h4><p>Employees must immediately notify a supervisor, dispatch, SOC, or management if they are unable to take a compliant meal or rest break. Failure to report may limit the Company's ability to address the issue. Employees should report any missed, delayed, interrupted, or shortened meal or rest break as soon as reasonably possible, and preferably within the same workday or pay period. Reporting a missed, delayed, or interrupted break will not result in discipline.</p></div><div class=\"pbox\"><h4>Premium Pay</h4><p>Premium pay is provided as a remedy when the Company fails to provide a compliant meal or rest break in accordance with California law. Premium pay will be provided when a compliant meal or rest break is not provided, regardless of whether the employee reports the issue at the time.</p></div><div class=\"pbox\"><h4>Anti-Retaliation</h4><p>Hammer Head Security strictly prohibits retaliation against any employee who reports missed breaks, interrupted breaks, delayed breaks, or shortened breaks. The Company will investigate all reports and take appropriate corrective action.</p></div><div class=\"notice\">I acknowledge that: this policy has been provided to me and reviewed with me during orientation; I have had the opportunity to ask questions and fully understand its terms; I am authorized and permitted to take all legally required meal periods and rest breaks; and meal periods must begin before the end of the 5th hour of work unless a lawful exception applies.</div><div class=\"fld\"><label>Employer Representative</label><input type=\"text\" name=\"f[employer_representative]\" class=\"fi\"></div>"}, "on_duty": {"title": "On-Duty Meal Period Agreement", "body": "<div class=\"row\"><div class=\"fld\"><label>Employee Name</label><input type=\"text\" name=\"f[employee_name]\" class=\"fi\" required></div> <div class=\"fld\"><label>Employee ID</label><input type=\"text\" name=\"f[employee_id]\" class=\"fi\" required></div> <div class=\"fld\"><label>Position</label><input type=\"text\" name=\"f[position]\" class=\"fi\" required></div> <div class=\"fld\"><label>Date</label><input type=\"text\" name=\"f[date]\" class=\"fi\" required></div></div><div class=\"notice\"><strong>Voluntary — NOT a condition of employment.</strong> This agreement will only be used when the nature of the work genuinely prevents relief from duty and not for reasons of convenience, staffing limitations, or scheduling preferences.</div><div class=\"pbox\"><h4>Voluntary Agreement</h4><p>I voluntarily agree to take an on-duty meal period when I cannot be fully relieved of all duties due to operational requirements. I understand that I am not required to enter into this agreement as a condition of employment and that I may decline to sign this agreement. I understand that I have been given the opportunity to ask questions about this agreement before signing.</p></div><div class=\"pbox\"><h4>Paid Meal Period</h4><p>I understand that any on-duty meal period will be paid and counted as hours worked. I understand that during an on-duty meal period, I will remain on duty and may be required to perform work as needed.</p></div><div class=\"pbox\"><h4>Opportunity to Eat</h4><p>I will be provided a reasonable opportunity to take and consume a meal while on duty.</p></div><div class=\"pbox\"><h4>Right to Revoke</h4><p>I understand that I may revoke this agreement at any time by providing written notice to the Company. Any revocation will apply prospectively and will not affect previously worked shifts.</p></div><div class=\"pbox\"><h4>Alternative Meal Period</h4><p>If operational conditions allow, Hammer Head Security Inc. will provide a duty-free, off-duty meal period instead.</p></div><div class=\"pbox\"><h4>No Waiver of Rights</h4><p>This agreement does not waive any rights under California law.</p></div><div class=\"notice\">I acknowledge that I have read and understand this agreement and that entering into it is voluntary.</div><div class=\"fld\"><label>Employer Representative</label><input type=\"text\" name=\"f[employer_representative]\" class=\"fi\"></div>"}, "meal_wv": {"title": "Meal Period Waiver Agreement", "body": "<div class=\"row\"><div class=\"fld\"><label>Employee Name</label><input type=\"text\" name=\"f[employee_name]\" class=\"fi\" required></div> <div class=\"fld\"><label>Employee ID</label><input type=\"text\" name=\"f[employee_id]\" class=\"fi\" required></div> <div class=\"fld\"><label>Position</label><input type=\"text\" name=\"f[position]\" class=\"fi\" required></div> <div class=\"fld\"><label>Date</label><input type=\"text\" name=\"f[date]\" class=\"fi\" required></div></div><div class=\"pbox\"><h4>First Meal Period Waiver (Shifts ≤ 6 Hours Only)</h4><p>Under California Labor Code §512, employees working more than five (5) hours are entitled to a meal period. However, when the total work period does not exceed six (6) hours, the meal period may be voluntarily waived by mutual written consent between the employee and Hammer Head Security. I voluntarily agree to waive my 30-minute meal period on workdays where my total shift does not exceed six (6) hours. I understand that I am not required to enter into this agreement as a condition of employment. This agreement is entered into voluntarily and may be revoked by the employee at any time in writing.</p></div><div class=\"pbox\"><h4>Second Meal Period Waiver (Shifts ≤ 12 Hours Only)</h4><p>Under California Labor Code §512, employees working more than ten (10) hours are entitled to a second meal period. However, when the total work period does not exceed twelve (12) hours, the second meal period may be voluntarily waived by mutual written consent between the employee and Hammer Head Security only if the first meal period was taken and not waived. I voluntarily agree to waive my second 30-minute meal period on workdays where my total shift does not exceed twelve (12) hours, provided that I have taken my first meal period. This waiver will not apply on any day where my total work period exceeds twelve (12) hours. I understand that I am not required to enter into this agreement as a condition of employment. This agreement is entered into voluntarily and may be revoked by the employee at any time in writing.</p></div><div class=\"notice\">I understand that: the first meal period waiver applies only to shifts of six (6) hours or less; the second meal period waiver applies only to shifts of no more than twelve (12) hours and only if the first meal period is taken; these waivers are voluntary; and I may revoke either waiver at any time by providing written notice to Hammer Head Security, and such revocation will apply prospectively only.</div><div class=\"fld\"><label>Employer Representative</label><input type=\"text\" name=\"f[employer_representative]\" class=\"fi\"></div>"}, "probation": {"title": "90-Day Introductory (Probationary) Period Acknowledgment", "body": "<div class=\"row\"><div class=\"fld\"><label>Employee Name</label><input type=\"text\" name=\"f[employee_name]\" class=\"fi\" required></div> <div class=\"fld\"><label>Employee ID</label><input type=\"text\" name=\"f[employee_id]\" class=\"fi\" required></div> <div class=\"fld\"><label>Position</label><input type=\"text\" name=\"f[position]\" class=\"fi\" required></div> <div class=\"fld\"><label>Date of Hire</label><input type=\"text\" name=\"f[date_of_hire]\" class=\"fi\" required></div></div><div class=\"pbox\"><h4>Purpose of Introductory Period</h4><p>I understand that the first ninety (90) days of employment constitute an introductory (Introductory) period. This period allows the Company to evaluate my: job performance; reliability and attendance; compliance with company policies and procedures; ability to safely perform assigned duties; and professional conduct with clients, the public, and coworkers. The introductory period does not guarantee employment for any specific duration, and employment may be terminated at any time during or after this period, consistent with at-will employment.</p></div><div class=\"pbox\"><h4>At-Will Employment</h4><p>I understand that my employment with Hammer Head Security is at-will, meaning employment may be terminated by me or the Company at any time, with or without cause or notice, subject to applicable California law. Nothing in this agreement alters or modifies my at-will employment status.</p></div><div class=\"pbox\"><h4>Performance Expectations</h4><p>During the introductory period, I am expected to: maintain a valid BSIS Guard Registration and all required permits at all times; follow all post orders, company policies, and client directives; comply with all Cal/OSHA safety requirements, including reporting hazards, injuries, and unsafe conditions immediately; maintain professional conduct, punctuality, and proper uniform standards; and perform all duties safely and effectively.</p></div><div class=\"pbox\"><h4>Immediate Termination Conditions (Critical Violations)</h4><p>The following may result in disciplinary action, up to and including immediate termination, subject to applicable law: expired, suspended, or invalid BSIS Guard Card or required permits; post abandonment or failure to remain on assigned duty without authorization; falsification of reports, time records, or company documents; theft, dishonesty, or misconduct; violation of safety rules creating a serious risk to persons or property; possession of weapons or prohibited items in violation of company policy or law; being under the influence of drugs or alcohol while on duty.</p></div><div class=\"pbox\"><h4>Attendance & Reliability Requirements</h4><p>I understand that reliable attendance is an essential job function. During the introductory period: excessive absenteeism, tardiness, or failure to report to scheduled shifts may result in discipline up to and including termination; failure to properly notify the Company of an absence in accordance with company policy may be treated as a no-call/no-show; multiple no-call/no-show occurrences may be considered job abandonment.</p></div><div class=\"pbox\"><h4>Overtime & Schedule Flexibility</h4><p>I understand that the nature of security services requires flexibility in scheduling to meet operational and client needs. My work schedule may include days, nights, weekends, holidays, and extended shifts. I may be required to work overtime, including last-minute or emergency coverage, as permitted by law. All overtime will be compensated in accordance with California wage and hour laws. I must obtain prior authorization from management before working overtime, unless required due to an emergency or operational necessity.</p></div><div class=\"pbox\"><h4>Use of Force & Incident Reporting</h4><p>I understand that as a security officer, my primary role is to observe and report, deter incidents, and act within the limits of my training, Company policy, and applicable law. I will only use force when legally justified and permitted under Company policy and applicable law. All incidents must be reported immediately to the Company and documented accurately. All reports must be truthful, complete, and accurate.</p></div><div class=\"pbox\"><h4>Cell Phone & Distraction Policy</h4><p>I understand that maintaining constant awareness and attentiveness is an essential function of my role. Personal cell phone use while on duty is strictly limited and may only be used in accordance with Company policy. I will not use my phone or other personal devices in a manner that interferes with my duties, including while monitoring posts, conducting patrols, or observing surveillance systems.</p></div><div class=\"notice\">By signing, I acknowledge that I have read and understand this agreement; I understand my employment is at-will; I agree to comply with all Company policies, safety rules, and legal requirements; and the contents of this agreement were reviewed and discussed with me during orientation.</div><div class=\"fld\"><label>Company Representative</label><input type=\"text\" name=\"f[company_representative]\" class=\"fi\"></div>"}, "background": {"title": "Authorization for Background Investigation", "body": "<div class=\"row\"><div class=\"fld\"><label>Applicant Name</label><input type=\"text\" name=\"f[applicant_name]\" class=\"fi\" required></div> <div class=\"fld\"><label>Date</label><input type=\"text\" name=\"f[date]\" class=\"fi\" required></div></div><div class=\"pbox\"><h4>Authorization</h4><p>I hereby authorize Hammer Head Security and its designated agents and representatives to obtain consumer reports and/or investigative consumer reports about me for employment purposes. I understand that these reports may include information regarding my: criminal history; employment history; education verification; professional licenses and certifications (including BSIS Guard Registration); driving record (if applicable); and other relevant background information. I authorize all courts, law enforcement agencies, employers, educational institutions, licensing authorities, and other relevant organizations to release information about me to Hammer Head Security or its authorized background screening provider.</p></div><div class=\"infob\">I understand that: this authorization applies to both pre-employment and, if hired, during the course of employment where permitted by law; I have the right to request a copy of any consumer report obtained about me; and I may request additional information about the nature and scope of any investigative consumer report.</div><label class=\"ck\"><input type=\"checkbox\"> Optional: I request to receive a copy of any consumer report obtained about me.</label><div class=\"notice\">I certify that the information I have provided in connection with my application for employment is true and complete to the best of my knowledge.</div>"}, "uniform": {"title": "California Uniform and Uniform Deposit Policy", "body": "<div class=\"row\"><div class=\"fld\"><label>Employee Name</label><input type=\"text\" name=\"f[employee_name]\" class=\"fi\" required></div> <div class=\"fld\"><label>Date</label><input type=\"text\" name=\"f[date]\" class=\"fi\" required></div></div><div class=\"pbox\"><h4>Issuance and Company Ownership</h4><p>Hammer Head will issue the company-owned distinctive uniform items required for the employee's assignment. All company-issued items remain company property at all times. Employees must sign an issuance record for company-issued items. Employees may not sell, loan, pledge, alter, conceal, or use company-issued uniform items for non-company purposes.</p></div><div class=\"pbox\"><h4>Wear Standards While on Duty</h4><p>Employees must report to duty in the complete assigned uniform for the post or event, neat in appearance, with company identifiers visible. This generally means the assigned company shirt or polo, jacket if issued or required by assignment, company badge or shield, arm patches, and any client-required tie or hat, together with any required plain black wardrobe items. Failure to comply with uniform standards may result in corrective action, up to and including termination of employment.</p></div><div class=\"pbox\"><h4>Maintenance, Care, and Replacement</h4><p>Hammer Head will provide and maintain company-issued distinctive uniform items required under this policy. Employees must follow reasonable care instructions, promptly report damage or sizing issues, and return company-issued items when a replacement or repair is requested. Employees are not charged for ordinary laundering, ordinary maintenance, repair, or normal wear and tear of company-issued distinctive uniform items.</p></div><div class=\"pbox\"><h4>Return of Company Property</h4><p>All company-issued uniform items and related company property must be returned immediately upon separation of employment, transfer out of the assignment if requested, or earlier upon company demand. At separation, Hammer Head will not delay, condition, or reduce final wage payment based on whether company-issued items have been returned.</p></div><div class=\"pbox\"><h4>Loss, Damage, and Discipline</h4><p>Employees must immediately report any lost, stolen, damaged, or missing company-issued item to their supervisor. Normal wear and tear will not result in a charge. Intentional damage, unauthorized alteration, misuse, or deliberate failure to return company property may result in discipline and any other lawful remedy available to Hammer Head. Nothing in this policy authorizes Hammer Head to make a unilateral deduction from current wages or final wages for allegedly lost, unreturned, or damaged company-issued items.</p></div><div class=\"notice\">I acknowledge receipt of Hammer Head Security\\'s California Uniform and Uniform Deposit Policy. I understand this acknowledgment confirms receipt of the policy only and does not authorize any payroll deduction or final-pay withholding.</div>"}, "handbook": {"title": "Employee Handbook Acknowledgment", "body": "<div class=\"row\"><div class=\"fld\"><label>Employee Name</label><input type=\"text\" name=\"f[employee_name]\" class=\"fi\" required></div> <div class=\"fld\"><label>Position</label><input type=\"text\" name=\"f[position]\" class=\"fi\" required></div> <div class=\"fld\"><label>Date</label><input type=\"text\" name=\"f[date]\" class=\"fi\" required></div></div><div class=\"pbox\"><h4>Electronic Delivery & Receipt</h4><p>I acknowledge that I have received access to the Hammer Head Security Employee Handbook (\"Handbook\") electronically, including via email or secure digital platform. I understand that it is my responsibility to review the Handbook in full and that I may request a printed copy at any time at no cost.</p></div><div class=\"pbox\"><h4>Acknowledgment of Understanding</h4><p>I acknowledge receipt of the Handbook and understand that it contains important information regarding Company policies, procedures, and expectations. I understand and agree that I am responsible for reading, understanding, and complying with all policies contained in the Handbook, as well as any updates, revisions, or supplements issued by the Company. Updated policies may be distributed electronically and that continued employment constitutes acknowledgment of and responsibility to comply with revised policies.</p></div><div class=\"pbox\"><h4>At-Will Employment</h4><p>I understand and agree that my employment with Hammer Head Security is at-will, meaning that either I or the Company may terminate the employment relationship at any time, with or without cause or notice, subject to applicable law. No supervisor, manager, or representative of the Company has authority to enter into any agreement for employment for any specified period or to make any agreement contrary to at-will employment unless such agreement is in a written contract signed by the Company President or authorized executive. Nothing in the Handbook or this acknowledgment creates a contract of employment.</p></div><div class=\"pbox\"><h4>No Contract / Right to Modify</h4><p>I understand that the Handbook is not a contract and does not create contractual rights. The Company reserves the right to modify, interpret, or discontinue policies at any time, with or without notice, to the extent permitted by law.</p></div><div class=\"pbox\"><h4>Agreement to Comply</h4><p>I agree to comply with all Company policies, including safety, use of force, incident reporting, scheduling, uniform, and conduct requirements. I understand violations may result in disciplinary action, up to and including termination. I understand that compliance with all applicable BSIS regulations, licensing requirements, training obligations, and lawful directives is a condition of employment.</p></div><div class=\"notice\">By signing electronically below, I acknowledge that I have received, read, and agree to comply with the Handbook.</div><div class=\"fld\"><label>Company Representative</label><input type=\"text\" name=\"f[company_representative]\" class=\"fi\"></div>"}, "drug1": {"title": "Drug & Alcohol Testing Consent and Authorization", "body": "<div class=\"row\"><div class=\"fld\"><label>Employee Name</label><input type=\"text\" name=\"f[employee_name]\" class=\"fi\" required></div> <div class=\"fld\"><label>Employee ID</label><input type=\"text\" name=\"f[employee_id]\" class=\"fi\" required></div> <div class=\"fld\"><label>Position</label><input type=\"text\" name=\"f[position]\" class=\"fi\" required></div> <div class=\"fld\"><label>Date</label><input type=\"text\" name=\"f[date]\" class=\"fi\" required></div></div><div class=\"pbox\"><h4>1. Agreement to Testing</h4><p>As a condition of employment with Hammer Head Security, I acknowledge and agree that I may be required to undergo drug and/or alcohol testing in accordance with Company policy and applicable federal and California law.</p></div><div class=\"pbox\"><h4>2. Types of Testing</h4><p>I understand that testing may be required under the following circumstances, where permitted by law: reasonable suspicion; post-incident / post-accident; return-to-duty; follow-up testing; and pre-employment (if applicable).</p></div><div class=\"pbox\"><h4>3. Testing Authorization</h4><p>I authorize Hammer Head Security to: require me to submit to drug and/or alcohol testing when applicable; collect appropriate specimens (such as urine, saliva, breath, blood, or other legally permitted methods); send specimens to a qualified laboratory for analysis; and receive and review the results of such testing for employment-related purposes.</p></div><div class=\"pbox\"><h4>4. Refusal to Test</h4><p>I understand that refusal to submit to required testing, failure to cooperate, or attempts to tamper with, substitute, or adulterate any specimen may result in disciplinary action, up to and including termination of employment. I further understand that refusal to test may be treated as a violation of Company policy.</p></div><div class=\"pbox\"><h4>5. California Cannabis Compliance</h4><p>I understand that: the Company will comply with applicable California laws regarding cannabis use; the Company will not take adverse action based solely on lawful off-duty cannabis use; testing, if conducted, will be interpreted and applied in a manner consistent with California law; and I may still be subject to discipline if I am impaired at work, possess or use cannabis during work, or otherwise violate Company policy.</p></div><div class=\"pbox\"><h4>9. Confidentiality of Results</h4><p>I understand that test results will be kept confidential to the extent required by law and results will only be shared with individuals who have a legitimate business need or as required by law.</p></div><div class=\"pbox\"><h4>11. Release of Information</h4><p>I authorize the testing laboratory or medical review entity to release test results to Hammer Head Security for employment-related purposes.</p></div><div class=\"notice\">By signing, I: acknowledge that I have received and understand the Company\\'s Drug and Alcohol Testing Policy; agree to comply with testing requirements as a condition of employment; and authorize the Company to conduct testing as outlined above.</div><div class=\"fld\"><label>Company Representative</label><input type=\"text\" name=\"f[company_representative]\" class=\"fi\"></div>"}, "drug2": {"title": "Drug-Free Workplace Acknowledgment", "body": "<div class=\"row\"><div class=\"fld\"><label>Employee Name</label><input type=\"text\" name=\"f[employee_name]\" class=\"fi\" required></div> <div class=\"fld\"><label>Employee ID</label><input type=\"text\" name=\"f[employee_id]\" class=\"fi\" required></div> <div class=\"fld\"><label>Position</label><input type=\"text\" name=\"f[position]\" class=\"fi\" required></div> <div class=\"fld\"><label>Date</label><input type=\"text\" name=\"f[date]\" class=\"fi\" required></div></div><div class=\"pbox\"><h4>1. Agreement to Testing</h4><p>As a condition of employment with Hammer Head Security, I acknowledge and agree that I may be required to undergo drug and/or alcohol testing in accordance with Company policy and applicable federal and California law.</p></div><div class=\"pbox\"><h4>2. Types of Testing</h4><p>I understand that testing may be required under the following circumstances, where permitted by law: reasonable suspicion; post-incident / post-accident; return-to-duty; follow-up testing; and pre-employment (if applicable).</p></div><div class=\"pbox\"><h4>3. Testing Authorization</h4><p>I authorize Hammer Head Security to: require me to submit to drug and/or alcohol testing when applicable; collect appropriate specimens (such as urine, saliva, breath, blood, or other legally permitted methods); send specimens to a qualified laboratory for analysis; and receive and review the results of such testing for employment-related purposes.</p></div><div class=\"pbox\"><h4>4. Refusal to Test</h4><p>Refusal to submit to required testing, failure to cooperate, or attempts to tamper with, substitute, or adulterate any specimen may result in disciplinary action, up to and including termination of employment. Refusal to test may be treated as a violation of Company policy.</p></div><div class=\"pbox\"><h4>5. California Cannabis Compliance</h4><p>The Company will comply with applicable California laws regarding cannabis use. The Company will not take adverse action based solely on lawful off-duty cannabis use. Testing, if conducted, will be interpreted and applied in a manner consistent with California law. I may still be subject to discipline if I am impaired at work, possess or use cannabis during work, or otherwise violate Company policy.</p></div><div class=\"pbox\"><h4>11. Release of Information</h4><p>I authorize the testing laboratory or medical review entity to release test results to Hammer Head Security for employment-related purposes.</p></div><div class=\"notice\">By signing, I: acknowledge that I have received and understand the Company\\'s Drug and Alcohol Testing Policy; agree to comply with testing requirements as a condition of employment; and authorize the Company to conduct testing as outlined above.</div><div class=\"fld\"><label>Company Representative</label><input type=\"text\" name=\"f[company_representative]\" class=\"fi\"></div>"}, "drug3": {"title": "Drug-Free Workplace Policy & Drug Testing Acknowledgment", "body": "<div class=\"row\"><div class=\"fld\"><label>Employee Name</label><input type=\"text\" name=\"f[employee_name]\" class=\"fi\" required></div> <div class=\"fld\"><label>Employee ID</label><input type=\"text\" name=\"f[employee_id]\" class=\"fi\" required></div> <div class=\"fld\"><label>Position</label><input type=\"text\" name=\"f[position]\" class=\"fi\" required></div> <div class=\"fld\"><label>Date</label><input type=\"text\" name=\"f[date]\" class=\"fi\" required></div></div><div class=\"pbox\"><h4>Prohibited Conduct</h4><p>Employees are strictly prohibited from the following while on duty, on company property, at a client site, or while representing Hammer Head Security: being under the influence or impaired by alcohol, cannabis, illegal drugs, or controlled substances; reporting to work impaired by drugs, cannabis, alcohol, or medications; possessing, using, distributing, or selling illegal drugs or controlled substances; using cannabis during working hours, including meal or rest breaks; operating company vehicles or equipment while impaired; and performing security duties while impaired in any way. Any employee who appears impaired may be immediately removed from duty pending investigation and testing.</p></div><div class=\"pbox\"><h4>Cannabis (Marijuana) Policy – California Compliance</h4><p>While cannabis use is legal under California law: employees may not be impaired while working; employees may not possess or use cannabis on duty or on company property; and employees may not perform security duties while impaired. The company will base impairment determinations on the totality of observable circumstances, not on any single factor. Hammer Head Security does not discipline lawful off-duty cannabis use that does not result in workplace impairment.</p></div><div class=\"pbox\"><h4>Reasonable Suspicion Indicators</h4><p>Testing may be required when a supervisor reasonably suspects impairment based on observable behavior, including: slurred speech; unsteady movement or coordination; erratic or unsafe behavior; confusion or impaired judgment; odor of alcohol or drugs; possession of drugs or paraphernalia; significant behavior changes. Odor alone will not be the sole basis for disciplinary action but may be considered along with other observable indicators.</p></div><div class=\"pbox\"><h4>Refusal to Test</h4><p>The following may be considered refusal: refusing testing; failing to cooperate; delaying testing without valid reason; tampering with testing; providing false information. Refusal to test is considered a violation of company safety policy and may result in disciplinary action up to and including termination.</p></div><div class=\"pbox\"><h4>Prescription and Over-the-Counter Medications</h4><p>Employees must notify management of medications that may affect their ability to perform duties safely. Employees may not work in safety-sensitive roles if impaired by medication. Medical information will be handled confidentially.</p></div><div class=\"notice\">I authorize Hammer Head Security and its designated testing provider, laboratory, or medical review officer to conduct drug and/or alcohol testing when required and to release test results to the company for employment-related purposes in accordance with applicable laws. By signing, I acknowledge that I have received and read this policy; I understand I must report to work free from impairment; I understand testing may be required; I authorize drug/alcohol testing when required; and I understand refusal may result in termination.</div><div class=\"fld\"><label>Company Representative</label><input type=\"text\" name=\"f[company_representative]\" class=\"fi\"></div>"}, "uof": {"title": "Use of Force Policy Acknowledgment", "body": "<div class=\"row\"><div class=\"fld\"><label>Employee Name</label><input type=\"text\" name=\"f[employee_name]\" class=\"fi\" required></div> <div class=\"fld\"><label>Employee ID</label><input type=\"text\" name=\"f[employee_id]\" class=\"fi\" required></div> <div class=\"fld\"><label>Position</label><input type=\"text\" name=\"f[position]\" class=\"fi\" required></div> <div class=\"fld\"><label>Date</label><input type=\"text\" name=\"f[date]\" class=\"fi\" required></div></div><div class=\"pbox\"><h4>2. Legal Compliance Statement</h4><p>I understand that this policy is intended to comply with: applicable California law, including provisions of the California Penal Code governing use of force and citizen's arrest; Bureau of Security and Investigative Services (BSIS) requirements and training standards; and applicable federal legal standards regarding objective reasonableness, based on the totality of circumstances.</p></div><div class=\"pbox\"><h4>3. Status as Private Security</h4><p>I understand that: I am not a peace officer; I have no authority beyond that of a private person under California law; and my authority is limited to: observation and reporting; deterrence and prevention; and lawful citizen's arrest (Penal Code §837) when legally justified.</p></div><div class=\"pbox\"><h4>4. Use of Force Standard</h4><p>I understand and agree that: force may only be used when legally justified and reasonably necessary; any use of force must be proportional to the threat, objectively reasonable under the circumstances, and limited to the minimum amount necessary; and force must be immediately discontinued once the threat has ended.</p></div><div class=\"pbox\"><h4>5. De-Escalation Requirement</h4><p>I understand that I am required to: attempt verbal de-escalation and conflict resolution whenever safe and feasible; and avoid physical confrontation whenever possible.</p></div><div class=\"pbox\"><h4>6. Prohibited Conduct</h4><p>I understand that the following are strictly prohibited: excessive, unreasonable, or unnecessary force; retaliatory, punitive, or emotionally driven force; use of chokeholds, carotid restraints, or airway-restricting techniques; and use of force outside Company policy, assigned duties, training, or the law.</p></div><div class=\"pbox\"><h4>8. Reporting Requirement</h4><p>I understand that I must: immediately report any use of force, regardless of severity; notify a supervisor without delay; and complete accurate, complete, and truthful reports. Failure to report or falsification of information may result in disciplinary action, up to and including termination.</p></div><div class=\"pbox\"><h4>12. Personal Liability Acknowledgment</h4><p>I understand that improper, excessive, or unlawful use of force may result in: personal civil liability; and criminal prosecution. I further understand that the Company may deny defense or indemnification for actions taken outside policy, training, assigned duties, or applicable law.</p></div><div class=\"notice\">By signing, I acknowledge that: I received this policy during onboarding; I understand its contents; I agree to comply fully; and I understand the legal and personal consequences of violating this policy. I confirm that this Use of Force Policy has been provided to me and reviewed with me during my onboarding/orientation.</div><div class=\"fld\"><label>Employer Representative Name</label><input type=\"text\" name=\"f[employer_representative_name]\" class=\"fi\"></div>"}, "econsent": {"title": "Consent to Receive Documents Electronically", "body": "<div class=\"row\"><div class=\"fld\"><label>Employee Name</label><input type=\"text\" name=\"f[employee_name]\" class=\"fi\" required></div> <div class=\"fld\"><label>Employee ID</label><input type=\"text\" name=\"f[employee_id]\" class=\"fi\" required></div> <div class=\"fld\"><label>Position</label><input type=\"text\" name=\"f[position]\" class=\"fi\" required></div> <div class=\"fld\"><label>Date</label><input type=\"text\" name=\"f[date]\" class=\"fi\" required></div> <div class=\"fld\"><label>Email Address</label><input type=\"text\" name=\"f[email_address]\" class=\"fi\" required></div> <div class=\"fld\"><label>Phone Number</label><input type=\"text\" name=\"f[phone_number]\" class=\"fi\" required></div></div><div class=\"pbox\"><h4>1. Consent to Electronic Delivery</h4><p>I acknowledge that during orientation I have been informed that Hammer Head Security provides many employment-related documents electronically. I voluntarily consent to receive and access documents in electronic form, including but not limited to: payroll documents, including pay stubs and wage statements; tax documents, including Form W-2 and related forms; corrective action, disciplinary notices, and performance documentation; company policies, handbook updates, and acknowledgments; and work schedules, notices, and other employment-related communications.</p></div><div class=\"pbox\"><h4>2. Electronic Tax Document Consent (W-2)</h4><p>I specifically consent to receive my Form W-2 electronically. I understand that: I may request a paper copy of my Form W-2 at any time; I may withdraw this consent before issuance of the Form W-2 for any tax year; and if I withdraw consent, a paper Form W-2 will be provided to me.</p></div><div class=\"pbox\"><h4>3. Paystub Access (California Compliance)</h4><p>I understand that my wage statements (pay stubs) will be provided electronically through the Company's designated payroll system. I acknowledge that: I have the ability to access and print my pay stubs; I may request a paper copy of any pay stub at no cost; and the Company will comply with applicable California Labor Code requirements regarding wage statements.</p></div><div class=\"pbox\"><h4>7. Communication and Operational Notices</h4><p>I understand and agree that the Company may contact me and provide work-related communications electronically, including: work schedules and schedule changes; call-offs, post assignments, and shift instructions; emergency notifications and safety alerts; requests for availability or job assignments; instructions from supervisors or management; investigation-related communications; and reminders regarding licensing, certifications, or compliance requirements. I consent to receive work-related text messages and phone calls from the Company.</p></div><div class=\"pbox\"><h4>8. Contact Information Responsibility</h4><p>I agree to maintain current and accurate contact information with the Company, including my phone number and email address. Failure to update my contact information may result in missed communications. Failure to review or respond to electronic communications, or failure to maintain access to such communications, may result in disciplinary action, up to and including termination.</p></div><div class=\"notice\">By signing, I confirm that: I received this notice during orientation; I understand that employment-related documents, including pay stubs, tax forms, corrective actions, and work communications, may be provided electronically; and I consent to electronic delivery and communication as outlined above. I understand that I may request paper copies of any electronically provided document at any time, at no cost.</div>"}, "vehicle": {"title": "Use of Personal Vehicles on Duty Policy", "body": "<div class=\"row\"><div class=\"fld\"><label>Employee Name</label><input type=\"text\" name=\"f[employee_name]\" class=\"fi\" required></div> <div class=\"fld\"><label>Employee ID</label><input type=\"text\" name=\"f[employee_id]\" class=\"fi\" required></div> <div class=\"fld\"><label>Position</label><input type=\"text\" name=\"f[position]\" class=\"fi\" required></div> <div class=\"fld\"><label>Date</label><input type=\"text\" name=\"f[date]\" class=\"fi\" required></div></div><div class=\"pbox\"><h4>2. Policy Statement</h4><p>Hammer Head Security maintains strict control over patrol methods and transportation to ensure safety, regulatory compliance, and operational consistency. The use of personal vehicles while on duty is strictly prohibited unless expressly authorized in advance in writing under this policy.</p></div><div class=\"pbox\"><h4>3. Patrol Type Rules (Strict Enforcement)</h4><p>I understand and agree to the following: Foot Patrol Sites — No vehicle use is permitted under any circumstances. All duties must be performed on foot only. Vehicle Patrol Sites — Patrol duties must be conducted only using company-provided vehicles. Personal vehicles are not permitted. I understand that I may not modify patrol methods, substitute patrol types, or use any vehicle unless specifically assigned and authorized.</p></div><div class=\"pbox\"><h4>4. Prohibited Use of Personal Vehicles</h4><p>I understand that I am not authorized to use my personal vehicle for any work-related purpose, including but not limited to: patrol routes or site inspections; responding to incidents; transporting equipment or personnel; or traveling between posts or locations during a shift (unless expressly directed under this policy).</p></div><div class=\"pbox\"><h4>5. Limited Exception (Written Authorization Required)</h4><p>A personal vehicle may only be used if I receive prior written authorization from the Company's Safety / Risk / Compliance Department, and the authorization clearly defines the scope, duration, and purpose of such use. As part of the authorization process, the Safety / Risk / Compliance Department will verify my valid driver's license, vehicle registration, and active insurance coverage. Verbal approval or approval from supervisors or managers is not valid and will not be relied upon. No employee is required or expected to use a personal vehicle unless formally authorized under this policy.</p></div><div class=\"pbox\"><h4>8. Violations</h4><p>I understand that: unauthorized use of a personal vehicle is a violation of Company policy; such violations may result in disciplinary action, up to and including removal from duty and termination of employment; and failure to follow this policy may result in denial of liability coverage to the extent permitted by law.</p></div><div class=\"notice\">I certify that: I received this policy during orientation; I fully understand that I am not permitted to use my personal vehicle unless I have prior written authorization under this policy; I understand that I may not rely on verbal instructions that conflict with this policy; and I agree to comply fully with this policy as a condition of my employment.</div><div class=\"fld\"><label>Employer Representative Name</label><input type=\"text\" name=\"f[employer_representative_name]\" class=\"fi\"></div>"}, "driver": {"title": "Driver Requirements, Company Vehicle Use & EPN Compliance", "body": "<div class=\"row\"><div class=\"fld\"><label>Employee Name</label><input type=\"text\" name=\"f[employee_name]\" class=\"fi\" required></div> <div class=\"fld\"><label>Employee ID</label><input type=\"text\" name=\"f[employee_id]\" class=\"fi\" required></div> <div class=\"fld\"><label>Position</label><input type=\"text\" name=\"f[position]\" class=\"fi\" required></div> <div class=\"fld\"><label>Date</label><input type=\"text\" name=\"f[date]\" class=\"fi\" required></div> <div class=\"fld\"><label>Driver's License #</label><input type=\"text\" name=\"f[s_license_e_dln_e_dln]\" class=\"fi\"></div> <div class=\"fld\"><label>DL Expiry</label><input type=\"text\" name=\"f[dl_expiry]\" class=\"fi\"></div></div><div class=\"pbox\"><h4>3. Strict Company Vehicle Use Policy</h4><p>Employees may only operate Company-owned vehicles that are: properly registered and insured; maintained in accordance with Company standards; and operated in compliance with applicable laws and BSIS requirements (including vehicle marking, where applicable). No supervisor, manager, or employee has authority to override this policy. Any exception must be formally approved in writing by the Company's executive management and Safety/Risk Compliance function. Use of personal vehicles for any Company business is strictly prohibited. No exceptions. No reimbursement-based use. Any unauthorized use of a personal vehicle is considered outside the course and scope of employment to the extent permitted by law.</p></div><div class=\"pbox\"><h4>5. Driver's License Requirement</h4><p>Employees must: maintain a valid, active, and unrestricted California Driver's License at all times; and be legally eligible to operate the assigned vehicle. Driving with a suspended, revoked, restricted, or expired license is strictly prohibited and will result in immediate removal from driving duties.</p></div><div class=\"pbox\"><h4>6. DMV Employer Pull Notice (EPN) Program</h4><p>Employees assigned driving duties must: complete DMV Form INF 1101 (Authorization for Release of Driver Record Information); and authorize the Company to enroll and monitor their driving record through the DMV. I understand that: this authorization is voluntary; however, it is required to perform driving-related job duties; and the Company may receive notifications regarding license suspensions, revocations, or expirations, and traffic violations and reportable incidents. Refusal to participate will result in ineligibility for driving duties.</p></div><div class=\"pbox\"><h4>8. Mandatory Reporting Obligation (Critical Requirement)</h4><p>Employees must notify the Company within 24 hours of: license suspension, revocation, restriction, or expiration; any traffic citation or violation; any accident (on-duty or off-duty, whether or not it involves Company business, if it may affect insurability); and any DUI or driving-related criminal matter. Failure to report may result in disciplinary action.</p></div><div class=\"pbox\"><h4>10. Prohibited Conduct</h4><p>Employees are strictly prohibited from: driving under the influence of drugs, alcohol, or impairing substances; driving with an invalid or suspended license; using Company vehicles for personal purposes; allowing unauthorized individuals to operate Company vehicles; and operating vehicles in violation of Company policy or applicable law.</p></div><div class=\"notice\">By signing, I acknowledge that: I have received, read, and understand this policy; I agree to fully comply with its terms; and I understand that compliance is required if I am assigned driving duties.</div>"}, "harassment": {"title": "Sexual Harassment Prevention Training Acknowledgment", "body": "<div class=\"row\"><div class=\"fld\"><label>Employee Name</label><input type=\"text\" name=\"f[employee_name]\" class=\"fi\" required></div> <div class=\"fld\"><label>Employee ID</label><input type=\"text\" name=\"f[employee_id]\" class=\"fi\" required></div> <div class=\"fld\"><label>Position</label><input type=\"text\" name=\"f[position]\" class=\"fi\" required></div> <div class=\"fld\"><label>Date</label><input type=\"text\" name=\"f[date]\" class=\"fi\" required></div></div><div class=\"pbox\"><h4>1. Acknowledgment of Training Requirement</h4><p>I acknowledge that I have been informed during orientation that Hammer Head Security is committed to maintaining a workplace free from sexual harassment, discrimination, retaliation, and abusive conduct (including workplace bullying). I understand that, in compliance with California law (including Government Code §12950.1) and applicable federal law, I am required to complete sexual harassment prevention training as a condition of employment.</p></div><div class=\"pbox\"><h4>2. Training Obligation</h4><p>I understand and agree to the following: I am required to complete mandatory sexual harassment prevention training within the legally required timeframe: Supervisors — at least 2 hours of training; Non-supervisory employees — at least 1 hour of training. Training must be completed within six (6) months of , or earlier if required by the Company. I may be required to complete refresher training every two (2) years. If I am a temporary or seasonal employee, training may be required within 30 calendar days or 100 hours worked, whichever occurs first, if applicable.</p></div><div class=\"pbox\"><h4>3. Training Content and Standards</h4><p>I understand that the training provided: will meet the requirements established by the California Civil Rights Department (CRD) (formerly DFEH); and will include instruction on sexual harassment prevention; discrimination and retaliation prevention; abusive conduct (including workplace bullying); and bystander intervention strategies and prevention techniques.</p></div><div class=\"pbox\"><h4>4. Policy Acknowledgment</h4><p>I acknowledge that: I have received access to the Company's Anti-Harassment, Anti-Discrimination, and Anti-Retaliation Policy; I understand that harassment, discrimination, retaliation, and abusive conduct are strictly prohibited; and I am responsible for complying with all Company policies and procedures.</p></div><div class=\"pbox\"><h4>5. Reporting Responsibility</h4><p>I understand that I must immediately report any incidents of sexual harassment, discrimination, retaliation, or abusive conduct. Reports may be made to: a supervisor or manager; Human Resources; or any designated Company representative. I understand that the Company strictly prohibits retaliation against any employee who makes a good faith complaint or participates in an investigation. I understand I am not required to report concerns to my direct supervisor and may report to any available reporting channel.</p></div><div class=\"pbox\"><h4>6. Failure to Complete Training</h4><p>I understand that failure to complete required training within the designated timeframe may result in disciplinary action, up to and including termination of employment.</p></div><div class=\"notice\">By signing, I acknowledge that: I have been informed of my training obligations; I understand the Company\\'s policies regarding harassment and workplace conduct; and I agree to complete all required training and comply with all Company policies.</div><div class=\"fld\"><label>Employer Representative Name</label><input type=\"text\" name=\"f[employer_representative_name]\" class=\"fi\"></div>"}, "notices": {"title": "Acknowledgment of Receipt of Required New Hire Notices", "body": "<div class=\"row\"><div class=\"fld\"><label>Employee Name</label><input type=\"text\" name=\"f[employee_name]\" class=\"fi\" required></div> <div class=\"fld\"><label>Position</label><input type=\"text\" name=\"f[position]\" class=\"fi\" required></div> <div class=\"fld\"><label>Date of Hire</label><input type=\"text\" name=\"f[date_of_hire]\" class=\"fi\" required></div></div><div class=\"infob\">I acknowledge that during my onboarding and new hire orientation with Hammer Head Security, I received copies of, or was provided access to, the following required notices, brochures, and informational materials:</div><ul class=\"bl\"><li>DE 2515 – Disability Insurance Provisions Brochure</li><li>DE 2511 – Paid Family Leave Brochure</li><li>DE 2320 – California's Programs for the Unemployed Brochure</li><li>Sexual Harassment Fact Sheet</li><li>Victims of Domestic Violence, Sexual Assault, Stalking, and Related Crimes Leave and Accommodation Notice</li><li>Time of Hire Notice</li><li>California Know Your Rights Notice</li></ul><div class=\"notice\">By signing, I acknowledge that I received the above-listed documents during the onboarding process. I understand that my signature acknowledges receipt of these materials only and does not necessarily indicate agreement with their contents. I understand that it is my responsibility to review the information provided and to seek clarification from management or Human Resources if I have any questions regarding these notices or my rights and responsibilities.</div><div class=\"fld\"><label>Manager / Representative</label><input type=\"text\" name=\"f[manager_representative]\" class=\"fi\"></div>"}, "w4": {"title": "Form W-4 — Employee's Withholding Certificate (2026)", "body": "<div class=\"infob\">IRS Form W-4 (2026) &middot; OMB No. 1545-0074 &middot; Employee&#39;s Withholding Certificate &middot; Give this form to your employer. Your withholding is subject to review by the IRS.</div><div class=\"sh\">Step 1 — Enter Personal Information</div><div class=\"row\"><div class=\"fld\"><label>(a) First Name & Middle Initial</label><input type=\"text\" name=\"f[w4_first]\" class=\"fi\" required></div><div class=\"fld\"><label>Last Name</label><input type=\"text\" name=\"f[w4_last]\" class=\"fi\" required></div><div class=\"fld\"><label>Address</label><input type=\"text\" name=\"f[w4_address]\" class=\"fi\" required></div><div class=\"fld\"><label>City or Town, State, and ZIP Code</label><input type=\"text\" name=\"f[w4_csz]\" class=\"fi\" required></div><div class=\"fld\"><label>(b) Social Security Number</label><input type=\"text\" name=\"f[w4_ssn]\" class=\"fi\" data-mirror=\"ssn\" required></div></div><div class=\"sub\">(c) Filing Status — check one box</div><label class=\"ck\"><input type=\"radio\" name=\"f[w4_filing]\" value=\"single\" required> Single or Married filing separately</label><label class=\"ck\"><input type=\"radio\" name=\"f[w4_filing]\" value=\"married\" required> Married filing jointly or Qualifying surviving spouse</label><label class=\"ck\"><input type=\"radio\" name=\"f[w4_filing]\" value=\"hoh\" required> Head of household (Check only if you&#39;re unmarried and pay more than half the costs of keeping up a home for yourself and a qualifying individual.)</label><div class=\"sh\">Step 2 — Multiple Jobs or Spouse Works (complete if applicable)</div><div class=\"notice\">Complete this step if you (1) hold more than one job at a time, or (2) are married filing jointly and your spouse also works. Do only one of the following:</div><label class=\"ck\"><input type=\"radio\" name=\"f[w4_step2]\" value=\"a\" required> (a) Use the IRS estimator at www.irs.gov/W4App</label><label class=\"ck\"><input type=\"radio\" name=\"f[w4_step2]\" value=\"b\" required> (b) Use the Multiple Jobs Worksheet (page 3 of official W-4)</label><label class=\"ck\"><input type=\"radio\" name=\"f[w4_step2]\" value=\"c\" required> (c) If there are only two jobs total, check this box (do the same on Form W-4 for the other job)</label><label class=\"ck\"><input type=\"radio\" name=\"f[w4_step2]\" value=\"na\" required> Not applicable — I have only one job and my spouse does not work</label><div class=\"sh\">Step 3 — Claim Dependent and Other Credits</div><div class=\"notice\">If your total income will be $200,000 or less ($400,000 or less if married filing jointly), complete Steps 3&ndash;4(b). Otherwise skip to Step 5.</div><div class=\"row\"><div class=\"fld\"><label>3(a) Qualifying children under age 17 &times; $2,200</label><input type=\"number\" min=\"0\" id=\"w4_children\" name=\"f[w4_children]\" class=\"fi fi-opt\" oninput=\"w4calc()\"></div><div class=\"fld\"><label>3(b) Other dependents &times; $500</label><input type=\"number\" min=\"0\" id=\"w4_other\" name=\"f[w4_other]\" class=\"fi fi-opt\" oninput=\"w4calc()\"></div><div class=\"fld\"><label>Add amounts above — total (line 3)</label><input type=\"text\" id=\"w4_dep_total\" name=\"f[w4_dep_total]\" class=\"fi\" readonly style=\"background:#eef4ff;font-weight:700\"></div></div><div class=\"sh\">Step 4 — Other Adjustments (optional)</div><div class=\"row\"><div class=\"fld\"><label>4(a) Other income not from jobs (interest, dividends, retirement)</label><input type=\"text\" name=\"f[w4_4a]\" class=\"fi fi-opt\"></div><div class=\"fld\"><label>4(b) Deductions (from Deductions Worksheet page 4)</label><input type=\"text\" name=\"f[w4_4b]\" class=\"fi fi-opt\"></div><div class=\"fld\"><label>4(c) Extra withholding per pay period</label><input type=\"text\" name=\"f[w4_4c]\" class=\"fi fi-opt\"></div></div><div class=\"sh\">Step 5 — Sign Here</div><div class=\"notice\">Under penalties of perjury, I declare that this certificate, to the best of my knowledge and belief, is true, correct, and complete.</div><div class=\"infob\"><label class=\"ck\"><input type=\"checkbox\" name=\"f[w4_exempt]\" value=\"1\"> I claim exemption from withholding for 2026, and I certify that I meet both of the conditions for exemption. (Do not complete Steps 2&ndash;4 if claiming exemption.) <em>(optional)</em></label></div><div class=\"infob\"><strong>Employer:</strong> Hammer Head Security &middot; 4551 South B Street, Stockton, CA 95206 &middot; EIN provided by HR.</div>"}, "de4": {"title": "Form DE 4 — Employee's Withholding Allowance Certificate (California)", "body": "<div class=\"infob\">California EDD Form DE 4, Rev. 56 (1-26) &mdash; Employee&#39;s Withholding Allowance Certificate. Complete this form so that your employer can withhold the correct California state income tax from your pay.</div><div class=\"notice\">As of January 1, 2020, the federal Form W-4 is used for federal income tax withholding only. You must file the state form DE 4 to determine the appropriate California PIT withholding. If you do not provide your employer a completed DE 4, your employer must use Single with Zero withholding allowance.</div><div class=\"sh\">Personal Information</div><div class=\"row\"><div class=\"fld\"><label>First, Middle, Last Name</label><input type=\"text\" name=\"f[de4_name]\" class=\"fi\" required></div><div class=\"fld\"><label>Social Security Number</label><input type=\"text\" name=\"f[de4_ssn]\" class=\"fi\" data-mirror=\"ssn\" required></div><div class=\"fld\"><label>Address</label><input type=\"text\" name=\"f[de4_address]\" class=\"fi\" required></div><div class=\"fld\"><label>City</label><input type=\"text\" name=\"f[de4_city]\" class=\"fi\" required></div><div class=\"fld\"><label>State</label><input type=\"text\" name=\"f[de4_state]\" class=\"fi\" required></div><div class=\"fld\"><label>ZIP Code</label><input type=\"text\" name=\"f[de4_zip]\" class=\"fi\" required></div></div><div class=\"sh\">Filing Status</div><label class=\"ck\"><input type=\"radio\" name=\"f[de4_filing]\" value=\"single_two\" required> Single or Married (with two or more incomes)</label><label class=\"ck\"><input type=\"radio\" name=\"f[de4_filing]\" value=\"married_one\" required> Married (one income)</label><label class=\"ck\"><input type=\"radio\" name=\"f[de4_filing]\" value=\"hoh\" required> Head of Household</label><div class=\"sh\">Withholding Allowances</div><div class=\"row\"><div class=\"fld\"><label>1a. Number of Regular Withholding Allowances (Worksheet A)</label><input type=\"text\" name=\"f[de4_1a]\" class=\"fi fi-opt\"></div><div class=\"fld\"><label>1b. Number of allowances from the Estimated Deductions (Worksheet B)</label><input type=\"text\" name=\"f[de4_1b]\" class=\"fi fi-opt\"></div><div class=\"fld\"><label>1c. Total Number of Allowances you are claiming</label><input type=\"text\" name=\"f[de4_1c]\" class=\"fi fi-opt\"></div><div class=\"fld\"><label>2. Additional amount withheld each pay period (if employer agrees) (Worksheet C)</label><input type=\"text\" name=\"f[de4_2]\" class=\"fi fi-opt\"></div></div><div class=\"sh\">Exemption from Withholding <span style=\"font-weight:400;text-transform:none;\">(optional — only if it applies to you)</span></div><div class=\"infob\"><label class=\"ck\"><input type=\"checkbox\" name=\"f[de4_exempt3]\" value=\"1\"> 3. I claim exemption from withholding for 2026, and I certify I meet both conditions for exemption.</label><label class=\"ck\"><input type=\"checkbox\" name=\"f[de4_exempt4]\" value=\"1\"> 4. I certify under penalty of perjury that I am not subject to California withholding (SCRA / Military Spouses Residency Relief Act / Veterans Benefits and Transition Act of 2018).</label></div><div class=\"notice\">Under penalty of perjury, I certify that the number of withholding allowances claimed on this certificate does not exceed the number to which I am entitled or, if claiming exemption from withholding, that I am entitled to claim the exempt status.</div>"}, "wotc": {"title": "Form 8850 — WOTC Pre-Screening Notice", "body": "<div class=\"infob\">IRS Form 8850 (Rev. March 2016) &middot; Pre-Screening Notice and Certification Request for the Work Opportunity Credit &middot; OMB No. 1545-1500.</div><div class=\"notice\">Job applicant: Fill in the lines below and check any boxes that apply. Complete only this side.</div><div class=\"row\"><div class=\"fld\"><label>Your Name</label><input type=\"text\" name=\"f[wotc_name]\" class=\"fi\" required></div><div class=\"fld\"><label>Social Security Number</label><input type=\"text\" name=\"f[wotc_ssn]\" class=\"fi\" data-mirror=\"ssn\" required></div><div class=\"fld\"><label>Street Address Where You Live</label><input type=\"text\" name=\"f[wotc_street]\" class=\"fi\" required></div><div class=\"fld\"><label>City or Town, State, and ZIP Code</label><input type=\"text\" name=\"f[wotc_csz]\" class=\"fi\" required></div><div class=\"fld\"><label>County</label><input type=\"text\" name=\"f[wotc_county]\" class=\"fi\" required></div><div class=\"fld\"><label>Telephone Number</label><input type=\"text\" name=\"f[wotc_phone]\" class=\"fi\" required></div><div class=\"fld\"><label>If under age 40, date of birth (month, day, year)</label><input type=\"text\" name=\"f[wotc_dob_u40]\" class=\"fi\" data-mirror=\"dob\"></div></div><div class=\"sub\">Check any boxes that apply to you:</div><label class=\"ck\"><input type=\"checkbox\" name=\"f[wotc_box1]\" value=\"1\"> 1 &mdash; Check here if you received a conditional certification from the state workforce agency (SWA) or a participating local agency for the work opportunity credit.</label><label class=\"ck\"><input type=\"checkbox\" name=\"f[wotc_box2]\" value=\"1\"> 2 &mdash; Check here if any of the following apply: TANF assistance 9 of past 18 months; OR veteran whose family received SNAP for a 3-month period in past 15 months; OR referred by a state rehab agency, a Ticket to Work employment network, or the VA; OR age 18&ndash;39 in a family that received SNAP for the past 6 months (or 3 of past 5, no longer eligible); OR convicted of a felony or released from prison for a felony in the past year; OR received SSI in the past 60 days; OR veteran unemployed 4 weeks&ndash;6 months in the past year.</label><label class=\"ck\"><input type=\"checkbox\" name=\"f[wotc_box6]\" value=\"1\"> 6 &mdash; Check here if you are a member of a family that received TANF payments for at least the past 18 months; OR for any 18 months beginning after Aug 5, 1997 (earliest such period ended in past 2 years); OR stopped being eligible in past 2 years due to a maximum-time limit.</label><label class=\"ck\"><input type=\"checkbox\" name=\"f[wotc_box7]\" value=\"1\"> 7 &mdash; Check here if you are in a period of unemployment that is at least 27 consecutive weeks and for all or part of that period you received unemployment compensation.</label><div class=\"notice\">Signature — All Applicants Must Sign. Under penalties of perjury, I declare that I gave the above information to the employer on or before the day I was offered a job, and it is, to the best of my knowledge, true, correct, and complete.</div><div class=\"sh\">Page 2 — WOTC Screening Questionnaire</div><div class=\"notice\">Please fill in these forms slowly and legibly. (Form Updated 01/01/2020)</div><div class=\"row\"><div class=\"fld\"><label>Company Name</label><input type=\"text\" name=\"f[wotc_company]\" class=\"fi\"></div><div class=\"fld\"><label>Company EIN Number</label><input type=\"text\" name=\"f[wotc_ein]\" class=\"fi\"></div></div><div class=\"ck\">Have you ever worked for this Employer before? Are you a Re-hire? &nbsp; <label><input type=\"radio\" name=\"f[wotc_q_rehire]\" required value=\"yes\"> Yes</label> &nbsp; <label><input type=\"radio\" name=\"f[wotc_q_rehire]\" required value=\"no\"> No</label></div><div class=\"ck\">Are you under age 40? &nbsp; <label><input type=\"radio\" name=\"f[wotc_q_u40]\" required value=\"yes\"> Yes</label> &nbsp; <label><input type=\"radio\" name=\"f[wotc_q_u40]\" required value=\"no\"> No</label></div><div class=\"ck\">Have you been unemployed for at least 27 weeks, and collected Unemployment Insurance? &nbsp; <label><input type=\"radio\" name=\"f[wotc_q_ui27]\" required value=\"yes\"> Yes</label> &nbsp; <label><input type=\"radio\" name=\"f[wotc_q_ui27]\" required value=\"no\"> No</label></div><div class=\"ck\">Are you a Veteran of the US Armed Forces? &nbsp; <label><input type=\"radio\" name=\"f[wotc_q_vet]\" required value=\"yes\"> Yes</label> &nbsp; <label><input type=\"radio\" name=\"f[wotc_q_vet]\" required value=\"no\"> No</label></div><div class=\"pbox\"><h4>If yes (Veteran):</h4></div><div class=\"ck\">Are you a member of a family that received SNAP (Food Stamps Benefits)? &nbsp; <label><input type=\"radio\" name=\"f[wotc_q_vet_snap]\" required value=\"yes\"> Yes</label> &nbsp; <label><input type=\"radio\" name=\"f[wotc_q_vet_snap]\" required value=\"no\"> No</label></div><div class=\"ck\">Are you entitled to compensation for a service-connected disability? &nbsp; <label><input type=\"radio\" name=\"f[wotc_q_vet_disab]\" required value=\"yes\"> Yes</label> &nbsp; <label><input type=\"radio\" name=\"f[wotc_q_vet_disab]\" required value=\"no\"> No</label></div><div class=\"ck\">Were you discharged from active duty within the last year? &nbsp; <label><input type=\"radio\" name=\"f[wotc_q_vet_disch]\" required value=\"yes\"> Yes</label> &nbsp; <label><input type=\"radio\" name=\"f[wotc_q_vet_disch]\" required value=\"no\"> No</label></div><div class=\"ck\">Were you unemployed for a combined total of 6 months before you were hired? &nbsp; <label><input type=\"radio\" name=\"f[wotc_q_vet_unemp6]\" required value=\"yes\"> Yes</label> &nbsp; <label><input type=\"radio\" name=\"f[wotc_q_vet_unemp6]\" required value=\"no\"> No</label></div><div class=\"ck\">Have you, or your family, received SNAP benefits in the 6 months before you were hired? &nbsp; <label><input type=\"radio\" name=\"f[wotc_q_snap6]\" required value=\"yes\"> Yes</label> &nbsp; <label><input type=\"radio\" name=\"f[wotc_q_snap6]\" required value=\"no\"> No</label></div><div class=\"ck\">Or received SNAP Benefits for at least a 3-month period, but you are no longer receiving it? &nbsp; <label><input type=\"radio\" name=\"f[wotc_q_snap3]\" required value=\"yes\"> Yes</label> &nbsp; <label><input type=\"radio\" name=\"f[wotc_q_snap3]\" required value=\"no\"> No</label></div><div class=\"row\"><div class=\"fld\"><label>If yes, Name of Primary Recipient</label><input type=\"text\" name=\"f[wotc_snap_recip]\" class=\"fi\"></div><div class=\"fld\"><label>And City, State where benefits were received</label><input type=\"text\" name=\"f[wotc_snap_city]\" class=\"fi\"></div></div><div class=\"ck\">Are you a member of a family that received TANF assistance for at least 18 months before you were hired? &nbsp; <label><input type=\"radio\" name=\"f[wotc_q_tanf18]\" required value=\"yes\"> Yes</label> &nbsp; <label><input type=\"radio\" name=\"f[wotc_q_tanf18]\" required value=\"no\"> No</label></div><div class=\"ck\">Or, did your family stop being eligible for TANF assistance within 2 years before being hired (max time reached)? &nbsp; <label><input type=\"radio\" name=\"f[wotc_q_tanf_end]\" required value=\"yes\"> Yes</label> &nbsp; <label><input type=\"radio\" name=\"f[wotc_q_tanf_end]\" required value=\"no\"> No</label></div><div class=\"row\"><div class=\"fld\"><label>If yes, Name of Primary Recipient</label><input type=\"text\" name=\"f[wotc_tanf_recip]\" class=\"fi\"></div><div class=\"fld\"><label>And City, State where benefits were received</label><input type=\"text\" name=\"f[wotc_tanf_city]\" class=\"fi\"></div></div><div class=\"ck\">Did you receive Supplemental Security Income (SSI Benefits) for any month, ending within the 60 days, before you were hired? &nbsp; <label><input type=\"radio\" name=\"f[wotc_q_ssi]\" required value=\"yes\"> Yes</label> &nbsp; <label><input type=\"radio\" name=\"f[wotc_q_ssi]\" required value=\"no\"> No</label></div><div class=\"ck\">Were you convicted of a Felony during the year before you were hired? &nbsp; <label><input type=\"radio\" name=\"f[wotc_q_felony]\" required value=\"yes\"> Yes</label> &nbsp; <label><input type=\"radio\" name=\"f[wotc_q_felony]\" required value=\"no\"> No</label></div><div class=\"pbox\"><h4>Were you referred to an employer by:</h4></div><div class=\"ck\">A Vocational Rehab Agency approved by the state? &nbsp; <label><input type=\"radio\" name=\"f[wotc_q_ref_voc]\" required value=\"yes\"> Yes</label> &nbsp; <label><input type=\"radio\" name=\"f[wotc_q_ref_voc]\" required value=\"no\"> No</label></div><div class=\"ck\">An Employment Network under the Ticket to Work Program? &nbsp; <label><input type=\"radio\" name=\"f[wotc_q_ref_ticket]\" required value=\"yes\"> Yes</label> &nbsp; <label><input type=\"radio\" name=\"f[wotc_q_ref_ticket]\" required value=\"no\"> No</label></div><div class=\"ck\">The Dept. of Veteran Affairs? &nbsp; <label><input type=\"radio\" name=\"f[wotc_q_ref_va]\" required value=\"yes\"> Yes</label> &nbsp; <label><input type=\"radio\" name=\"f[wotc_q_ref_va]\" required value=\"no\"> No</label></div><div class=\"row\"><div class=\"fld\"><label>Print Name</label><input type=\"text\" name=\"f[wotc_print_name]\" class=\"fi\"></div><div class=\"fld\"><label>Social Security #</label><input type=\"text\" name=\"f[wotc_p2_ssn]\" class=\"fi\" data-mirror=\"ssn\"></div><div class=\"fld\"><label>Date of Birth</label><input type=\"text\" name=\"f[wotc_p2_dob]\" class=\"fi\" data-mirror=\"dob\"></div></div><div class=\"notice\">By signing this form, I hereby authorize any agency, organization, Social Security Administration, Department of Veterans Affairs, or individuals, to supply verification of information as may be needed to determine tax credit eligibility to my employer, employer representative (TC Services USA, Inc. dba WOTC.com), or the Department of Labor. I also understand that my responses are used, in part or in full, to complete the IRS Form 8850 and any other documents pertaining to the WOTC Program, and that modifications can be made by my employer, or employer representative, in order to enable the verification screening process as required by some states. This information will not in any way affect my employment.</div><div class=\"row\"><div class=\"fld\"><label>Employment Start Date</label><input type=\"text\" name=\"f[wotc_start]\" class=\"fi\"></div><div class=\"fld\"><label>Starting Wage</label><input type=\"text\" name=\"f[wotc_wage]\" class=\"fi\"></div><div class=\"fld\"><label>Position</label><input type=\"text\" name=\"f[wotc_position]\" class=\"fi\"></div></div><div class=\"infob\">Upload To: www.wotc.com | Phone: 212-635-9500 | Fax: 212-994-2718 | Email: support@wotc.com</div>"}, "emergency": {"title": "Employee Emergency Contact Form (SB 294)", "body": "<div class=\"infob\">4551 South B Street, Stockton, CA 95206 · (877) 505-6463 · www.hammerheadsecurity.com</div><div class=\"notice\"><b>Required by California Labor Code § 1555 (SB 294) — Workplace Know Your Rights Act, effective March 30, 2026.</b></div><div class=\"infob\"><b>IMPORTANT LEGAL NOTICE TO EMPLOYEE:</b> Under California Labor Code § 1555, your employer is required to collect emergency contact information from you. You have the right to designate a person to be notified if you are arrested or detained at the worksite or during work hours. Providing this information is voluntary, but your employer must give you the opportunity. You may update this information at any time.</div><div class=\"sh\">Section A — Employee Information</div><div class=\"row\"><div class=\"fld\"><label>Employee Full Name</label><input type=\"text\" name=\"f[employee_name]\" class=\"fi\"></div><div class=\"fld\"><label>Employee ID</label><input type=\"text\" name=\"f[employee_id]\" class=\"fi\"></div><div class=\"fld\"><label>Job Title / Position</label><input type=\"text\" name=\"f[position]\" class=\"fi\"></div><div class=\"fld\"><label>Hire Date</label><input type=\"text\" name=\"f[date_of_hire]\" class=\"fi\"></div><div class=\"fld\"><label>Work Site / Post Assignment</label><input type=\"text\" name=\"f[work_location_site]\" class=\"fi\"></div><div class=\"fld\"><label>Department / Division</label><input type=\"text\" name=\"f[department_division]\" class=\"fi\"></div><div class=\"fld\"><label>Personal Phone Number</label><input type=\"text\" name=\"f[primary_phone]\" class=\"fi\"></div><div class=\"fld\"><label>Personal Email Address (optional)</label><input type=\"text\" name=\"f[email_address]\" class=\"fi\"></div></div><div class=\"sh\">Section B — Primary Emergency Contact</div><div class=\"row\"><div class=\"fld\"><label>Contact Full Name <span class=\"req\">*</span></label><input type=\"text\" name=\"f[ec1_full_name]\" class=\"fi\" required></div><div class=\"fld\"><label>Relationship to Employee <span class=\"req\">*</span></label><input type=\"text\" name=\"f[ec1_relationship]\" class=\"fi\" required></div><div class=\"fld\"><label>Primary Phone Number <span class=\"req\">*</span></label><input type=\"text\" name=\"f[ec1_phone]\" class=\"fi\" required></div><div class=\"fld\"><label>Alternate Phone Number</label><input type=\"text\" name=\"f[ec1_alt_phone]\" class=\"fi\"></div><div class=\"fld\"><label>Email Address (optional)</label><input type=\"text\" name=\"f[ec1_email]\" class=\"fi\"></div><div class=\"fld\"><label>Home Address (optional)</label><input type=\"text\" name=\"f[ec1_address]\" class=\"fi\"></div></div><div class=\"sub\" style=\"color:var(--crit);\">Arrest / Detention Notification Authorization (Labor Code § 1555 — Required) <span class=\"req\">*</span></div><div class=\"rg\"><label><input type=\"radio\" name=\"f[ec1_arrest_auth]\" required value=\"yes\"> YES — I authorize Hammer Head Security to notify the Primary Emergency Contact named above if I am arrested or detained at the worksite, or during work hours while performing job duties.</label><label><input type=\"radio\" name=\"f[ec1_arrest_auth]\" required value=\"no\"> NO — I do NOT authorize notification of my emergency contact in the event of arrest or detention.</label></div><div class=\"sh\">Section C — Secondary Emergency Contact (Optional)</div><div class=\"row\"><div class=\"fld\"><label>Contact Full Name</label><input type=\"text\" name=\"f[ec2_full_name]\" class=\"fi\"></div><div class=\"fld\"><label>Relationship to Employee</label><input type=\"text\" name=\"f[ec2_relationship]\" class=\"fi\"></div><div class=\"fld\"><label>Primary Phone Number</label><input type=\"text\" name=\"f[ec2_phone]\" class=\"fi\"></div><div class=\"fld\"><label>Alternate Phone Number</label><input type=\"text\" name=\"f[ec2_alt_phone]\" class=\"fi\"></div></div><div class=\"rg\"><label><input type=\"radio\" name=\"f[ec2_arrest_auth]\" value=\"yes\"> YES — Also authorize Hammer Head Security to notify this Secondary Contact in the event of arrest or detention.</label><label><input type=\"radio\" name=\"f[ec2_arrest_auth]\" value=\"no\"> NO</label></div><div class=\"sh\">Section D — Employee Declaration & Signature</div><div class=\"notice\">I certify that the information provided is accurate. I understand I may update this form at any time by submitting a new form to HR. I acknowledge that providing or withholding this information is entirely voluntary.</div>"}, "offer21a": {"title": "Form 21A — Job Offer / At-Will Agreement (On-Call)", "body": "<div class=\"infob\">4551 South B Street, Stockton, CA 95206 · (877) 505-6463 · www.hammerheadsecurity.com</div><div class=\"offer-banner offer-ft\">📄 Form 21A — Job Offer / At-Will Agreement (On-Call / Flexible)</div><div class=\"row\"><div class=\"fld\"><label>Employee Name</label><input type=\"text\" name=\"f[employee_name]\" class=\"fi\"></div><div class=\"fld\"><label>Phone Number</label><input type=\"text\" name=\"f[phone_number]\" class=\"fi\"></div><div class=\"fld\"><label>Email Address</label><input type=\"text\" name=\"f[email_address]\" class=\"fi\"></div><div class=\"fld\"><label>BSIS Guard Registration #</label><input type=\"text\" name=\"f[bsis_guard_card]\" class=\"fi\"></div><div class=\"fld\"><label>Guard Card Expiration</label><input type=\"text\" name=\"f[guard_card_expiry]\" class=\"fi\"></div></div><div class=\"sh\">Orientation Acknowledgment</div><div class=\"pbox\"><p>I acknowledge that this On-Call / Flexible Employment Agreement has been provided to me during my onboarding process. I have had the opportunity to review this document, ask questions, and fully understand the terms and conditions of my employment.</p></div><div class=\"sh\">Position Offered</div><div class=\"pbox\"><p>Job Title: Security Guard / Security Officer (On-Call / Flexible). Employment Classification: Non-Exempt, At-Will Employee. Work Status: Flexible / On-Call Based on Employee Availability.</p></div><div class=\"sh\">Nature of Job Offer</div><div class=\"pbox\"><p>This job offer is extended to employees who have been hired by Hammer Head Security but voluntarily choose not to accept permanent, full-time, or guaranteed hours. The employee is not required to remain on standby unless a shift has been formally accepted. The employee understands and agrees that:</p></div><ul class=\"bl\"><li>No minimum number of hours is guaranteed in any workday or workweek</li><li>Shifts may be offered on a weekly, daily, or per-assignment basis</li><li>The employee is not required to accept all offered shifts</li><li>Declining offered shifts will not result in retaliation or disciplinary action, provided company and licensing requirements are met</li><li>Acceptance of a shift creates a binding work obligation for that specific assignment, and failure to report may result in removal from future assignments and disciplinary action up to and including termination</li><li>This arrangement does not create full-time, part-time, or permanent scheduling status</li></ul><div class=\"pbox\"><p>Nothing in this agreement alters the at-will employment relationship. Either the employee or Hammer Head Security may terminate employment at any time, with or without cause or notice, in accordance with California law. All wages, overtime, meal periods, rest breaks, reporting time pay, and payroll practices will be provided in full compliance with the California Labor Code and applicable IWC Wage Orders.</p></div><div class=\"sh\">Availability Acknowledgment</div><div class=\"pbox\"><p>Availability is provided voluntarily by the employee and does not guarantee or obligate the company to offer work. The employee agrees to communicate availability clearly and in advance when possible, accept only shifts they are legally able and licensed to work, and maintain required certifications and licenses at all times.</p></div><div class=\"sh\">Compensation</div><div class=\"row\"><div class=\"fld\"><label>Rate of Pay ($ / hour)</label><input type=\"text\" name=\"f[pay_rate_amt]\" class=\"fi\" readonly></div></div><div class=\"pbox\"><p>Overtime will be paid in accordance with California Labor Code. Paydays and payroll practices follow company payroll policy.</p></div><div class=\"sh\">Shift Cancellation Policy (California Compliance)</div><ul class=\"bl\"><li>Shift offers are not considered scheduled work until the employee accepts the assignment</li><li>Once a shift is accepted, the company will make reasonable efforts to provide notice of any cancellation or modification</li><li>If a shift is canceled before the employee reports to work, reporting time pay will be provided only if required under IWC Wage Order No. 4-2001</li><li>If the employee reports to the assigned work location as instructed and is not provided the expected hours of work, reporting time pay will be provided in accordance with California law, unless a legal exception applies</li></ul><div class=\"sh\">Employee Call-Outs (Declining or Canceling Accepted Shifts)</div><ul class=\"bl\"><li>If unable to work an accepted shift, the employee will notify Hammer Head Security as soon as reasonably possible</li><li>Repeated last-minute cancellations or no-shows after accepting shifts may result in removal from future assignments and disciplinary action, up to and including termination</li><li>This policy is not intended to penalize lawful use of sick leave or legally protected absences</li></ul><div class=\"sh\">California Labor Law Acknowledgments</div><ul class=\"bl\"><li>Employee is classified as non-exempt and eligible for overtime</li><li>Overtime is paid at 1.5× regular rate after 8 hours in a workday or 40 hours in a workweek; 2× after 12 hours in a workday (when applicable)</li><li>Meal and rest periods will be provided as required by law</li><li>Employment is at-will — either party may terminate at any time, with or without cause or notice</li></ul><div class=\"sh\">BSIS Compliance</div><ul class=\"bl\"><li>A valid BSIS Guard Card must be maintained at all times</li><li>Required BSIS training (including annual continuing education) must be completed</li><li>Uniform, conduct, and reporting standards must comply with BSIS regulations</li><li>Any suspension, expiration, or revocation of BSIS license must be reported immediately</li></ul><div class=\"sh\">No Guarantee of Continued Work</div><div class=\"pbox\"><p>This agreement does not guarantee future assignments, permanent status, or set scheduling. Work is assigned based on client needs, licensing compliance, employee availability, and performance. No expectation of ongoing or regular work is created.</p></div><div class=\"sh\">On-Call / Variable Schedule Policy</div><div class=\"pbox\"><p>The employee understands that this position is on-call and variable schedule employment. The employee is not required to remain on the employer’s premises, remain on duty, monitor communications, respond to shift offers, or otherwise restrict personal activities during non-working time unless a specific shift has been formally offered and accepted. Once a shift is accepted, the employee is expected to report to work as scheduled and perform assigned duties.</p></div><div class=\"sh\">Reporting Time Pay (IWC Wage Order No. 4-2001)</div><div class=\"pbox\"><p>If the employee accepts a scheduled shift and reports to work as instructed but is not provided the expected hours of work, reporting time pay will be provided in accordance with California law, unless a legal exception applies.</p></div><div class=\"sh\">Timekeeping and Payroll Compliance</div><ul class=\"bl\"><li>Employees must accurately record all hours worked using company-approved timekeeping methods</li><li>Off-the-clock work is strictly prohibited</li><li>Falsification of time records may result in disciplinary action, up to and including termination</li><li>Employees are not authorized to perform work unless a shift has been formally assigned and accepted</li></ul><div class=\"sh\">Break and Meal Period Compliance</div><ul class=\"bl\"><li>One paid 10-minute rest break for every 4 hours worked or major fraction thereof</li><li>One unpaid 30-minute meal period for shifts exceeding 5 hours, unless legally waived</li><li>Second meal period provided for shifts exceeding 10 hours unless legally waived</li><li>Employees working solo posts or special assignments will be provided legally compliant on-duty meal periods when permitted by law and acknowledged in writing</li></ul><div class=\"sh\">Uniforms, Equipment, and Appearance Standards</div><ul class=\"bl\"><li>Employees must wear company-approved uniforms while on duty</li><li>Uniforms and equipment must be maintained in clean, professional condition</li><li>Any issued equipment must be returned upon separation of employment</li></ul><div class=\"sh\">Code of Conduct, Use of Force, Confidentiality, Drug-Free Workplace &amp; Safety</div><ul class=\"bl\"><li>Act professionally and courteously; follow post orders and client instructions; use de-escalation whenever possible</li><li>Use of force is permitted only when reasonable and necessary; all use-of-force incidents must be documented and reported immediately</li><li>Do not disclose confidential client or company information during or after employment</li><li>Hammer Head Security maintains a drug- and alcohol-free workplace; reporting to work under the influence is strictly prohibited</li><li>Follow all safety procedures; immediately report any workplace injury, accident, or unsafe condition; cooperate with workers’ compensation procedures</li></ul><div class=\"sh\">Separation of Employment</div><div class=\"pbox\"><p>Either the employee or Hammer Head Security may terminate employment at any time, with or without cause or notice, consistent with at-will employment under California law.</p></div><div class=\"notice\">Electronic Signature Acknowledgment: I agree that my electronic signature is legally equivalent to my handwritten signature under applicable federal and California law, including the ESIGN Act and the California Uniform Electronic Transactions Act (UETA). By signing electronically, I confirm that I have read, understood, and agreed to the terms of this policy, and that this acknowledgment is binding and enforceable to the same extent as a physical signature.</div><div class=\"sh\">Acknowledgment and Acceptance <span class=\"req\">*</span></div><div class=\"pbox\"><p>By signing, the employee confirms they understand this is a flexible / on-call job offer, they are not guaranteed permanent or full-time hours, and they agree to comply with all company policies, California labor laws, and BSIS regulations. This agreement represents the entire understanding regarding on-call employment and supersedes any prior verbal or written representations.</p></div><label class=\"ck\"><input type=\"checkbox\" name=\"f[offer_accept]\" required value=\"accept\"> I ACKNOWLEDGE AND ACCEPT THIS ON-CALL / AT-WILL JOB OFFER</label>"}};
const PHASES = { A: ["offer", "w4", "de4", "i9", "wotc", "emp_info", "emergency", "direct_dep", "bsis_lic", "bsis_tr", "meal1", "meal2", "on_duty", "meal_wv", "background", "uniform", "handbook", "drug1", "drug2", "drug3", "econsent"], B: ["safety_ob", "probation", "uof", "vehicle", "driver", "harassment", "notices"] };  // Phase B: add post-training form keys here

let hires=[{token:'a1b2c3',first:'Sara',middle:'',last:'Kaur',phone:'(209) 555-0142',email:'sarakaur1960@gmail.com',address:'128 Miner Ave',city:'Stockton',state:'CA',zip:'95202',guardCard:'GC1234567',guardCardExp:'2027-05-31',dl:'D2345678',dlExp:'2028-03-15',firearmsPermit:'No',position:'Security Officer',site:'Aivress Construction Site',hire:'2026-07-07',hireType:'New Hire',empStatus:'Full-Time',payRate:'22.00/hr',payFreq:'Weekly',hrRep:'Rachel Adams',eid:'5044',status:'A_done'},{token:'d4e5f6',first:'Marcus',middle:'',last:'Reyes',phone:'(209) 555-0198',email:'marcus.reyes.demo@example.com',address:'842 Pershing Ave',city:'Stockton',state:'CA',zip:'95204',guardCard:'GC7654321',guardCardExp:'2027-11-20',dl:'D9876543',dlExp:'2029-01-10',firearmsPermit:'No',position:'Security Officer',site:'Weston Ranch Patrol',hire:'2026-07-20',hireType:'New Hire',empStatus:'Full-Time',payRate:'21.50/hr',payFreq:'Weekly',hrRep:'Rachel Adams',eid:'5045',status:'New'},{token:'g7h8i9',first:'Priya',middle:'',last:'Nair',phone:'(209) 555-0233',email:'priya.nair.demo@example.com',address:'2210 Country Club Blvd',city:'Stockton',state:'CA',zip:'95207',guardCard:'GC1122334',guardCardExp:'2026-09-15',dl:'D5566778',dlExp:'2027-06-01',firearmsPermit:'Yes',position:'Lead Security Officer',site:'Downtown Office Tower',hire:'2026-06-15',hireType:'New Hire',empStatus:'Full-Time',payRate:'24.00/hr',payFreq:'Weekly',hrRep:'Rachel Adams',eid:'5046',status:'Training'}];
let editingToken=null;
let currentToken='a1b2c3', signature=null, view='hr', legendShown=false;
let dashFilter=null;
let wizStep=0, wizKeys=[], wizPhase='A', formSigs={}, sigKind='type', typedSig=null, drawnSig=null, signerName='';
const S={New:'New',A_sent:'Phase A sent',A_done:'Phase A done · I-9 §2 due',I9_done:'I-9 verified',Training:'Training complete',B_sent:'Phase B sent',Final:'Finalized'};
const $=id=>document.getElementById(id); const val=id=>{const e=$(id);return e?e.value:'';};
function toast(m){const t=$('toast');t.textContent=m;t.classList.add('show');setTimeout(()=>t.classList.remove('show'),2600);}
function badge(s){return '<span class="badge">'+(S[s]||s)+'</span>';}
// Formats any date string (ISO, YYYY-MM-DD, or a parseable date) as MM/DD/YYYY
// for consistent display across the HR console, I-9, and Forms tab.
// Converts a MM/DD/YYYY typed string back to YYYY-MM-DD for saving/storage —
// keeps every downstream date comparison, folder naming, and PDF field
// working exactly as before; only the on-screen typing format changes.
function mdyToIso(s){
  if(/^\d{4}-\d{2}-\d{2}$/.test(String(s||'').trim())) return String(s).trim();
  const m=String(s||'').trim().match(/^(\d{1,2})\/(\d{1,2})\/(\d{2}|\d{4})$/);
  if(!m) return '';
  const year=m[3].length===4 ? m[3] : (Number(m[3]) <= 69 ? '20'+m[3] : '19'+m[3]);
  return year+'-'+m[1].padStart(2,'0')+'-'+m[2].padStart(2,'0');
}
// Attaches a typing mask to a text input so it auto-formats as MM/DD/YYYY.
function attachDateMask(el){
  if(!el||el._masked) return; el._masked=true;
  el.addEventListener('input',function(){
    const digits=el.value.replace(/\D/g,'').slice(0,8);
    let formatted=digits.slice(0,2);
    if(digits.length>2) formatted+='/'+digits.slice(2,4);
    if(digits.length>4) formatted+='/'+digits.slice(4,8);
    el.value=formatted;
  });
}
// Native browser date controls are reliable inside the Apps Script iframe:
// unlike an overlaid hidden picker, the whole field and its icon are clickable.
function initNativeDateField(id){
  const el=$(id); if(!el||el._nativeDateInit) return; el._nativeDateInit=true;
  const current=String(el.value||'').trim();
  const iso=/^\d{4}-\d{2}-\d{2}$/.test(current) ? current : mdyToIso(current);
  el.type='date';
  el.removeAttribute('maxlength');
  el.removeAttribute('placeholder');
  if(iso) el.value=iso;
}
function initHybridDateField(id){
  const el=$(id); if(!el){console.warn('initHybridDateField: element not found:',id);return;} if(el._hybridInit) return; el._hybridInit=true;
  attachDateMask(el);
  const wrap=document.createElement('span');
  wrap.style.cssText='position:relative;display:inline-block;width:100%;';
  el.parentNode.insertBefore(wrap, el); wrap.appendChild(el);
  const hidden=document.createElement('input'); hidden.type='date';
  hidden.style.cssText='position:absolute;width:1px;height:1px;opacity:0;pointer-events:none;';
  wrap.appendChild(hidden);
  el.style.paddingRight='38px';
  const button=document.createElement('button'); button.type='button'; button.setAttribute('aria-label','Choose date from calendar'); button.textContent='📅';
  button.style.cssText='position:absolute;right:9px;top:50%;transform:translateY(-50%);border:0;background:transparent;padding:5px;cursor:pointer;font-size:14px;line-height:1;z-index:2;';
  wrap.appendChild(button);
  hidden.addEventListener('change',function(){ if(hidden.value){ el.value=fmtMDY(hidden.value); el.dispatchEvent(new Event('input',{bubbles:true})); el.dispatchEvent(new Event('change',{bubbles:true})); } });
  button.addEventListener('click',function(){ if(hidden.showPicker) try{hidden.showPicker();return;}catch(e){} hidden.focus();hidden.click(); });
}
// Adds a small calendar icon next to a masked MM/DD/YYYY text field. Clicking
// it opens a hidden native date picker; picking a date fills the text field
// in MM/DD/YYYY. Typing directly still works via attachDateMask above — both
// entry methods stay available, matching native <input type="date"> feel.
function initHybridDateFieldLegacy(id){
  const el=$(id); if(!el||el._hybridInit) return; el._hybridInit=true;
  attachDateMask(el);
  const wrap=document.createElement('span');
  wrap.style.cssText='position:relative;display:inline-block;width:100%;';
  el.parentNode.insertBefore(wrap, el); wrap.appendChild(el);
  const hidden=document.createElement('input'); hidden.type='date';
  hidden.style.cssText='position:absolute;right:6px;top:50%;transform:translateY(-50%);width:22px;height:22px;opacity:0;cursor:pointer;';
  wrap.appendChild(hidden);
  const icon=document.createElement('span'); icon.textContent='📅';
  icon.style.cssText='position:absolute;right:9px;top:50%;transform:translateY(-50%);pointer-events:none;font-size:13px;';
  wrap.appendChild(icon);
  el.style.paddingRight='32px';
  hidden.addEventListener('change',function(){ if(hidden.value){ el.value=fmtMDY(hidden.value); el.dispatchEvent(new Event('input',{bubbles:true})); el.dispatchEvent(new Event('change',{bubbles:true})); } });
  button.addEventListener('click',function(){ if(hidden.showPicker) try{hidden.showPicker();return;}catch(e){} hidden.focus();hidden.click(); });
}
function fmtMDY(d){
  if(!d) return '';
  let dt;
  const plainDate=typeof d==='string'&&d.match(/^(\d{4})-(\d{2})-(\d{2})$/);
  if(plainDate){ dt=new Date(+plainDate[1], +plainDate[2]-1, +plainDate[3]); }
  else { dt=new Date(d); }
  if(isNaN(dt.getTime())) return String(d);
  const mm=String(dt.getMonth()+1).padStart(2,'0');
  const dd=String(dt.getDate()).padStart(2,'0');
  return mm+'/'+dd+'/'+dt.getFullYear();
}
function fmtMDY2(d){
  if(!d) return '';
  let dt;
  const plainDate=typeof d==='string'&&d.match(/^(\d{4})-(\d{2})-(\d{2})$/);
  if(plainDate){ dt=new Date(+plainDate[1], +plainDate[2]-1, +plainDate[3]); }
  else { dt=new Date(d); }
  if(isNaN(dt.getTime())) return String(d);
  const mm=String(dt.getMonth()+1).padStart(2,'0');
  const dd=String(dt.getDate()).padStart(2,'0');
  return mm+'/'+dd+'/'+dt.getFullYear();
}
// Formats a signature timestamp as MM/DD/YYYY, HH:MM:SS — used instead of
// toLocaleString() so the date always displays in US order regardless of
// the browser/OS locale (toLocaleString() was rendering DD/MM/YYYY on some
// systems).
function fmtMDYDateTime(ts){
  const d=new Date(ts);
  if(isNaN(d.getTime())) return String(ts);
  const mm=String(d.getMonth()+1).padStart(2,'0');
  const dd=String(d.getDate()).padStart(2,'0');
  const yyyy=d.getFullYear();
  const hh=String(d.getHours()).padStart(2,'0');
  const mi=String(d.getMinutes()).padStart(2,'0');
  const ss=String(d.getSeconds()).padStart(2,'0');
  return mm+'/'+dd+'/'+yyyy+', '+hh+':'+mi+':'+ss;
}
function hire(){return hires.find(h=>h.token===currentToken)||hires[0];}
function newToken(){return Math.random().toString(36).slice(2,10);}
async function save(action,payload){
  if(!APPS_SCRIPT_URL){console.log('[DEMO]',action,payload);return {ok:true,demo:true};}
  try{const r=await fetch(APPS_SCRIPT_URL,{method:'POST',body:JSON.stringify({action,...payload})});return await r.json();}
  catch(e){console.error(e);toast('Save failed — check the script URL');return{ok:false};}
}
async function apiGet(action,params){
  if(!APPS_SCRIPT_URL)return null;
  try{const qs=new URLSearchParams(Object.assign({action:action,_ts:Date.now()},params||{})).toString();
    const r=await fetch(APPS_SCRIPT_URL+'?'+qs,{cache:'no-store'});
    if(!r.ok){ toast('Server returned '+r.status+' — check you\'re signed in / deployment access'); return null; }
    return await r.json();}
  catch(e){console.error(e); toast('Could not reach the server — check sign-in / deployment access'); return null;}
}
let pdfLibPromise=null;
function loadPdfLib(){
  if(window.PDFLib)return Promise.resolve(window.PDFLib);
  if(pdfLibPromise)return pdfLibPromise;
  pdfLibPromise=new Promise(function(resolve,reject){const s=document.createElement('script');s.src='https://cdn.jsdelivr.net/npm/pdf-lib@1.17.1/dist/pdf-lib.min.js';s.onload=function(){resolve(window.PDFLib);};s.onerror=function(){reject(new Error('PDF form library could not be loaded'));};document.head.appendChild(s);});
  return pdfLibPromise;
}
function pdfValue(v){return String(v==null?'':v).replace(/[\r\n]+/g,' ').trim();}
function pdfSetText(form,name,value){try{if(pdfValue(value))form.getTextField(name).setText(pdfValue(value));}catch(e){console.warn('PDF field not found or wrong type — no data written:', JSON.stringify(name));}}
function pdfCheck(form,name,on){try{if(on)form.getCheckBox(name).check();}catch(e){console.warn('PDF checkbox not found — no box checked:', JSON.stringify(name));}}
function pdfSelect(form,name,value){const v=pdfValue(value);if(!v)return;try{form.getDropdown(name).select(v);}catch(e){try{form.getDropdown(name).select(v.toUpperCase());}catch(e2){console.warn('PDF dropdown not found or invalid option — no selection made:', JSON.stringify(name), JSON.stringify(value));}}}
function pdfMark(page,x,y,on){if(on)page.drawText('X',{x:x,y:y,size:9});}
function pdfDraw(page,x,y,value,size){const text=pdfValue(value);if(text)page.drawText(text,{x:x,y:y,size:size||8});}
function pdfYN(page,value,yesX,noX,y){const v=pdfValue(value).toLowerCase();if(v==='yes')page.drawText('X',{x:yesX,y:y,size:8});else if(v==='no')page.drawText('X',{x:noX,y:y,size:8});}
function pdfSSN(page,x1,x2,x3,y,value){const digits=pdfValue(value).replace(/[^0-9]/g,'');if(!digits)return;const pitch=12.5;for(let i=0;i<3&&i<digits.length;i++)page.drawText(digits[i],{x:x1+i*pitch,y:y,size:8});for(let i=3;i<5&&i<digits.length;i++)page.drawText(digits[i],{x:x2+(i-3)*pitch,y:y,size:8});for(let i=5;i<9&&i<digits.length;i++)page.drawText(digits[i],{x:x3+(i-5)*pitch,y:y,size:8});}
// Draws one digit per box directly onto the page (not into the AcroForm
// field) for forms with a single 9-cell "comb" SSN box, like the I-9. This
// avoids relying on the PDF viewer to regenerate the comb field's own
// appearance stream, which some viewers render inconsistently.
function pdfSSNComb(page,x,y,width,value){const digits=pdfValue(value).replace(/[^0-9]/g,'');if(!digits)return;const pitch=width/9;for(let i=0;i<9&&i<digits.length;i++)page.drawText(digits[i],{x:x+i*pitch+pitch/2-3,y:y,size:9});}
async function pdfSig(doc,page,sig,x,y,maxW,maxH){
  if(!sig)return;
  try{
    if(sig.kind==='draw'&&sig.data&&sig.data.indexOf('data:image')===0){
      const img=await doc.embedPng(sig.data);
      const scale=Math.min(maxW/img.width,maxH/img.height,1);
      page.drawImage(img,{x:x,y:y,width:img.width*scale,height:img.height*scale});
    }else{
      const font=await doc.embedFont(PDFLib.StandardFonts.TimesRomanItalic);
      page.drawText(pdfValue(sig.data||sig.name),{x:x,y:y,size:11,font:font});
    }
  }catch(e){console.warn('Signature could not be drawn',e);}
}
function pdfSigDate(page,sig,x,y){if(!sig||!sig.ts)return;try{const d=new Date(sig.ts);if(isNaN(d))return;page.drawText(fmtMDY2(d),{x:x,y:y,size:9});}catch(e){}}
function employerSignatureName(value){return pdfValue(value).replace(/\s*[—-]\s*HR Representative\s*$/i,'');}
function valueForPdf(h,f,key){return (f&&f[key])||h[key]||'';}
async function loadPdfTemplate(key){const r=await apiGet('template',{template:key});if(!r||!r.ok)throw new Error((r&&r.error)||'Unable to load blank PDF template');return r.base64;}
async function fillOfficialPdf(key,title,h,fields,section2){
  const PDFLib=await loadPdfLib();const b64=await loadPdfTemplate(key);const doc=await PDFLib.PDFDocument.load(PDFLib.decodeFromBase64(b64),{ignoreEncryption:true});const pages=doc.getPages();const form=doc.getForm();
  const first=pdfValue(h.first),last=pdfValue(h.last),full=(first+' '+last).trim(),addr=pdfValue(h.address),csz=[h.city,h.state,h.zip].filter(Boolean).join(', ');
  if(key==='w4'){
    pdfSetText(form,'topmostSubform[0].Page1[0].Step1a[0].f1_01[0]',valueForPdf(h,fields,'w4_first')||first);
    pdfSetText(form,'topmostSubform[0].Page1[0].Step1a[0].f1_02[0]',valueForPdf(h,fields,'w4_last')||last);
    pdfSetText(form,'topmostSubform[0].Page1[0].Step1a[0].f1_03[0]',valueForPdf(h,fields,'w4_address')||addr);
    pdfSetText(form,'topmostSubform[0].Page1[0].Step1a[0].f1_04[0]',valueForPdf(h,fields,'w4_csz')||csz);
    pdfSetText(form,'topmostSubform[0].Page1[0].f1_05[0]',valueForPdf(h,fields,'w4_ssn'));
    pdfSetText(form,'topmostSubform[0].Page1[0].Step3_ReadOrder[0].f1_06[0]',valueForPdf(h,fields,'w4_children'));
    pdfSetText(form,'topmostSubform[0].Page1[0].Step3_ReadOrder[0].f1_07[0]',valueForPdf(h,fields,'w4_other'));
    pdfSetText(form,'topmostSubform[0].Page1[0].f1_08[0]',valueForPdf(h,fields,'w4_dep_total'));
    pdfSetText(form,'topmostSubform[0].Page1[0].f1_09[0]',valueForPdf(h,fields,'w4_4a'));
    pdfSetText(form,'topmostSubform[0].Page1[0].f1_10[0]',valueForPdf(h,fields,'w4_4b'));
    pdfSetText(form,'topmostSubform[0].Page1[0].f1_11[0]',valueForPdf(h,fields,'w4_4c'));
    const filing=valueForPdf(h,fields,'w4_filing');
    try{
      if(filing==='single')form.getCheckBox('topmostSubform[0].Page1[0].c1_1[0]').check();
      else if(filing==='married')form.getCheckBox('topmostSubform[0].Page1[0].c1_1[1]').check();
      else if(filing==='hoh')form.getCheckBox('topmostSubform[0].Page1[0].c1_1[2]').check();
    }catch(e){console.warn('W-4 filing status checkbox not found',e);}
    pdfSetText(form,'topmostSubform[0].Page1[0].f1_12[0]',(section2&&section2.employer_name_address)||(h.companyName?h.companyName+(COMPANIES[h.companyName]&&COMPANIES[h.companyName].address?', '+COMPANIES[h.companyName].address:''):'Hammer Head Security, 4551 South B Street, Stockton, CA 95206'));
    pdfSetText(form,'topmostSubform[0].Page1[0].f1_13[0]',fmtMDY2((section2&&section2.first_day)||h.hire||''));
    pdfSetText(form,'topmostSubform[0].Page1[0].f1_14[0]',(section2&&section2.employer_ein)||h.ein||'');
    const w4sig=(h.formSigs&&h.formSigs['w4'])||{kind:'type',data:full||h.signerName,name:full||h.signerName};
    await pdfSig(doc,pages[0],w4sig,105,93,220,16);
    pdfSigDate(pages[0],w4sig,465,93);
  } else if(key==='de4'){
    pdfSetText(form,'Name 1',valueForPdf(h,fields,'de4_name')||full);pdfSetText(form,'Social Security Number 1',valueForPdf(h,fields,'de4_ssn'));pdfSetText(form,'Address 1',valueForPdf(h,fields,'de4_address')||addr);pdfSetText(form,'City',valueForPdf(h,fields,'de4_city')||h.city);pdfSetText(form,'State',valueForPdf(h,fields,'de4_state')||h.state);pdfSetText(form,'ZIP Code',valueForPdf(h,fields,'de4_zip')||h.zip);
    pdfSetText(form,'1a',valueForPdf(h,fields,'de4_1a'));pdfSetText(form,'1b',valueForPdf(h,fields,'de4_1b'));pdfSetText(form,'1c',valueForPdf(h,fields,'de4_1c'));pdfSetText(form,'2',valueForPdf(h,fields,'de4_2'));pdfSetText(form,"Employer's Name and Address",(section2&&section2.employer_business_name)||h.companyName||'');pdfSetText(form,'California Employer Payroll Tax Account Number',(section2&&section2.ca_payroll_acct)||'');
    // The DE 4 name/address widget retains only its first line when flattened.
    // Draw the company address on the next official line so it is never lost.
    pdfDraw(pages[0],41,311,(section2&&section2.employer_address)||'');
    const filing=valueForPdf(h,fields,'de4_filing');pdfMark(pages[0],313,filing==='single_two'?611:filing==='married_one'?599:587,true);pdfMark(pages[0],570,480,!!valueForPdf(h,fields,'de4_exempt3'));pdfMark(pages[0],570,432,!!valueForPdf(h,fields,'de4_exempt4'));
    const de4sig=(h.formSigs&&h.formSigs['de4'])||{kind:'type',data:full||h.signerName,name:full||h.signerName};
    await pdfSig(doc,pages[0],de4sig,140,375,150,16);
    // Draw the original signing date at the official DE 4 date line. Some
    // template editions omit the AcroForm date field.
    pdfSigDate(pages[0],de4sig,465,375);
  } else if(key==='i9'){
    pdfSetText(form,'Last Name (Family Name)',valueForPdf(h,fields,'last_name_family_name')||last);pdfSetText(form,'First Name Given Name',valueForPdf(h,fields,'first_name_given_name')||first);pdfSetText(form,'Employee Middle Initial (if any)',valueForPdf(h,fields,'middle_initial_if_any')||h.middle);pdfSetText(form,'Employee Other Last Names Used (if any)',valueForPdf(h,fields,'other_last_names_used_if_any'));
    pdfSetText(form,'Address Street Number and Name',valueForPdf(h,fields,'address_street_number_and_name')||addr);pdfSetText(form,'Apt Number (if any)',valueForPdf(h,fields,'apt_number_if_any'));pdfSetText(form,'City or Town',valueForPdf(h,fields,'city_or_town')||h.city);pdfSelect(form,'State',valueForPdf(h,fields,'state')||h.state);pdfSetText(form,'ZIP Code',valueForPdf(h,fields,'zip_code')||h.zip);pdfSetText(form,'Date of Birth mmddyyyy',fmtMDY2(valueForPdf(h,fields,'date_of_birth')||valueForPdf(h,fields,'date_of_birth_mm_dd_yyyy')));const i9ssn=valueForPdf(h,fields,'u_s_social_security_number')||valueForPdf(h,fields,'w4_ssn')||valueForPdf(h,fields,'de4_ssn')||valueForPdf(h,fields,'wotc_ssn');pdfSSNComb(pages[0],150,556.9,105,i9ssn);pdfSetText(form,'Employees E-mail Address',valueForPdf(h,fields,'s_email_address_e_em_true')||h.email);pdfSetText(form,'Telephone Number',valueForPdf(h,fields,'s_telephone_number_e_ph_true')||h.phone);
    const cit=valueForPdf(h,fields,'i9cit');pdfCheck(form,'CB_1',cit==='us');pdfCheck(form,'CB_2',cit==='natl');pdfCheck(form,'CB_3',cit==='lpr');pdfCheck(form,'CB_4',cit==='alien');
    // A lawful permanent resident's A-number appears only on line 3. The
    // lower A-number, I-94, and passport fields are for line 4 only.
    pdfSetText(form,'3 A lawful permanent resident Enter USCIS or ANumber',cit==='lpr'?valueForPdf(h,fields,'uscis_a_number_if_applicable'):'');
    pdfSetText(form,'USCIS ANumber',cit==='alien'?valueForPdf(h,fields,'uscis_a_number_if_applicable'): '');
    pdfSetText(form,'Form I94 Admission Number',cit==='alien'?valueForPdf(h,fields,'form_i_94_admission_number_if_applicable'): '');
    pdfSetText(form,'Foreign Passport Number and Country of IssuanceRow1',cit==='alien'?[valueForPdf(h,fields,'foreign_passport_number_if_applicable'),valueForPdf(h,fields,'country_of_issuance_if_passport_used')].filter(Boolean).join(' / '): '');
    pdfSetText(form,'Exp Date mmddyyyy',fmtMDY2(valueForPdf(h,fields,'i9_exp_date')));
    const a=section2||{}, rep=employerSignatureName(a.employer_rep||h.hrRep||'');pdfSetText(form,'Document Title 1',a.doc_path==='A'?a.listA_title:'');pdfSetText(form,'Issuing Authority 1',a.doc_path==='A'?a.listA_auth:'');pdfSetText(form,'Document Number 0 (if any)',a.doc_path==='A'?a.listA_num:'');pdfSetText(form,'Expiration Date if any',a.doc_path==='A'?fmtMDY2(a.listA_exp):'');pdfSetText(form,'List B Document 1 Title',a.doc_path==='BC'?a.listB_title:'');pdfSetText(form,'List B Issuing Authority 1',a.doc_path==='BC'?a.listB_auth:'');pdfSetText(form,'List B Document Number 1',a.doc_path==='BC'?a.listB_num:'');pdfSetText(form,'List B Expiration Date 1',a.doc_path==='BC'?fmtMDY2(a.listB_exp):'');pdfSetText(form,'List C Document Title 1',a.doc_path==='BC'?a.listC_title:'');pdfSetText(form,'List C Issuing Authority 1',a.doc_path==='BC'?a.listC_auth:'');pdfSetText(form,'List C Document Number 1',a.doc_path==='BC'?a.listC_num:'');pdfSetText(form,'List C Expiration Date 1',a.doc_path==='BC'?fmtMDY2(a.listC_exp):'');pdfSetText(form,'Additional Information',a.additional_info||'');pdfSetText(form,'FirstDayEmployed mmddyyyy',fmtMDY2(a.first_day||h.hire));pdfSetText(form,'Last Name First Name and Title of Employer or Authorized Representative',rep);pdfSetText(form,'Employers Business or Org Name',a.employer_business_name||'Hammer Head Security');pdfSetText(form,'Employers Business or Org Address',a.employer_name_address||a.employer_address||'');
    await pdfSig(doc,pages[0],{kind:'type',data:rep,name:rep},306,88,190,16);
    pdfSetText(form,"S2 Todays Date mmddyyyy",fmtMDY2(new Date()));
    const i9sig=(h.formSigs&&h.formSigs['i9'])||{kind:'type',data:full||h.signerName,name:full||h.signerName};
    await pdfSig(doc,pages[0],i9sig,150,431,205,16);
    pdfSigDate(pages[0],i9sig,525,431);
    } else if(key==='wotc'){
    const dob=fmtMDY2(valueForPdf(h,fields,'date_of_birth')||valueForPdf(h,fields,'date_of_birth_mm_dd_yyyy')||valueForPdf(h,fields,'wotc_dob_u40'));const p=pages[0];pdfDraw(p,90,669,valueForPdf(h,fields,'wotc_name')||full);pdfDraw(p,468,669,valueForPdf(h,fields,'wotc_ssn'));pdfDraw(p,160,645,valueForPdf(h,fields,'wotc_street')||addr);pdfDraw(p,175,621,valueForPdf(h,fields,'wotc_csz')||csz);pdfDraw(p,95,597,valueForPdf(h,fields,'wotc_county'));pdfDraw(p,470,597,valueForPdf(h,fields,'wotc_phone')||h.phone);pdfDraw(p,330,573,dob);
    // --- Page 1 checkboxes: only boxes 1, 2, 6, 7 have a verified 1:1 mapping to a single UI checkbox.
    // Boxes 3/4/5 are veteran eligibility determinations requiring IRS instruction logic not yet verified — left unmarked intentionally.
    if(valueForPdf(h,fields,'wotc_box1'))p.drawText('X',{x:68,y:539,size:8});
    if(valueForPdf(h,fields,'wotc_box2'))p.drawText('X',{x:68,y:503,size:8});
    if(valueForPdf(h,fields,'wotc_box6'))p.drawText('X',{x:68,y:215,size:8});
    if(valueForPdf(h,fields,'wotc_box7'))p.drawText('X',{x:68,y:131,size:8});
    const wotcsig=(h.formSigs&&h.formSigs['wotc'])||{kind:'type',data:full||h.signerName,name:full||h.signerName};
    await pdfSig(doc,p,wotcsig,165,36,220,16);
    pdfSigDate(p,wotcsig,495,36);
    // --- Page 2 (WOTC.com screening worksheet): coordinates verified against the real template, not guessed.
    const p2=pages[1];
    pdfDraw(p2,324,760,valueForPdf(h,fields,'wotc_company'));
    pdfDraw(p2,350,744,valueForPdf(h,fields,'wotc_ein'));
    pdfYN(p2,valueForPdf(h,fields,'wotc_q_rehire'),508,557,707);
    pdfYN(p2,valueForPdf(h,fields,'wotc_q_u40'),510,558,686);
    pdfYN(p2,valueForPdf(h,fields,'wotc_q_ui27'),511,559,663);
    pdfYN(p2,valueForPdf(h,fields,'wotc_q_vet'),511,558,641);
    pdfYN(p2,valueForPdf(h,fields,'wotc_q_vet_snap'),406,453,614);
    pdfYN(p2,valueForPdf(h,fields,'wotc_q_vet_disab'),406,454,601);
    pdfYN(p2,valueForPdf(h,fields,'wotc_q_vet_disch'),406,455,587);
    pdfYN(p2,valueForPdf(h,fields,'wotc_q_vet_unemp6'),408,455,574);
    pdfYN(p2,valueForPdf(h,fields,'wotc_q_snap6'),516,558,555);
    pdfYN(p2,valueForPdf(h,fields,'wotc_q_snap3'),517,558,542);
    pdfDraw(p2,295,531,valueForPdf(h,fields,'wotc_snap_recip'));
    pdfDraw(p2,300,515,valueForPdf(h,fields,'wotc_snap_city'));
    pdfYN(p2,valueForPdf(h,fields,'wotc_q_tanf18'),517,559,493);
    pdfYN(p2,valueForPdf(h,fields,'wotc_q_tanf_end'),520,559,467);
    pdfDraw(p2,295,456,valueForPdf(h,fields,'wotc_tanf_recip'));
    pdfDraw(p2,300,442,valueForPdf(h,fields,'wotc_tanf_city'));
    pdfYN(p2,valueForPdf(h,fields,'wotc_q_ssi'),518,557,404);
    pdfYN(p2,valueForPdf(h,fields,'wotc_q_felony'),517,558,381);
    pdfYN(p2,valueForPdf(h,fields,'wotc_q_ref_voc'),513,554,345);
    pdfYN(p2,valueForPdf(h,fields,'wotc_q_ref_ticket'),514,555,331);
    pdfYN(p2,valueForPdf(h,fields,'wotc_q_ref_va'),515,555,317);
    pdfDraw(p2,16,280,valueForPdf(h,fields,'wotc_print_name')||full);
    pdfSSN(p2,237,306,347,280,valueForPdf(h,fields,'wotc_p2_ssn')||valueForPdf(h,fields,'wotc_ssn'));
    pdfDraw(p2,426,280,dob);
    pdfDraw(p2,182,146,fmtMDY2(valueForPdf(h,fields,'wotc_start')||h.hire));
    pdfDraw(p2,329,146,valueForPdf(h,fields,'wotc_wage')||payRateAmt(h));
    pdfDraw(p2,434,146,valueForPdf(h,fields,'wotc_position')||h.position);
    await pdfSig(doc,p2,wotcsig,145,124,185,16);
    pdfSigDate(p2,wotcsig,410,124);
  }
  try{form.flatten();}catch(e){};return {title:title,base64:await doc.saveAsBase64({dataUri:false})};
}
async function createOfficialPdfs(h){
  const f=h.phaseA_fields||h.fields||{},s=h.i9_section2||{};
  const specs=[['wotc','Form 8850 (WOTC)'],['de4','Form DE 4'],['w4','Form W-4'],['i9','Form I-9']];
  const errors=[];
  const results=await Promise.all(specs.map(async function(spec){
    try{ return await fillOfficialPdf(spec[0],spec[1],h,f,s); }
    catch(err){ console.error('Official PDF generation failed for '+spec[1], err); errors.push(spec[1]+': '+((err&&err.message)||err)); return null; }
  }));
  const completed=results.filter(Boolean);
  if(completed.length<specs.length){
    toast('Some government forms could not be generated — '+errors.join(' | '));
  }
  return completed;
}
async function loadAllHires(){
  const res=await apiGet('list',{});
  if(res&&res.ok&&Array.isArray(res.hires)){
    // De-duplicate by token only. Email is NOT used here — multiple real,
    // distinct hires can legitimately share the same email address (shared
    // test inboxes, family accounts, etc.), so merging by email would hide
    // genuinely separate people. Token is the one truly unique identifier.
    const byToken={};
    res.hires.forEach(function(h){
      const t=h.token;
      if(!t){return;}
      const existing=byToken[t];
      if(!existing || String(h.updatedAt||'') > String(existing.updatedAt||'')) byToken[t]=h;
    });
    hires=Object.values(byToken);
  }
  return res;
}
async function loadHireByToken(token){const res=await apiGet('get',{token:token});return(res&&res.ok&&res.hire)?res.hire:null;}
// ---- Deleted (S2) — separate in-memory list, only fetched when the
// Deleted tab is opened. Does not affect `hires` (active list) at all.
let deletedHires=[];
async function loadDeletedHires(){
  const res=await apiGet('list',{scope:'deleted'});
  deletedHires=(res&&res.ok&&Array.isArray(res.hires))?res.hires:[];
  return res;
}
async function deleteHire(token){
  if(!confirm('Remove this hire from the active list? Their record, documents, and government forms are kept and can be found in the Deleted tab.'))return;
  const res=await save('deleteHire',{token:token});
  if(res&&res.ok){
    hires=hires.filter(function(h){return h.token!==token;});
    toast('Moved to Deleted');
    render();
  }else{
    toast('Could not remove hire'+((res&&res.error)?(': '+res.error):''));
  }
}
// Mirror of deleteHire() above — only ever moves a hire the opposite
// direction (Deleted -> active). Same record, same token, nothing else
// touched; all phase/I-9/document/gov-form data was never affected by
// deletion in the first place, so there's nothing to restore there.
async function restoreHire(token){
  if(!confirm('Restore this hire to the active New Hires list?'))return;
  const res=await save('restoreHire',{token:token});
  if(res&&res.ok){
    deletedHires=deletedHires.filter(function(h){return h.token!==token;});
    toast('Restored to New Hires');
    render();
  }else{
    toast('Could not restore hire'+((res&&res.error)?(': '+res.error):''));
  }
}
async function refreshHires(){
  if(!APPS_SCRIPT_URL){toast('Demo mode — connect Apps Script to sync');return;}
  const res=await loadAllHires();
  if(!res||!res.ok){toast('Refresh failed — check the Apps Script deployment/URL');return;}
  render();toast('Refreshed from Google Sheet ('+hires.length+' hire'+(hires.length===1?'':'s')+')');
}
// Auto-refresh internal staff views periodically so newly-submitted forms
// and status changes show up without anyone needing to click Refresh — but
// only when it's safe to do so (an internal view is active, not applicant-
// locked, and no edit form currently open).
setInterval(async function(){
  if(APPLICANT_TOKEN)return; // applicants never auto-poll
  if(view!=='hr'&&view!=='forms')return; // 'i9' excluded: auto-refresh would wipe unsaved in-progress I-9 entries
  const addForm=$('addForm'); if(addForm&&!addForm.classList.contains('hide'))return; // don't disrupt HR mid-edit
  if(!APPS_SCRIPT_URL)return;
  const res=await loadAllHires();
  if(res&&res.ok){
    const addForm2=$('addForm'); if(!addForm2||addForm2.classList.contains('hide')) render();
  }
}, 20000);
function i9Switch(v){
  document.querySelectorAll('.i9-panel').forEach(function(p){p.style.display='none';});
  const el=document.getElementById('i9p-'+v);if(el)el.style.display='block';
  const form=$('obform'); if(form) form.querySelectorAll('input,select,textarea').forEach(reapplyFieldStyle);
}
function styleRequiredOptional(){
  const form=$('obform'); if(!form) return;
  form.querySelectorAll('input[name^="f["],textarea[name^="f["]').forEach(function(el){
    if(el.type==='checkbox'||el.type==='radio') return;
    if(el.readOnly||el.disabled) return;
    if(el.classList.contains('prefilled')) return;
    el.classList.add(el.hasAttribute('required')?'fi-req':'fi-opt');
  });
  form.querySelectorAll('input[type="radio"],input[type="checkbox"]').forEach(function(el){
    const label=el.closest('label'); if(!label) return;
    if(label.classList.contains('req-choice')||label.classList.contains('opt-choice')) return;
    label.classList.add(el.hasAttribute('required')?'req-choice':'opt-choice');
  });
}
function showColorLegend(){
  const div=document.createElement('div'); div.className='modal-overlay'; div.id='legendModal';
  div.innerHTML='<div class="modal-box"><h3 style="margin:0 0 10px;">Before you sign</h3>'+
    '<div class="muted" style="margin-bottom:14px;">You will go through your forms one at a time. On each form, two colors mark what needs your attention:</div>'+
    '<div style="margin-bottom:10px;"><span class="legend-chip"><span class="legend-swatch" style="background:#dcfce7;border-color:#22c55e;"></span><b>Green</b> - mandatory — must be filled before you can submit</span></div>'+
    '<div style="margin-bottom:16px;"><span class="legend-chip"><span class="legend-swatch" style="background:#fef9c3;border-color:#fde047;"></span><b>Yellow</b> - optional — fill in only if it applies to you</span></div>'+
    '<div style="margin-bottom:16px;"><span class="legend-chip"><span class="legend-swatch" style="background:#e5e7eb;border-color:#9ca3af;"></span><b>Grey</b> - already filled in for you</span></div>'+
    '<div class="muted" style="margin-bottom:14px;">Read each form, fill anything mandatory, then sign it before moving on with <b>Next</b>. Use the floating <b>Next required field</b> button to jump to anything mandatory you have not filled in yet.</div>'+
    '<button type="button" class="btn" onclick="closeLegend()">Got it</button></div>';
  document.body.appendChild(div);
}
function closeLegend(){const m=$('legendModal'); if(m) m.remove();}
function nextRequiredField(){
  const steps=[].slice.call(document.querySelectorAll('.wizstep')); const form=steps[wizStep]; if(!form) return;
  const req=[...form.querySelectorAll('[required]')];
  const seen=new Set();
  const missing=req.filter(function(el){
    if(el.type==='radio'){
      if(seen.has(el.name)) return false; seen.add(el.name);
      return ![...form.querySelectorAll('input[name="'+el.name+'"]')].some(function(r){return r.checked;});
    }
    if(el.type==='checkbox') return !el.checked;
    return !el.value;
  });
  if(missing.length===0){toast('All mandatory fields are complete ✓');return;}
  const active=document.activeElement;
  const activeIdx=active&&req.indexOf(active)>=0?req.indexOf(active):-1;
  let next=missing.find(function(el){return req.indexOf(el)>activeIdx;})||missing[0];
  next.scrollIntoView({behavior:'smooth',block:'center'});
  if(typeof next.focus==='function') next.focus({preventScroll:true});
  toast(missing.length+' mandatory field'+(missing.length===1?'':'s')+' left');
}
function updateFieldRequiredStyle(el){
  if(!el||!el.classList) return;
  if(el.type==='radio'||el.type==='checkbox'){
    if(!el.hasAttribute('required')) return;
    const label=el.closest('label'); if(!label) return;
    const form=$('obform');
    const satisfied=el.type==='checkbox'?el.checked:(form&&[...form.querySelectorAll('input[name="'+el.name+'"]')].some(function(r){return r.checked;}));
    label.classList.toggle('req-choice', !satisfied);
  } else {
    if(!el.hasAttribute('required')) return;
    if(el.value){ el.classList.remove('fi-req'); el.classList.add('prefilled'); }
    else { el.classList.remove('prefilled'); el.classList.add('fi-req'); }
  }
}
function wotcAutoBoxes(){
  var f=$('obform'); if(!f) return;
  function yes(n){var el=f.querySelector('input[name="f['+n+']"][value="yes"]');return !!(el&&el.checked);}
  function setBox(n,on){var c=f.querySelector('input[name="f['+n+']"]');if(c){c.checked=on;var lb=c.closest('label');if(lb)lb.style.background=on?'#dcfce7':'';}}
  var box2 = yes('wotc_q_felony')||yes('wotc_q_ssi')||yes('wotc_q_ref_voc')||yes('wotc_q_ref_ticket')||yes('wotc_q_ref_va')||(yes('wotc_q_u40')&&(yes('wotc_q_snap6')||yes('wotc_q_snap3')))||(yes('wotc_q_vet')&&yes('wotc_q_vet_snap'))||(yes('wotc_q_vet')&&yes('wotc_q_vet_unemp6'));
  var box6 = yes('wotc_q_tanf18')||yes('wotc_q_tanf_end');
  var box7 = yes('wotc_q_ui27');
  setBox('wotc_box2',box2); setBox('wotc_box6',box6); setBox('wotc_box7',box7);
}
function reapplyFieldStyle(el){
  if(!el||!el.classList) return;
  if(el.type==='radio'||el.type==='checkbox'){
    const label=el.closest('label'); if(!label) return;
    label.classList.remove('req-choice','opt-choice');
    const req=el.hasAttribute('required'); const form=$('obform');
    const satisfied=el.type==='checkbox'?el.checked:(form&&[].slice.call(form.querySelectorAll('input[name="'+el.name+'"]')).some(function(r){return r.checked;}));
    if(req&&!satisfied) label.classList.add('req-choice'); else if(!req) label.classList.add('opt-choice');
  } else {
    el.classList.remove('fi-req','fi-opt','prefilled');
    if(el.hasAttribute('required')) el.classList.add(el.value?'prefilled':'fi-req'); else el.classList.add('fi-opt');
  }
}
function ddToggle(v){
  const form=$('obform'); if(!form) return; const on=(v==='yes');
  ['f[accttype]','f[bank_name]','f[routing_number]','f[account_number]'].forEach(function(nm){
    form.querySelectorAll('[name="'+nm+'"]').forEach(function(el){
      if(on) el.setAttribute('required',''); else el.removeAttribute('required');
      reapplyFieldStyle(el);
    });
  });
}

/* =====================================================================
   AUTO-FILL: live mirroring of shared fields across every step of the
   wizard (Phase A and Phase B), since every step lives inside the same
   single <form id="obform">. Listening at the form level lets us sync
   ANY field, on ANY step, to every other field that represents the
   same real-world value (name, phone, email, address, SSN, DOB, etc.)
   ===================================================================== */

const MIRROR_GROUPS = [
  ['employee_name','applicant_name','wotc_name','de4_name'],
  ['first_name_given_name'],
  ['last_name_family_name'],
  ['middle_initial_if_any'],
  ['phone_number','primary_phone','s_telephone_number_e_ph_true','wotc_phone','phone'],
  ['email_address','email','s_email_address_e_em_true'],
  ['address','address_street_number_and_name','wotc_street','w4_address','de4_address'],
  ['city','city_or_town','de4_city'],
  ['state','de4_state'],
  ['zip','zip_code','de4_zip'],
  ['employee_id'],
  ['position','job_title','wotc_position'],
  ['work_location_site'],
  ['date'],
  ['date_of_hire','start_date','wotc_start'],
  ['bsis_guard_card'],
  ['guard_card_expiry'],
  ['s_license_e_dln_e_dln'],
  ['dl_expiry'],
  ['employer_representative','employer_representative_name','company_representative','manager_representative'],
  // DOB / SSN kept as their own groups (previously handled by data-mirror only)
  ['date_of_birth','date_of_birth_mm_dd_yyyy','wotc_dob_u40','wotc_p2_dob'],
  ['u_s_social_security_number','w4_ssn','de4_ssn','wotc_ssn','wotc_p2_ssn'],
];

// key -> groupIndex lookup, built once
const MIRROR_KEY_TO_GROUP = {};
MIRROR_GROUPS.forEach(function(group, gi){
  group.forEach(function(key){ MIRROR_KEY_TO_GROUP[key] = gi; });
});

function extractFKey(el){
  if(!el || !el.name) return null;
  const m = el.name.match(/^f\[(.+)\]$/);
  return m ? m[1] : null;
}

function mirrorGroupSync(sourceEl){
  const form = $('obform'); if(!form) return;
  const key = extractFKey(sourceEl); if(!key) return;
  const gi = MIRROR_KEY_TO_GROUP[key];
  if(gi === undefined) return; // not a mirrored field
  const value = sourceEl.value;
  MIRROR_GROUPS[gi].forEach(function(otherKey){
    form.querySelectorAll('[name="f['+otherKey+']"]').forEach(function(el){
      if(el === sourceEl) return;
      if(el.type === 'checkbox' || el.type === 'radio') return; // only sync plain text/date/number fields
      if(el.value !== value){
        el.value = value;
        updateFieldRequiredStyle(el);
      }
    });
  });
}

function initMirror(){
  const form = $('obform'); if(!form) return;
  form.addEventListener('input', function(e){
    // legacy data-mirror support (dob/ssn attribute-based, kept for compatibility)
    const g = e.target.getAttribute && e.target.getAttribute('data-mirror');
    if(g){
      form.querySelectorAll('[data-mirror="'+g+'"]').forEach(function(el){
        if(el !== e.target){ el.value = e.target.value; updateFieldRequiredStyle(el); }
      });
    }
    // new generalized group-based mirroring across every f[] field
    mirrorGroupSync(e.target);
    updateFieldRequiredStyle(e.target);
  });
  form.addEventListener('change', function(e){
    updateFieldRequiredStyle(e.target);
    mirrorGroupSync(e.target);
    if(e.target.name && e.target.name.indexOf('wotc_q') >= 0) wotcAutoBoxes();
  });
}

function prefillSavedFields(fields){if(!fields)return;document.querySelectorAll('#obform [name]').forEach(function(el){const m=el.name.match(/^f\[(.+)\]$/);if(!m)return;const key=m[1];if(!(key in fields))return;const v=fields[key];if(el.type==='checkbox'){el.checked=!!v;return;}if(el.type==='radio'){el.checked=(el.value===v);return;}el.value=isDateFieldKey(key)?fmtMDY(v):v;});}
async function setView(v){view=v;document.querySelectorAll('.viewswitch button').forEach(b=>b.classList.toggle('active',b.dataset.v===v));
  if(!APPLICANT_TOKEN&&APPS_SCRIPT_URL&&(v==='hr'||v==='forms'||v==='i9'||v==='i9hr')){ await loadAllHires(); }
  if(!APPLICANT_TOKEN&&APPS_SCRIPT_URL&&v==='deleted'){ await loadDeletedHires(); }
  render();}
function render(){$('modePill').textContent=APPS_SCRIPT_URL?'Connected':'Demo mode';
  const lb=$('legendBar'); if(lb&&view!=='a'&&view!=='b') lb.classList.add('hide');
  const wrapEl=$('wrapEl'); if(wrapEl) wrapEl.classList.toggle('wide', view==='hr');
  if(view==='hr')return renderHR();if(view==='a')return renderApplicant('A');if(view==='i9')return renderI9();if(view==='b')return renderApplicant('B');if(view==='forms')return renderForms();if(view==='deleted')return renderDeleted();if(view==='i9hr')return renderI9HR();}

/* ---- Deleted (S2) — read-only list of soft-deleted hires. The
   underlying onboarding_hires row, and all of that hire's documents and
   government forms, are untouched in the database; this view only reads
   rows where deleted_at IS NOT NULL (see actionList scope='deleted'). */
function renderDeleted(){
  const rows=deletedHires.map(function(h){
    const idBits=[h.email,'#'+String(h.token||'').slice(-6)].filter(Boolean).join(' · ');
    return `<tr><td><b>${h.first} ${h.last}</b><div class="muted">${h.position||''}${idBits?' · '+idBits:''}</div></td><td>${h.site||''}</td><td>${fmtMDY(h.hire)}</td><td>${badge(h.status)}<div class="muted" style="margin-top:3px;">Removed: ${h.deletedAt?fmtMDY(h.deletedAt):'—'}</div></td><td style="text-align:right;white-space:nowrap;"><button class="btn sm" onclick="restoreHire('${h.token}')">↩ Restore</button></td></tr>`;
  }).join('');
  $('app').innerHTML='<div class="actions" style="margin-bottom:10px;"><button class="btn secondary sm" onclick="setView(\'hr\')">&#8592; Back</button></div>'
    + '<div class="banner info">🗑️ Entries removed from the active New Hires list appear here. Their record, documents, and government forms remain fully intact in the system — nothing shown here has been deleted from the database.</div>'
    + '<div class="card"><h2>Deleted</h2>'
    + (rows ? `<div style="overflow-x:auto;"><table style="margin-top:14px;width:100%;min-width:0;"><thead><tr><th>Name</th><th>Site</th><th>Hire date</th><th>Status</th><th></th></tr></thead><tbody>${rows}</tbody></table></div>` : '<div class="muted" style="margin-top:10px;">No deleted entries.</div>')
    + '</div>';
}

/* ---- I-9 HR — review/edit already-saved I-9 Section 2 records. Reads
   from the same already-loaded, already ownership-filtered `hires` array
   used by the main New Hires list (renderHR()) — no separate query, no
   separate visibility rule; a user sees exactly the same set of hires here
   as everywhere else in Employee Onboarding. Editing is only offered while
   status is before Phase B (A_done/I9_done/Training); B_sent/Final show as
   read-only so an already-sent Phase B packet can't be altered here. */
function renderI9HR(){
  const withI9=hires.filter(function(h){return h.i9_section2;});
  const editable=['A_done','I9_done','Training'];
  const rows=withI9.map(function(h){
    const idBits=[h.email,'#'+String(h.token||'').slice(-6)].filter(Boolean).join(' · ');
    const canEdit=editable.indexOf(h.status)!==-1;
    const action=canEdit
      ? `<button class="btn sm" onclick="currentToken='${h.token}';setView('i9')">Edit I-9</button>`
      : `<span class="muted" style="font-size:12px;">Locked (Phase B sent)</span>`;
    return `<tr><td><b>${h.first} ${h.last}</b><div class="muted">${h.position||''}${idBits?' · '+idBits:''}</div></td><td>${h.site||''}</td><td>${badge(h.status)}</td><td style="text-align:right;white-space:nowrap;">${action}</td></tr>`;
  }).join('');
  $('app').innerHTML='<div class="actions" style="margin-bottom:10px;"><button class="btn secondary sm" onclick="setView(\'hr\')">&#8592; Back</button></div>'
    + '<div class="banner info">🪪 Every hire with a saved I-9 Section 2 record appears here. Editing is available until Phase B is sent — after that, the I-9 is shown read-only to keep it consistent with what was already sent to the applicant.</div>'
    + '<div class="card"><h2>I-9 HR</h2>'
    + (rows ? `<div style="overflow-x:auto;"><table style="margin-top:14px;width:100%;min-width:0;"><thead><tr><th>Name</th><th>Site</th><th>Status</th><th></th></tr></thead><tbody>${rows}</tbody></table></div>` : '<div class="muted" style="margin-top:10px;">No saved I-9 records yet.</div>')
    + '</div>';
}

/* ---- Forms tab (internal only) — lists the 4 auto-generated government-
   form PDFs (Form 8850/WOTC, DE 4, W-4, I-9), populated with the applicant's
   actual submitted data. Nothing appears here until the applicant's ENTIRE
   package is done (Phase A + I-9 §2 + Phase B) — all 4 then appear at once.
   Hidden from applicants because the entire nav bar (including this button)
   is hidden whenever the page is opened via an applicant's ?token= link —
   see the bootstrap IIFE at the bottom of this file. */
function renderForms(){
  const cards=hires.map(function(h){
    const pdfs=h.pdfs||[];
    const docs=h.documents||[];
    if(!pdfs.length && !docs.length) return '';
    const rows=pdfs.map(function(f){return '<tr><td>'+f.title+'</td><td style="text-align:right;"><a class="btn sm" href="'+f.url+'" target="_blank" rel="noopener">View PDF</a></td></tr>';}).join('');
    const docRows=docs.map(function(d){return '<tr><td>'+d.title+' <span class="muted">('+d.category+')</span></td><td style="text-align:right;"><a class="btn sm" href="'+d.url+'" target="_blank" rel="noopener">View PDF</a></td></tr>';}).join('');
    return '<div class="card"><h2 style="margin:0 0 3px;">'+h.first+' '+h.last+'</h2><div class="muted" style="margin-bottom:10px;">'+(h.position||'')+' · '+(h.site||'')+'</div>'
      + (docRows ? '<div class="sub">Onboarding Documents (HR Form · Phase A · I-9 · Phase B)</div><table class="doclist"><thead><tr><th>Document</th><th></th></tr></thead><tbody>'+docRows+'</tbody></table>' : '')
      + (rows ? '<div class="sub" style="margin-top:12px;">Government Forms</div><table class="doclist"><thead><tr><th>Form</th><th></th></tr></thead><tbody>'+rows+'</tbody></table>' : '')
      + '</div>';
  }).filter(Boolean).join('');
  $('app').innerHTML='<div class="actions" style="margin-bottom:10px;"><button class="btn secondary sm" onclick="setView(\'hr\')">&#8592; Back</button></div><div class="banner info">📄 All 8 completed documents (HR Form, Phase A, I-9, Phase B, plus the 4 government forms — W-4, DE 4, I-9, Form 8850/WOTC) appear here together, organized in each applicant\u2019s own folder on the server, as soon as they\u2019re generated during the onboarding process.</div>'
    + (cards || '<div class="card"><div class="muted">No completed documents yet. Documents appear here automatically as each stage (Phase A, I-9, Phase B) is completed.</div></div>');
}

/* ---- HR console ---- */
function renderHR(){
  const byRecency=hires.slice().sort(function(a,b){return String(a.updatedAt||a.createdAt||'').localeCompare(String(b.updatedAt||b.createdAt||''));});
  const filtered=dashFilter?byRecency.filter(h=>matchesDashFilter(h,dashFilter)):byRecency;
  const rows=filtered.map(h=>{
    const justSubmitted=(h.status==='A_done'||h.status==='Final');
    const rowStyle=justSubmitted?' style="background:#f0fdf4;"':'';
    const idBits=[h.email,'#'+String(h.token||'').slice(-6)].filter(Boolean).join(' · ');
    const lastActivity=h.updatedAt||h.createdAt||'';
    const lastActivityDisp=lastActivity?fmtMDY(lastActivity):'—';
    return `<tr${rowStyle}><td><b>${h.first} ${h.last}</b><div class="muted">${h.position}${idBits?' · '+idBits:''}</div></td><td>${h.site}</td><td>${fmtMDY(h.hire)}</td><td>${badge(h.status)}<div class="muted" style="margin-top:3px;">Updated: ${lastActivityDisp}</div></td><td style="text-align:right;white-space:nowrap;">${hrBtns(h)}</td></tr>`;
  }).join('');
  const m=computeOnboardingMetrics();
  const filterChip=dashFilter?`<div class="dash-filter-chip"><span>Showing: <b>${DASH_FILTER_LABELS[dashFilter]||dashFilter}</b> (${filtered.length})</span><button class="btn ghost sm" onclick="setDashFilter(null)">✕ Clear filter</button></div>`:'';
  $('app').innerHTML=`<div class="banner info">${APPS_SCRIPT_URL?'✅ Connected — forms save to the applicant folder on the server.':'🧪 Demo mode — click through the flow.'}</div>
  ${metricsDashboardHtml(m)}
  <div class="card"><div style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:10px;"><div><h2>New Hires</h2><div class="muted">${FORMS_COUNT} forms · send Phase A at the job offer, Phase B after training</div></div><div style="display:flex;gap:8px;"><button class="btn ghost sm" onclick="refreshHires()">⟳ Refresh</button><button class="btn" onclick="showAdd()">+ Add new hire</button></div></div>
  ${filterChip}
  <div style="overflow-x:auto;"><table style="margin-top:14px;width:100%;min-width:0;"><thead><tr><th style="white-space:nowrap;">Name</th><th style="white-space:nowrap;">Site</th><th style="white-space:nowrap;">Hire date</th><th style="white-space:nowrap;">Status</th><th style="white-space:nowrap;"></th></tr></thead><tbody>${rows}</tbody></table></div></div>`;
}
const DASH_FILTER_LABELS={invitesSent:'Invitations Sent',phaseA:'Phase A Sent / Received',i9Pending:'I-9 Pending (HR)',phaseB:'Phase B Sent / Received',completed:'Completed Onboardings',pendingTasks:'Pending Tasks'};
function matchesDashFilter(h,key){
  const s=h.status;
  switch(key){
    case 'invitesSent': return s!=='New';
    case 'phaseA': return ['A_sent','A_done','I9_done','Training','B_sent','Final'].includes(s);
    case 'i9Pending': return s==='A_done';
    case 'phaseB': return ['B_sent','Final'].includes(s);
    case 'completed': return s==='Final';
    case 'pendingTasks': return s!=='Final';
    default: return true;
  }
}
function setDashFilter(key){
  dashFilter=(dashFilter===key)?null:key;
  if(view==='hr') renderHR();
}
// ── Metrics dashboard — computed entirely from the hires already loaded
// in memory, no extra server round-trip. Statuses: New -> A_sent -> A_done
// -> I9_done -> Training -> B_sent -> Final.
function computeOnboardingMetrics(){
  const c={total:hires.length,invitesSent:0,phaseASent:0,phaseAReceived:0,i9Pending:0,i9Done:0,phaseBSent:0,phaseBReceived:0,completed:0,pendingTasks:0};
  hires.forEach(function(h){
    const s=h.status;
    if(s!=='New') c.invitesSent++;
    if(['A_sent','A_done','I9_done','Training','B_sent','Final'].includes(s)) c.phaseASent++;
    if(['A_done','I9_done','Training','B_sent','Final'].includes(s)) c.phaseAReceived++;
    if(s==='A_done') c.i9Pending++;
    if(['I9_done','Training','B_sent','Final'].includes(s)) c.i9Done++;
    if(['B_sent','Final'].includes(s)) c.phaseBSent++;
    if(s==='Final') c.phaseBReceived++;
    if(s==='Final') c.completed++;
    if(s!=='Final') c.pendingTasks++;
  });
  return c;
}
function metricsDashboardHtml(m){
  const card=function(icon,label,value,color,sub,key){
    const active=dashFilter===key;
    return `<div class="dash-card${active?' dash-card-active':''}" style="--dc-color:${color};" onclick="setDashFilter('${key}')" title="Click to filter New Hires by this metric">
      <div class="dash-card-glow"></div>
      <div style="display:flex;justify-content:space-between;align-items:flex-start;position:relative;z-index:1;">
        <div style="font-size:11px;text-transform:uppercase;letter-spacing:.5px;color:var(--muted);font-weight:700;">${label}</div>
        <div class="dash-card-icon">${icon}</div>
      </div>
      <div style="font-size:28px;font-weight:800;color:${color};margin-top:6px;position:relative;z-index:1;">${value}</div>
      ${sub?`<div style="font-size:11px;color:var(--muted);margin-top:2px;position:relative;z-index:1;">${sub}</div>`:''}
      ${active?'<div class="dash-card-active-tag">✓ Filtering</div>':''}
    </div>`;
  };
  return `${DASH_STYLE_ONCE()}<div class="dash-grid">
    ${card('📨','Invitations Sent',m.invitesSent,'#3b82f6',m.total+' total hires','invitesSent')}
    ${card('📝','Phase A Sent / Received',m.phaseASent+' / '+m.phaseAReceived,'#0ea5e9','','phaseA')}
    ${card('⚠️','I-9 Pending (HR)',m.i9Pending,m.i9Pending>0?'#f59e0b':'#94a3b8',m.i9Pending>0?'Needs action':'All caught up','i9Pending')}
    ${card('📄','Phase B Sent / Received',m.phaseBSent+' / '+m.phaseBReceived,'#8b5cf6','','phaseB')}
    ${card('✅','Completed Onboardings',m.completed,'#16a34a','','completed')}
    ${card('⏳','Pending Tasks',m.pendingTasks,m.pendingTasks>0?'#dc2626':'#16a34a',m.pendingTasks>0?'Across all hires':'Nothing outstanding','pendingTasks')}
  </div>`;
}
let _dashStyleInjected=false;
function DASH_STYLE_ONCE(){
  if(_dashStyleInjected || document.getElementById('dash-style-tag')) { _dashStyleInjected=true; return ''; }
  _dashStyleInjected=true;
  const styleTag=document.createElement('style');
  styleTag.id='dash-style-tag';
  styleTag.textContent=`
  .dash-grid{display:flex;flex-wrap:wrap;gap:14px;margin-bottom:18px;}
  .dash-card{
    position:relative;overflow:hidden;flex:1;min-width:150px;
    background:linear-gradient(145deg,#ffffff 0%,#f8fafc 100%);
    border:1px solid var(--line);border-radius:14px;padding:16px 18px;
    cursor:pointer;user-select:none;
    box-shadow:0 1px 2px rgba(15,23,42,.04);
    transition:transform .22s cubic-bezier(.2,.8,.2,1),box-shadow .22s ease,border-color .22s ease;
    opacity:0;transform:translateY(10px);
    animation:dashCardIn .5s cubic-bezier(.2,.8,.2,1) forwards;
  }
  .dash-grid .dash-card:nth-child(1){animation-delay:.02s}
  .dash-grid .dash-card:nth-child(2){animation-delay:.07s}
  .dash-grid .dash-card:nth-child(3){animation-delay:.12s}
  .dash-grid .dash-card:nth-child(4){animation-delay:.17s}
  .dash-grid .dash-card:nth-child(5){animation-delay:.22s}
  .dash-grid .dash-card:nth-child(6){animation-delay:.27s}
  @keyframes dashCardIn{from{opacity:0;transform:translateY(10px) scale(.98);}to{opacity:1;transform:translateY(0) scale(1);}}
  .dash-card:hover{transform:translateY(-3px);box-shadow:0 10px 24px -8px rgba(15,23,42,.18),0 0 0 1px var(--dc-color);}
  .dash-card:active{transform:translateY(-1px) scale(.99);}
  .dash-card-active{border-color:var(--dc-color);box-shadow:0 0 0 2px var(--dc-color),0 10px 24px -8px rgba(15,23,42,.22);}
  .dash-card-glow{position:absolute;inset:0;background:radial-gradient(120px 60px at 85% -10%,color-mix(in srgb, var(--dc-color) 22%, transparent),transparent 70%);opacity:0;transition:opacity .3s ease;pointer-events:none;}
  .dash-card:hover .dash-card-glow{opacity:1;}
  .dash-card-icon{font-size:17px;filter:drop-shadow(0 1px 1px rgba(0,0,0,.08));transition:transform .3s ease;}
  .dash-card:hover .dash-card-icon{transform:scale(1.15) rotate(-4deg);}
  .dash-card-active-tag{position:absolute;top:8px;right:8px;font-size:9px;font-weight:700;color:var(--dc-color);background:color-mix(in srgb, var(--dc-color) 14%, white);border-radius:20px;padding:2px 7px;letter-spacing:.3px;}
  .dash-filter-chip{display:flex;align-items:center;justify-content:space-between;gap:10px;background:#eff6ff;border:1px solid #bfdbfe;border-radius:10px;padding:8px 12px;margin-top:12px;font-size:13px;color:#1e3a8a;animation:dashCardIn .3s ease forwards;}
  `;
  document.head.appendChild(styleTag);
  return '';
}
function hrBtns(h){let b=`<button class="btn sm secondary" onclick="showAdd('${h.token}')">Edit</button> `;
  b+=`<button class="btn sm ghost" title="Remove from active list (kept in Deleted)" onclick="deleteHire('${h.token}')" style="color:var(--danger,#dc2626);">✕</button> `;
  if(h.status==='New')b+=`<button class="btn sm" onclick="sendPhase('${h.token}','A')">Send Phase A →</button>`;
  if(h.status==='A_sent')b+=`<span class="muted">awaiting applicant…</span> <button class="btn sm ghost" onclick="sendPhase('${h.token}','A')">Send Invite Again</button>`;
  if(h.status==='B_sent')b+=`<span class="muted">awaiting applicant…</span> <button class="btn sm ghost" onclick="sendPhase('${h.token}','B')">Send Invite Again</button>`;
  if(h.status==='A_done')b+=`<button class="btn sm" onclick="currentToken='${h.token}';setView('i9')">Do I-9 §2</button>`;
  if(h.status==='I9_done')b+=`<button class="btn sm secondary" onclick="mark('${h.token}','Training','Training complete')">Mark training done</button>`;
  if(h.status==='Training')b+=`<button class="btn sm" onclick="sendPhase('${h.token}','B')">Send Phase B →</button>`;
  if(h.status==='Final')b+='<span style="color:var(--ok);font-weight:600;">✓ complete</span> <button class="btn sm ghost" onclick="regenerateGovForms(\''+h.token+'\')">⟳ Generate Govt Forms</button>';
  return b;}
async function regenerateGovForms(token){
  const h=hires.find(x=>x.token===token); if(!h){toast('Hire not found');return;}
  toast('Regenerating government forms…');
  try{
    const storedSigs=JSON.parse(localStorage.getItem('hh_sigs_'+h.token)||'{}');
    h.formSigs=Object.assign({}, storedSigs, h.formSigs||{});
    if(!h.signerName) h.signerName=fullName(h);
  }catch(e){console.warn('Could not restore saved signatures for regenerate',e);}
  const f=h.phaseA_fields||h.fields||{}, s=h.i9_section2||{};
  const specs=[['wotc','Form 8850 (WOTC)'],['de4','Form DE 4'],['w4','Form W-4'],['i9','Form I-9']];
  const results=[];
  for(const spec of specs){
    try{ results.push(await fillOfficialPdf(spec[0],spec[1],h,f,s)); }
    catch(err){ console.error('Regenerate failed for '+spec[1], err); toast('Failed: '+spec[1]+' — '+((err&&err.message)||err)); results.push(null); }
  }
  const completed=results.filter(Boolean);
  if(!completed.length){ toast('No government forms could be generated — see the failure messages above / browser console for the exact error.'); return; }
  try{
    const stored=await save('storePdfs',{token:h.token,pdfs:completed});
    if(stored&&stored.ok){ h.pdfs=stored.pdfs||h.pdfs; toast(completed.length+' of '+specs.length+' government forms generated and saved.'); render(); }
    else toast('Forms generated but saving to server failed — '+((stored&&stored.error)||'unknown error'));
  }catch(err){ console.error(err); toast('Saving failed: '+((err&&err.message)||err)); }
}
function showAdd(token){editingToken=token||null;openHireModal(editingToken?'Edit hire':'New Hire');$('hire-modal-body').innerHTML=`<div>
  <div class="hrsect" style="margin-top:0;" id="addFormTitle">${editingToken?'Edit hire':'Employee Info'}</div>
  <div class="row3-compact"><div><label>First name</label><input id="n_first"></div><div><label>Middle name</label><input id="n_middle"></div><div><label>Last name</label><input id="n_last"></div></div>
  <div class="row3-compact"><div><label>Phone number</label><input id="n_phone" placeholder="(555) 555-5555"></div><div><label>Email address</label><input id="n_email" type="email"></div><div><label>Job title</label><input id="n_pos" value="Security Officer"></div></div>
  <label>Address</label><input id="n_address" placeholder="Street address">
  <div class="row3-compact"><div><label>City</label><input id="n_city"></div><div><label>State</label><input id="n_state" value="CA" maxlength="2"></div><div><label>Zip</label><input id="n_zip"></div></div>
  <div class="hrsect">Licensing</div>
  <div class="row3-compact"><div><label>BSIS Guard Card #</label><input id="n_guardcard"></div><div><label>Guard Card Expiry</label><input type="text" id="n_guardcard_exp" class="datefld" placeholder="MM/DD/YYYY" maxlength="10"></div><div><label>Firearms Permit</label><select id="n_firearms"><option value="No">No</option><option value="Yes">Yes</option></select></div></div>
  <div class="row3-compact"><div><label>Driver's License #</label><input id="n_dl"></div><div><label>DL Expiry</label><input type="text" id="n_dl_exp" class="datefld" placeholder="MM/DD/YYYY" maxlength="10"></div><div></div></div>
  <div class="hrsect">Employment</div>
  <div class="row3-compact"><div><label>Hire type</label><input id="n_hiretype" value="New Hire" readonly></div><div><label>Employment status</label><select id="n_empstatus"><option value="Full-Time">Full-Time</option><option value="Part-Time">Part-Time</option><option value="On-Call / At-Will">On-Call / At-Will</option></select></div><div><label>Date of hire</label><input type="text" id="n_hire" class="datefld" placeholder="MM/DD/YYYY" maxlength="10"></div></div>
  <div class="row3-compact"><div><label>Pay rate <span class="req">*</span></label><input id="n_payrate" placeholder="e.g. 22.00/hr" required></div><div><label>Pay frequency</label><select id="n_payfreq"><option value="Weekly">Weekly</option><option value="Bi-Weekly">Bi-Weekly</option><option value="Semi-Monthly">Semi-Monthly</option><option value="Monthly">Monthly</option></select></div><div><label>Job site</label><select id="n_site"><option value="">— select a site —</option>${SITES.map(function(s){return '<option value="'+s.replace(/"/g,'&quot;')+'">'+s+'</option>';}).join('')}</select></div></div>
  <div class="hrsect">Work Schedule <span class="muted" style="font-weight:400;text-transform:none;">— set days & times before sending for signature</span></div>
  <div id="schedWrap">${scheduleRowsHtml()}</div>
  <div class="hrsect">HR Representative</div>
  <div class="row3-compact"><div><label>Employer / HR representative name</label><input id="n_hrrep" placeholder="Signs employer sections"></div><div></div><div></div></div>
  <div class="hrsect">Company Details</div>
  <div class="row3-compact"><div><label>Company Name</label><select id="n_company" onchange="onCompanyChange()"><option value="">— select a company —</option>${Object.keys(COMPANIES).map(function(c){return '<option value="'+c.replace(/"/g,'&quot;')+'">'+c+'</option>';}).join('')}</select></div><div><label>EIN</label><input id="n_ein" readonly placeholder="auto-fills from company"></div><div><label>State Tax ID (Entity ID)</label><input id="n_statetax" readonly placeholder="auto-fills from company"></div></div>
  <div class="row3-compact"><div style="grid-column:1 / -1"><label>Company Address</label><input id="n_company_address" readonly placeholder="auto-fills from company"></div></div>
<div class="actions"><button class="btn ghost" onclick="closeHireModal()">Cancel</button><button class="btn" id="saveHireBtn" onclick="saveHire()">${editingToken?'Save changes':'Save & add'}</button></div></div>`;if(editingToken){const h=hires.find(x=>x.token===editingToken);if(h)prefillAddForm(h);}
  else{const el=$('n_hrrep');if(el)el.value='Rachel Resurreccion';}
  ['n_guardcard_exp','n_dl_exp','n_hire'].forEach(initHybridDateField);
}
function onCompanyChange(){
  const name=val('n_company');const c=COMPANIES[name];
  const einEl=$('n_ein'),taxEl=$('n_statetax'),addrEl=$('n_company_address');
  if(einEl)einEl.value=c?c.ein:'';
  if(taxEl)taxEl.value=c?c.stateTaxId:'';
  if(addrEl)addrEl.value=c?c.address:'';
}
const SCHED_DAYS=[['mon','Mon'],['tue','Tue'],['wed','Wed'],['thu','Thu'],['fri','Fri'],['sat','Sat'],['sun','Sun']];
function scheduleRowsHtml(){
  const rows=SCHED_DAYS.map(function(d){var k=d[0];return '<div class="schedrow off" id="schrow_'+k+'"><label class="schedday"><input type="checkbox" id="sch_'+k+'_on" onchange="schedToggle(\''+k+'\')"> '+d[1]+'</label><input type="time" id="sch_'+k+'_start" onchange="schedToggle(\''+k+'\')"><span class="schedto">to</span><input type="time" id="sch_'+k+'_end" onchange="schedToggle(\''+k+'\')"></div>';}).join('');
  const bulk='<div style="margin-bottom:12px;padding:10px;border:1px dashed #cbd5e1;border-radius:8px;display:flex;gap:10px;align-items:center;flex-wrap:wrap;">'
    +'<span class="muted" style="font-size:12px;">Check the days below, set one time, then click Auto Fill:</span>'
    +'<input type="time" id="sch_bulk_start"><span class="schedto">to</span><input type="time" id="sch_bulk_end">'
    +'<button type="button" class="btn sm secondary" onclick="applyBulkSchedTime()">Auto Fill selected days</button></div>';
  return bulk+rows;
}
function applyBulkSchedTime(){
  const s=val('sch_bulk_start'),e=val('sch_bulk_end');
  if(!s||!e){toast('Set both a start and end time first');return;}
  let applied=0;
  SCHED_DAYS.forEach(function(d){var k=d[0];var on=$('sch_'+k+'_on');if(on&&on.checked){$('sch_'+k+'_start').value=s;$('sch_'+k+'_end').value=e;applied++;}});
  if(!applied){toast('Check at least one day first');return;}
  toast('Applied to '+applied+' day'+(applied===1?'':'s'));
}
function schedToggle(k){var on=$('sch_'+k+'_on');var row=$('schrow_'+k);if(row)row.classList.toggle('off',!(on&&on.checked));}
function collectSchedule(){var sched={};var parts=[];SCHED_DAYS.forEach(function(d){var k=d[0];var on=$('sch_'+k+'_on');var st=$('sch_'+k+'_start');var en=$('sch_'+k+'_end');if(on&&on.checked){var s=st?st.value:'',e=en?en.value:'';sched[k]={on:true,start:s,end:e};parts.push(d[1]+' '+(s||'?')+'-'+(e||'?'));}else{sched[k]={on:false,start:'',end:''};}});return {sched:sched,text:parts.join(', ')};}
function prefillSchedule(h){if(!h||!h.schedule)return;SCHED_DAYS.forEach(function(d){var k=d[0];var rec=h.schedule[k];if(!rec)return;var on=$('sch_'+k+'_on');var st=$('sch_'+k+'_start');var en=$('sch_'+k+'_end');if(on)on.checked=!!rec.on;if(st)st.value=rec.start||'';if(en)en.value=rec.end||'';schedToggle(k);});}
function prefillAddForm(h){const s=(id,v)=>{const e=$(id);if(e)e.value=v||'';};s('n_first',h.first);s('n_middle',h.middle);s('n_last',h.last);s('n_phone',h.phone);s('n_email',h.email);s('n_pos',h.position);s('n_address',h.address);s('n_city',h.city);s('n_state',h.state);s('n_zip',h.zip);s('n_guardcard',h.guardCard);s('n_guardcard_exp',fmtMDY(h.guardCardExp));s('n_dl',h.dl);s('n_dl_exp',fmtMDY(h.dlExp));s('n_firearms',h.firearmsPermit);s('n_hiretype',h.hireType);s('n_empstatus',h.empStatus);s('n_hire',fmtMDY(h.hire));s('n_payrate',h.payRate);s('n_payfreq',h.payFreq);s('n_site',h.site);s('n_hrrep',h.hrRep);s('n_company',h.companyName);onCompanyChange();prefillSchedule(h);}
async function saveHire(){
  if(!val('n_payrate').trim()){ toast('Pay rate is required before saving this hire'); const el=$('n_payrate'); if(el)el.focus(); return; }
  const d={first:val('n_first')||'New',middle:val('n_middle'),last:val('n_last')||'Hire',phone:val('n_phone'),email:val('n_email'),address:val('n_address'),city:val('n_city'),state:val('n_state'),zip:val('n_zip'),guardCard:val('n_guardcard'),guardCardExp:mdyToIso(val('n_guardcard_exp')),dl:val('n_dl'),dlExp:mdyToIso(val('n_dl_exp')),firearmsPermit:val('n_firearms'),position:val('n_pos'),site:val('n_site'),hire:mdyToIso(val('n_hire')),hireType:val('n_hiretype')||'New Hire',empStatus:val('n_empstatus'),payRate:val('n_payrate'),payFreq:val('n_payfreq'),hrRep:val('n_hrrep'),companyName:val('n_company'),ein:val('n_ein'),stateTaxId:val('n_statetax')};const _sc=collectSchedule();d.schedule=_sc.sched;d.scheduleText=_sc.text;if(editingToken){const h=hires.find(x=>x.token===editingToken);Object.assign(h,d);await save('updateHire',h);toast('Hire info updated');}else{const nowIso=new Date().toISOString();
const h=Object.assign({token:newToken(),eid:String(5044+hires.length),status:'New',createdAt:nowIso,updatedAt:nowIso},d);
const created=await save('addHire',h);
if(!created||!created.ok){toast((created&&created.error)||'Could not add the hire');return;}
// The server may merge a duplicate email into an existing record and return
// its token. Keep the browser copy in sync so Send Phase A works first time.
h.token=created.token||h.token; hires.push(h);toast('New hire added');}editingToken=null;closeHireModal();render();}
async function sendPhase(t,phase){
  const h=hires.find(x=>x.token===t),email=(h&&h.email||'').trim();
  if(!email){toast('Enter the applicant email address before sending');return;}
  if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)){toast('Enter a valid applicant email address');return;}
  const res=await save('sendPhase',{token:t,phase,email:email});
  if(!res||!res.ok){toast((res&&res.error)||'Email was not sent. Check the Apps Script execution log.');return;}
  h.status=phase==='A'?'A_sent':'B_sent';
  toast(`Phase ${phase} link emailed to ${email}`);render();
}
async function mark(t,st,msg){const h=hires.find(x=>x.token===t);h.status=st;await save('markStatus',{token:t,status:st});toast(msg);render();}

/* ---- applicant phase ---- */
function renderApplicant(phase){
  const h=hire();
  const atWill=/on-?call|at-?will/i.test(h.empStatus||'');
  const keys=(PHASES[phase]||[]).map(function(k){return k==='offer'?(atWill?'offer21a':'offer21b'):k;}).filter(function(k){return FORMS[k];});
  wizPhase=phase; wizKeys=keys; wizStep=0; formSigs={}; typedSig=null; drawnSig=null; sigKind='type'; signerName='';
  try{
    const storedSigs=JSON.parse(localStorage.getItem('hh_sigs_'+h.token)||'{}');
    Object.assign(formSigs, storedSigs);
  }catch(e){console.warn('Could not restore saved signatures',e);}
  const setup = `<div class="wizstep" data-step="0">
    <div class="card"><h2 style="margin:0 0 4px;">Welcome, ${h.first}</h2><div class="muted">You'll review and sign ${keys.length} form${keys.length===1?'':'s'}, one at a time. Each form appears on its own — read it, complete anything required, and sign it before moving to the next. First, a couple of quick details and your signature.</div></div>
    ${phase==='A'?`<div class="card" id="qCard"><h3 style="margin:0 0 6px;">Quick details</h3><div class="muted" style="margin-bottom:8px;">Enter once — automatically fills into your I-9, W-4, DE 4, and Form 8850.</div>
      <div class="row"><div class="fld"><label>Date of Birth (MM/DD/YYYY)</label><input type="text" id="dob_setup" class="fi fi-req datefld" data-mirror="dob" data-setup-req="1" placeholder="MM/DD/YYYY" maxlength="10" inputmode="numeric"></div>
      <div class="fld"><label>Social Security Number</label><input type="text" class="fi fi-req" data-mirror="ssn" data-setup-req="1" placeholder="XXX-XX-XXXX"></div></div></div>`:''}
    <div class="card"><h3 style="margin:0 0 6px;">Set up your signature</h3>
      <div class="muted" style="margin-bottom:10px;">Type your full legal name or draw it below. This is the signature you'll apply to each form.</div>
      <div class="sig-tabs"><button type="button" id="sigtab-type" class="btn sm" onclick="setSigMode('type')">Type</button><button type="button" id="sigtab-draw" class="btn sm secondary" onclick="setSigMode('draw')">Draw</button></div>
      <div id="sig-type-wrap"><input type="text" id="sigTypeInput" class="fi" placeholder="Type your full legal name" oninput="onSigType()"><div class="sig-preview" id="sigTypePreview"></div></div>
      <div id="sig-draw-wrap" class="hide"><canvas id="sigpad" class="sigpad"></canvas><div class="actions" style="margin-top:8px;"><button type="button" class="btn secondary sm" onclick="clearSig()">Clear</button></div></div>
      <div id="sigState" class="muted" style="margin-top:8px;">not set up yet</div>
    </div></div>`;
  const formSteps = keys.map(function(k,i){
    return `<div class="wizstep hide" data-step="${i+1}" data-formkey="${k}">
      <div class="doc"><h3 class="dt">${FORMS[k].title}</h3>${FORMS[k].body}</div>
      <div class="card sign-card" id="signcard-${k}"><h3 style="margin:0 0 6px;">Sign this form</h3>
        <div class="muted" style="margin-bottom:8px;">By signing, you confirm you have read and agree to <b>${FORMS[k].title}</b>. Your signature and the date & time are recorded for this form specifically.</div>
        <div class="sig-apply-preview" id="sigapply-${k}"></div>
        <button type="button" class="btn" id="signbtn-${k}" onclick="signCurrentForm()">&#9997; I have read this form and I sign it</button>
        <div class="signed-note hide" id="signed-${k}"></div>
      </div></div>`;
  }).join('');
  $('app').innerHTML=`<div class="banner info" id="wizBanner">Secure onboarding — welcome, ${h.first}! <button type="button" class="legend-link" onclick="showColorLegend()">What do the colors mean?</button></div>
    <div class="wizbar"><div class="wizprog"><div id="wizProgFill" class="wizprog-fill"></div></div><div id="wizLabel" class="muted"></div></div>
    <button type="button" class="btn next-req-btn hide" id="nextReqBtn" onclick="nextRequiredField()">Next required field &#8595;</button>
    <form id="obform" onsubmit="return false" autocomplete="off">${setup}${formSteps}</form>
    <div class="wiznav"><button type="button" class="btn secondary" id="wizBack" onclick="wizGo(-1)">&#8592; Back</button>
      <button type="button" class="btn" id="wizNext" onclick="wizGo(1)">Next &#8594;</button></div>`;
  initSig(); w4calc(); initMirror(); prefillApplicantFields(h); if(h.fields) prefillSavedFields(h.fields); applyHrPrefill(h);
reinforceKnownAutofills(h);
  const citChecked=document.querySelector('[name="f[i9cit]"]:checked'); if(citChecked) i9Switch(citChecked.value);
  const ddChecked=document.querySelector('[name="f[dd_enroll]"]:checked'); if(ddChecked) ddToggle(ddChecked.value);
  wotcAutoBoxes();
  document.querySelectorAll('#obform [data-today]').forEach(function(el){ if(!el.value){ el.value=new Date().toISOString().slice(0,10); el.classList.add('prefilled'); } });
  document.querySelectorAll('#obform input[type="date"]').forEach(function(el){ el.type='text'; el.classList.add('datefld'); if(el.value) el.value=fmtMDY(el.value); if(!el.id) el.id='date_'+Math.random().toString(36).slice(2); initHybridDateField(el.id); });
  initHybridDateField('dob_setup');
  styleRequiredOptional();
  const lb=$('legendBar'); if(lb) lb.classList.remove('hide');
  signerName=fullName(h);
  setSigMode('type');
  showWizStep(0);
  if(!legendShown){legendShown=true;showColorLegend();}
}
function showWizStep(n){
  const steps=[].slice.call(document.querySelectorAll('.wizstep')); const total=steps.length;
  wizStep=Math.max(0,Math.min(n,total-1));
  steps.forEach(function(s){s.classList.toggle('hide', (+s.dataset.step)!==wizStep);});
  const fill=$('wizProgFill'); if(fill) fill.style.width=(total>1?(wizStep/(total-1)*100):100)+'%';
  const cur=steps[wizStep]; const label=$('wizLabel');
  if(wizStep===0){ if(label) label.textContent='Getting started'; }
  else { const key=cur.dataset.formkey; if(label) label.textContent='Form '+wizStep+' of '+(total-1)+' — '+FORMS[key].title; }
  const back=$('wizBack'); if(back){ back.style.visibility=(wizStep===0?'hidden':'visible'); }
  const isLast=wizStep===total-1; const nx=$('wizNext'); if(nx) nx.textContent=isLast?'Submit my package →':'Next →';
  const nrb=$('nextReqBtn'); if(nrb) nrb.classList.toggle('hide', wizStep===0);
  if(typeof window.scrollTo==='function') window.scrollTo(0,0);
  updateSignAreaFor(cur);
}
async function wizGo(dir){
  const steps=[].slice.call(document.querySelectorAll('.wizstep')); const total=steps.length; const cur=steps[wizStep];
  if(dir>0){
    if(wizStep===0){ if(!validateSetup()) return; }
    else {
      const key=cur.dataset.formkey;
      if(!validateStepFields(cur)){ toast('Please complete all required fields on this form'); return; }
      if(!formSigs[key]){ toast('Please sign this form before continuing'); const b=$('signbtn-'+key); if(b&&b.scrollIntoView) b.scrollIntoView({behavior:'smooth',block:'center'}); return; }
    }
    if(wizStep===total-1){ return submitApplicant(wizPhase); }
    showWizStep(wizStep+1);
  } else { showWizStep(wizStep-1); }
}
function validateSetup(){
  const reqs=[].slice.call(document.querySelectorAll('[data-setup-req]'));
  for(var i=0;i<reqs.length;i++){ if(!reqs[i].value){ if(reqs[i].focus) reqs[i].focus(); toast('Please fill in your date of birth and SSN'); return false; } }
  if(!signature){ toast('Please set up your signature (type or draw)'); return false; }
  return true;
}
function validateStepFields(stepEl){
  const inputs=[].slice.call(stepEl.querySelectorAll('[required]'));
  for(var i=0;i<inputs.length;i++){ if(!inputs[i].checkValidity()){ if(inputs[i].reportValidity) inputs[i].reportValidity(); return false; } }
  const citEl=stepEl.querySelector('input[name="f[i9cit]"]:checked');
  if(citEl){
    const g=function(n){const els=stepEl.querySelectorAll('[name="f['+n+']"]');for(var j=0;j<els.length;j++){if(els[j].value&&els[j].value.trim())return els[j].value.trim();}return '';};
    if(citEl.value==='lpr' && !g('uscis_a_number_if_applicable')){
      toast('Enter your USCIS A-Number / Alien Registration Number');
      return false;
    }
    if(citEl.value==='alien'){
      if(!g('i9_exp_date')){
        toast('Enter your Work Authorization Expiration Date');
        return false;
      }
      if(!g('uscis_a_number_if_applicable') && !g('form_i_94_admission_number_if_applicable') && !g('foreign_passport_number_if_applicable')){
        toast('Enter at least one of: USCIS A-Number, Form I-94 Admission Number, or Foreign Passport Number');
        return false;
      }
    }
  }
  return true;
}
function setSigMode(mode){
  sigKind=mode;
  const tw=$('sig-type-wrap'), dw=$('sig-draw-wrap');
  if(tw) tw.classList.toggle('hide', mode!=='type');
  if(dw) dw.classList.toggle('hide', mode!=='draw');
  const tt=$('sigtab-type'), td=$('sigtab-draw');
  if(tt) tt.className='btn sm'+(mode==='type'?'':' secondary');
  if(td) td.className='btn sm'+(mode==='draw'?'':' secondary');
  if(mode==='draw'){ setTimeout(ensureSigCanvas, 0); }
  signature = (mode==='type'?typedSig:drawnSig);
  setSigState(!!signature);
}
function ensureSigCanvas(){
  const c=$('sigpad'); if(!c) return;
  const r=c.getBoundingClientRect();
  if(r.width<1){ return; } /* still hidden/zero — nothing to size yet */
  if(c._sizedW===Math.round(r.width) && c._inited){ return; } /* already correctly sized */
  initSig();
  c._inited=true; c._sizedW=Math.round(r.width);
}
function onSigType(){
  const v=($('sigTypeInput')&&$('sigTypeInput').value||'').trim();
  const prev=$('sigTypePreview');
  if(v){ typedSig=v; signerName=v; if(prev){prev.textContent=v;prev.style.display='block';} }
  else { typedSig=null; if(prev){prev.textContent='';prev.style.display='none';} const h=hire(); signerName=fullName(h); }
  if(sigKind==='type'){ signature=typedSig; setSigState(!!signature); }
}
function setSigState(ok){ const el=$('sigState'); if(!el) return; el.textContent=ok?'signature ready ✓':'not set up yet'; el.style.color=ok?'var(--ok)':''; }
function signCurrentForm(){
  const steps=[].slice.call(document.querySelectorAll('.wizstep')); const cur=steps[wizStep]; if(!cur) return;
  const key=cur.dataset.formkey; if(!key) return;
  if(!signature){ toast('Please set up your signature on the first step'); return; }
  if(!validateStepFields(cur)){ toast('Please complete the required fields before signing'); return; }
  formSigs[key]={ kind:sigKind, data:signature, name:signerName||fullName(hire()), ts:(new Date()).toISOString() };
  const card=$('signcard-'+key); if(card) card.classList.add('done');
  updateSignAreaFor(cur);
  toast('Signed ✓');
}
function updateSignAreaFor(stepEl){
  if(!stepEl) return; const key=stepEl.dataset.formkey; if(!key) return;
  const rec=formSigs[key];
  const applyPrev=$('sigapply-'+key), signedNote=$('signed-'+key), btn=$('signbtn-'+key), card=$('signcard-'+key);
  function sigMarkup(kind,data,name){ return kind==='draw' ? '<img src="'+data+'" style="height:46px;">' : '<span class="typed-sig">'+name+'</span>'; }
  if(rec){
    if(card) card.classList.add('done');
    const when=fmtMDYDateTime(rec.ts);
    if(signedNote){ signedNote.innerHTML='<div class="signed-box">✓ Signed by <b>'+rec.name+'</b> on '+when+'<div>'+sigMarkup(rec.kind,rec.data,rec.name)+'</div></div>'; signedNote.classList.remove('hide'); }
    if(btn){ btn.textContent='Re-sign this form'; btn.classList.add('secondary'); }
    if(applyPrev) applyPrev.innerHTML='';
  } else {
    if(card) card.classList.remove('done');
    if(signedNote){ signedNote.classList.add('hide'); signedNote.innerHTML=''; }
    if(btn){ btn.innerHTML='✍ I have read this form and I sign it'; btn.classList.remove('secondary'); }
    if(applyPrev){ applyPrev.innerHTML = signature ? ('<div class="muted" style="margin-bottom:4px;">Signature to apply:</div>'+sigMarkup(sigKind,signature,signerName||fullName(hire()))) : '<div class="muted">Set up your signature on the first step.</div>'; }
  }
}
function w4calc(){const k=parseInt(($('w4_children')||{}).value||0,10)||0,o=parseInt(($('w4_other')||{}).value||0,10)||0;const t=k*2200+o*500;const out=$('w4_dep_total');if(out)out.value=t?('$'+t.toLocaleString()):'';}
function isDateFieldKey(key){return /(?:date|dob|exp|start)/i.test(key);}
function collectFields(){const data={};document.querySelectorAll('#obform [name]').forEach(el=>{
  const m=el.name.match(/^f\[(.+)\]$/);if(!m)return;const key=m[1];
  if(el.type==='checkbox'){if(el.checked)data[key]=el.value||'1';}
  else if(el.type==='radio'){if(el.checked)data[key]=el.value;}
  else if(el.value!=='')data[key]=isDateFieldKey(key)?fmtMDY(el.value):el.value;});return data;}
function fullName(h){return [h.first,h.middle,h.last].filter(Boolean).join(' ');}
function cityStateZip(h){let s=h.city||'';if(h.state)s+=(s?', ':'')+h.state;if(h.zip)s+=' '+h.zip;return s;}
function schedDay(h,k){var s=h.schedule&&h.schedule[k];if(!s||!s.on)return 'Not scheduled';return (s.start||'?')+' – '+(s.end||'?');}
function autoFillValue(h,key){switch(key){
  case 'employee_name':return (h.first||'')+' '+(h.last||'');
  case 'first_name_given_name':return h.first||'';
  case 'last_name_family_name':return h.last||'';
  case 'middle_initial_if_any':return h.middle?h.middle.charAt(0).toUpperCase():'';
  case 'phone_number':case 'primary_phone':case 's_telephone_number_e_ph_true':case 'wotc_phone':case 'phone':return h.phone||'';
  case 'email_address':case 'email':case 's_email_address_e_em_true':return h.email||'';
  case 'address':case 'address_street_number_and_name':case 'wotc_street':case 'w4_address':case 'de4_address':return h.address||'';
  case 'city':case 'city_or_town':case 'de4_city':return h.city||'';
  case 'state':case 'de4_state':return h.state||'';
  case 'zip':case 'zip_code':case 'de4_zip':return h.zip||'';
  case 'w4_csz':case 'wotc_csz':return cityStateZip(h);
  case 'w4_first':return (h.first||'')+(h.middle?' '+h.middle.charAt(0)+'.':'');
  case 'w4_last':return h.last||'';
  case 'de4_name':case 'wotc_name':case 'wotc_print_name':return fullName(h);
  case 'bsis_guard_card':return h.guardCard||'';
  case 'guard_card_expiry':return h.guardCardExp?fmtMDY(h.guardCardExp):'';
  case 's_license_e_dln_e_dln':return h.dl||'';
  case 'dl_expiry':return h.dlExp?fmtMDY(h.dlExp):'';
  case 'position':case 'job_title':case 'wotc_position':return h.position||'';
  case 'work_location_site':return h.site||'';
  case 'sched_sat':return schedDay(h,'sat');
  case 'sched_sun':return schedDay(h,'sun');
  case 'sched_mon':return schedDay(h,'mon');
  case 'sched_tue':return schedDay(h,'tue');
  case 'sched_wed':return schedDay(h,'wed');
  case 'sched_thu':return schedDay(h,'thu');
  case 'sched_fri':return schedDay(h,'fri');
  case 'pay_rate_amt':case 'wotc_wage':return payRateAmt(h)?('$'+payRateAmt(h)):'';
  case 'pay_frequency':return h.payFreq||'';
  case 'firearms_permit_status':return h.firearmsPermit||'';
  case 'employment_status':return h.empStatus||'';
  case 'schedule':case 'work_schedule':case 'days_hours':return h.scheduleText||'';
  case 'date_of_hire':case 'start_date':case 'wotc_start':return h.hire?fmtMDY(h.hire):'';
  case 'date':return fmtMDY(new Date().toISOString().slice(0,10));
  case 'employee_id':return h.eid||'';
  case 'applicant_name':return fullName(h);
  case 'employer_representative':case 'employer_representative_name':case 'company_representative':case 'manager_representative':case 'employer_organization':return h.hrRep||'';
  case 'company_name':case 'wotc_company':return h.companyName||'';
  case 'federal_ein':case 'ein':case 'wotc_ein':return h.ein||'';
  case 'state_tax_id':case 'ca_employer_payroll_tax_account_number':return h.stateTaxId||'';
  default:return '';}}
function prefillApplicantFields(h){document.querySelectorAll('#obform [name]').forEach(el=>{
  const m=el.name.match(/^f\[(.+)\]$/);if(!m)return;const key=m[1];
  const v=autoFillValue(h,key);if(!v)return;
  if(el.type==='radio'){if(el.value===v){el.checked=true;}return;}
  if(el.type==='checkbox')return;
  el.value=v;el.classList.add('prefilled');});
  const femp=document.querySelectorAll('#obform [name="firearms_emp"]');
  if(femp.length===2){const wantsYes=(h.firearmsPermit||'').toLowerCase()==='yes';femp[wantsYes?0:1].checked=true;const box=document.getElementById('firearms-fields-emp');if(box)box.style.display=wantsYes?'block':'none';}
  fillOffer21bHR(h);
  fillAllHrFields(h);
}

function reinforceKnownAutofills(h){
  const doc=$('obform'); if(!doc) return;
  const apply=function(name,value){
    if(value==null||value==='') return;
    doc.querySelectorAll('[name="f['+name+']"]').forEach(function(el){
      if(el.type==='checkbox'||el.type==='radio') return;
      if(el.value==='') { el.value=value; el.classList.add('prefilled'); }
    });
  };
  const run=function(){
    apply('pay_rate_amt', payRateAmt(h)?('$'+payRateAmt(h)):'');
    apply('pay_frequency', h.payFreq||'');
    apply('w4_first', (h.first||'')+(h.middle?' '+h.middle.charAt(0)+'.':''));
    apply('w4_last', h.last||'');
    apply('w4_address', h.address||'');
    apply('w4_csz', cityStateZip(h));
    apply('zip', h.zip||''); apply('zip_code', h.zip||''); apply('de4_zip', h.zip||'');
    apply('work_location_site', h.site||'');
    apply('company_name', h.companyName||''); apply('wotc_company', h.companyName||'');
    apply('federal_ein', h.ein||''); apply('wotc_ein', h.ein||'');
    apply('state_tax_id', h.stateTaxId||'');
  };
  run();
  setTimeout(run,60);
  setTimeout(run,400);
}
// Fill HR-entered values on every generated form.  This deliberately uses
// the field keys (rather than a presentational CSS class) because most form
// controls are standard `.fi` inputs.  It also recognizes common label-only
// fields used in policy acknowledgements.
function applyHrPrefill(h){
  const doc=document.getElementById('obform'); if(!doc) return;
  doc.querySelectorAll('[name^="f["]').forEach(function(el){
    const key=extractFKey(el), value=autoFillValue(h,key);
    if(value!=='' && (el.value==='' || el.readOnly)){
      if(el.type==='radio') el.checked=(el.value===value);
      else if(el.type!=='checkbox'){ el.value=value; el.classList.add('prefilled'); }
    }
  });
  const byLabel={
    'Employee Name':fullName(h), 'Employee ID':h.eid||'',
    'Job Title':h.position||'', 'Position':h.position||'',
    'Work Location':h.site||'', 'Work Location / Site':h.site||'', 'Job Site':h.site||'',
    'Date of Hire':fmtMDY(h.hire), 'Pay Rate':h.payRate||'',
    'Regular Rate of Pay ($ / Hour)':payRateAmt(h), 'Pay Frequency':h.payFreq||'',
    'Paydays':h.payFreq||'', 'HR Representative':h.hrRep||'',
    'Employer Representative':h.hrRep||''
  };
  doc.querySelectorAll('.fld').forEach(function(field){
    const label=field.querySelector('label'), input=field.querySelector('input,textarea,select');
    if(!label||!input) return;
    const labelText=label.textContent.replace(/\s+/g,' ').replace('*','').trim();
    const value=byLabel[labelText];
    if(value && (input.value==='' || input.readOnly)){ input.value=value; input.classList.add('prefilled'); }
  });
}
function payRateAmt(h){return (h.payRate||'').replace(/\s*\/\s*(hr|hour)s?\b/ig,'').replace(/^\$/,'').trim();}
function fillOffer21bHR(h){const doc=document.getElementById('obform');if(!doc)return;
  const map={'Firearms Permit':h.firearmsPermit,'Job Title':h.position,'Hire Type':h.hireType,'Employment Status':h.empStatus,'Pay Rate':h.payRate,'Pay Frequency':h.payFreq,'Date of Hire':fmtMDY(h.hire),'Job Site':h.site};
  doc.querySelectorAll('input.fhr').forEach(inp=>{const lbl=inp.parentElement&&inp.parentElement.querySelector('label');if(!lbl)return;const k=lbl.textContent.trim();if(map[k]){inp.value=map[k];inp.classList.add('prefilled');}});
  if(h.empStatus)doc.querySelectorAll('.offer-banner strong').forEach(s=>{s.textContent=h.empStatus;});
  const amt=payRateAmt(h);
  doc.querySelectorAll('.pbox p').forEach(p=>{if(p.innerHTML.indexOf('Regular rate:')<0)return;let html=p.innerHTML;if(amt)html=html.replace('Regular rate: $/hr.','Regular rate: $'+amt+'/hr.');if(h.payFreq)html=html.replace('Paydays: .','Paydays: '+h.payFreq+'.');p.innerHTML=html;});
}
function fillAllHrFields(h){
  const doc=document.getElementById('obform'); if(!doc) return;
  const map={
    'Direct Supervisor':h.hrRep,'HR Coordinator':h.hrRep,'Safety Officer / Trainer':h.hrRep,
    'Trainer Name':h.hrRep,'Employer Representative':h.hrRep,
    'Firearms Permit':h.firearmsPermit,'Job Title':h.position,'Hire Type':h.hireType,
    'Employment Status':h.empStatus,'Pay Rate':h.payRate,'Pay Frequency':h.payFreq,
    'Date of Hire':h.hire,'Job Site':h.site,'Work Location / Site':h.site
  };
  doc.querySelectorAll('input.fhr').forEach(inp=>{
    const lbl=inp.parentElement&&inp.parentElement.querySelector('label');
    if(!lbl) return;
    const k=lbl.textContent.replace(/\s*HR\s*$/,'').trim();
    if(map[k]){ inp.value=map[k]; inp.classList.add('prefilled'); }
  });
}
  async function submitApplicant(phase){
  const keys=wizKeys||[];
  const unsigned=keys.filter(function(k){return FORMS[k] && !formSigs[k];});
  if(unsigned.length){ toast(unsigned.length+' form'+(unsigned.length===1?'':'s')+' still need signing'); return; }
  const h=hire();const fields=collectFields();
  const forms=keys.map(function(k){
    const stepEl=document.querySelector('.wizstep[data-formkey="'+k+'"]');
    const fFields={};
    if(stepEl){
      stepEl.querySelectorAll('[name]').forEach(function(el){
        const m=el.name.match(/^f\[(.+)\]$/); if(!m) return; const key=m[1];
        if(el.type==='checkbox'){ if(el.checked) fFields[key]=el.value||'1'; }
        else if(el.type==='radio'){ if(el.checked) fFields[key]=el.value; }
        else if(el.value!=='') fFields[key]=el.value;
      });
    }
    const sig=formSigs[k];
    return {key:k, title:(FORMS[k]&&FORMS[k].title)||k, fields:fFields, signedBy:sig?sig.name:'', signedAt:sig?sig.ts:''};
  });
  const res=await save('submitPhase',{token:h.token,phase,fields,forms,signatures:formSigs,signerName:signerName||fullName(h)});
  if(!res||res.ok===false){ toast('Submission failed — please try again or contact HR.'); return; }
  try{
    const sigStoreKey='hh_sigs_'+h.token;
    const existingSigs=JSON.parse(localStorage.getItem(sigStoreKey)||'{}');
    localStorage.setItem(sigStoreKey, JSON.stringify(Object.assign({}, existingSigs, formSigs)));
  }catch(e){console.warn('Could not persist signatures locally',e);}
  h.status=phase==='A'?'A_done':'Final';
  if(phase==='B'){
    // Generate & store the 4 official PDFs in the background instead of making
    // the applicant wait — the submission itself is already safely saved by
    // submitPhase above. This is the part that used to make "Submit" feel stuck.
    (async function(){
      try{
        h.formSigs=formSigs; h.signerName=signerName||fullName(h);
        const completed=await createOfficialPdfs(h);
        const stored=await save('storePdfs',{token:h.token,pdfs:completed});
        if(stored&&stored.ok)h.pdfs=stored.pdfs||h.pdfs;
        else console.error('Official PDF storage failed',stored);
      }catch(err){console.error('Official PDF generation failed',err);}
    })();
  }
  if(APPLICANT_TOKEN){
    renderThankYou(); // applicants never see the HR dashboard — dedicated confirmation screen only
    return;
  }
  toast(phase==='A'?'Submitted! HR notified to complete I-9 Section 2.':'All done! Package finalized.');
  setView('hr');
}
function renderThankYou(){
  $('app').innerHTML=`<div class="card" style="text-align:center;padding:48px 24px;">
    <div style="font-size:44px;margin-bottom:12px;">✅</div>
    <h2 style="margin:0 0 8px;">Thank you!</h2>
    <p class="muted" style="font-size:14px;">Your form has been successfully submitted to HR.</p>
  </div>`;
}

/* ---- I-9 section 2 ---- */
function i9Opts(arr){return arr.map(function(o){return '<option value="'+o.replace(/"/g,'&quot;')+'">'+o+'</option>';}).join('');}
var I9_LISTA=["U.S. Passport or U.S. Passport Card","Permanent Resident Card / Alien Registration Receipt Card (Form I-551)","Foreign passport with temporary I-551 stamp or notation","Employment Authorization Document with photograph (Form I-766)","Foreign passport + Form I-94/I-94A (temporary authorization)"];
var I9_LISTB=["Driver's license or ID card issued by a State/outlying possession (with photo)","ID card issued by federal, state, or local government (with photo)","School ID card with a photograph","Voter's registration card","U.S. Military card or draft record","Military dependent's ID card","U.S. Coast Guard Merchant Mariner Card","Native American tribal document","Driver's license issued by a Canadian government authority"];
var I9_LISTC=["Social Security Account Number card (unrestricted)","Certification of report of birth (DS-1350, FS-545, FS-240)","Original or certified U.S. birth certificate (official seal)","Native American tribal document","U.S. Citizen ID Card (Form I-197)","ID Card for Use of Resident Citizen (Form I-179)","Employment Authorization Document issued by DHS"];
function i9DocPath(v){var a=$('i9-listA-block'),bc=$('i9-listBC-block');if(a)a.style.display=(v==='A'?'block':'none');if(bc)bc.style.display=(v==='BC'?'block':'none');}
function renderI9(){const h=hire();
  const rep=employerSignatureName(h.hrRep||'');
  const savedBizName=h.companyName||localStorage.getItem('hh_company_name')||'Hammer Head Security';
  const savedAddr=localStorage.getItem('hh_company_addr')||'4551 South B Street, Stockton, CA 95206';
  const savedEin=h.ein||localStorage.getItem('hh_company_ein')||'';
  const savedPayroll=h.stateTaxId||localStorage.getItem('hh_company_capayroll')||'';
  $('app').innerHTML=`<div class="banner">&#9202; Complete within <b>3 business days</b> of ${h.first}'s first day. Examine the <b>original physical documents</b> in person.</div>
  <div class="card"><h2>I-9 Section 2 — Employer Verification</h2><div class="muted">Employee: <b>${h.first} ${h.last}</b> &middot; ${h.site}</div>
  <div class="sh">Documentation the employee presented</div>
  <div class="muted" style="margin-bottom:6px;">Choose what you examined: <b>either</b> one List A document, <b>or</b> one List B <b>and</b> one List C document.</div>
  <div class="rg"><label><input type="radio" name="i9docpath" value="A" onchange="i9DocPath('A')"> List A (identity <b>and</b> work authorization)</label>
  <label><input type="radio" name="i9docpath" value="BC" checked onchange="i9DocPath('BC')"> List B + List C</label></div>

  <div id="i9-listA-block" style="display:none;">
    <div class="sub">List A document</div>
    <div class="row"><div><label>Document title</label><select id="i9_a_title"><option value="">— select —</option>${i9Opts(I9_LISTA)}</select></div><div><label>Issuing authority</label><input id="i9_a_auth"></div></div>
    <div class="row"><div><label>Document number</label><input id="i9_a_num"></div><div><label>Expiration date (if any)</label><input type="text" id="i9_a_exp" class="datefld" placeholder="MM/DD/YYYY" maxlength="10"></div></div>
    <div class="muted" style="font-size:11px;">For a passport + Form I-94 combination, put the I-94 number & details in Additional Information below.</div>
  </div>

  <div id="i9-listBC-block">
    <div class="sub">List B — identity</div>
    <div class="row"><div><label>Document title</label><select id="i9_b_title"><option value="">— select —</option>${i9Opts(I9_LISTB)}</select></div><div><label>Issuing authority</label><input id="i9_b_auth"></div></div>
    <div class="row"><div><label>Document number</label><input id="i9_b_num"></div><div><label>Expiration date (if any)</label><input type="text" id="i9_b_exp" class="datefld" placeholder="MM/DD/YYYY" maxlength="10"></div></div>
    <div class="sub">List C — employment authorization</div>
    <div class="row"><div><label>Document title</label><select id="i9_c_title"><option value="">— select —</option>${i9Opts(I9_LISTC)}</select></div><div><label>Issuing authority</label><input id="i9_c_auth"></div></div>
    <div class="row"><div><label>Document number</label><input id="i9_c_num"></div><div><label>Expiration date (if any)</label><input type="text" id="i9_c_exp" class="datefld" placeholder="MM/DD/YYYY" maxlength="10"></div></div>
  </div>

  <label style="margin-top:8px;">Additional information (optional)</label><input id="i9_addl">

  <div class="sh">Employer / Company <span style="font-weight:400;text-transform:none;">— used on all government forms (W-4, DE 4, I-9, 8850)</span></div>
  <div class="row"><div><label>First day of employment</label><input type="text" id="i9_day" class="datefld" placeholder="MM/DD/YYYY" maxlength="10" value="${fmtMDY(h.hire)}"></div><div><label>Company legal name</label><input id="i9_bizname" value="${savedBizName}"></div></div>
  <div class="row"><div><label>Company address</label><input id="i9_addr" value="${savedAddr}"></div><div><label>Name &amp; title of employer representative</label><input id="i9_rep" value="${rep}"></div></div>
  <div class="row"><div><label>Federal EIN <span class="req">*</span> (W-4 &amp; 8850)</label><input id="i9_ein" value="${savedEin}" placeholder="XX-XXXXXXX"></div><div><label>CA Employer Payroll Tax Account # (DE 4)</label><input id="i9_capayroll" value="${savedPayroll}" placeholder="XXX-XXXX-X"></div></div>
  <label class="ck" style="margin-top:10px;"><input type="checkbox" id="i9_ck"> I have physically examined the original document(s); they appear genuine and relate to this employee.</label>
  <div style="margin-top:8px;padding:8px 0 0;">
    <div class="muted" style="font-size:11px;text-transform:uppercase;">Employer Representative Signature</div>
    <div style="font-family:'Brush Script MT',cursive,'Segoe Script',cursive;font-size:24px;color:var(--navy);border-bottom:1px solid #cbd5e1;display:inline-block;padding:0 6px 2px;">${rep}</div>
  </div>
  <div class="actions"><button class="btn secondary" onclick="setView('hr')">&#8592; Back</button><button class="btn" onclick="verifyI9()">${h.i9_section2?'Save changes':'Complete I-9 §2 →'}</button></div></div>`;
  document.querySelectorAll('.datefld').forEach(attachDateMask);
  document.querySelectorAll('.datefld').forEach(attachDateMask);
 ['i9_a_exp','i9_b_exp','i9_c_exp','i9_day'].forEach(initHybridDateField);
  // Prefill from a previously-saved I-9 (reached via the I-9 HR tab's
  // "Edit I-9" button). First-time completion (h.i9_section2 absent)
  // renders exactly as before — nothing below runs in that case.
  if(h.i9_section2){
    const sd=h.i9_section2;
    const s=(id,v)=>{const e=$(id);if(e)e.value=v||'';};
    s('i9_a_title',sd.listA_title);s('i9_a_auth',sd.listA_auth);s('i9_a_num',sd.listA_num);s('i9_a_exp',fmtMDY(sd.listA_exp));
    s('i9_b_title',sd.listB_title);s('i9_b_auth',sd.listB_auth);s('i9_b_num',sd.listB_num);s('i9_b_exp',fmtMDY(sd.listB_exp));
    s('i9_c_title',sd.listC_title);s('i9_c_auth',sd.listC_auth);s('i9_c_num',sd.listC_num);s('i9_c_exp',fmtMDY(sd.listC_exp));
    s('i9_addl',sd.additional_info);
    s('i9_bizname',sd.employer_business_name);s('i9_addr',sd.employer_address);s('i9_rep',sd.employer_rep);
    s('i9_ein',sd.employer_ein);s('i9_capayroll',sd.ca_payroll_acct);
    if(sd.first_day) s('i9_day',fmtMDY(sd.first_day));
    const ck=$('i9_ck');if(ck)ck.checked=true;
    const path=sd.doc_path||'BC';
    const radio=document.querySelector('input[name="i9docpath"][value="'+path+'"]');if(radio)radio.checked=true;
    i9DocPath(path);
  } else {
    i9DocPath('BC');
  }
}
async function verifyI9(){const h=hire();
  const focusField=function(id){const el=$(id);if(el&&el.scrollIntoView)el.scrollIntoView({behavior:'smooth',block:'center'});if(el&&el.focus)el.focus({preventScroll:true});};
  if(!$('i9_ck').checked){toast('Confirm you examined the documents');focusField('i9_ck');return;}
  const path=(document.querySelector('input[name="i9docpath"]:checked')||{}).value||'BC';
  if(path==='A'){ if(!val('i9_a_title')){toast('Select the List A document');focusField('i9_a_title');return;} }
  else { if(!val('i9_b_title')){toast('Select the List B document');focusField('i9_b_title');return;} if(!val('i9_c_title')){toast('Select the List C document');focusField('i9_c_title');return;} }
  if(!val('i9_ein')){toast('Enter the Federal EIN (required for W-4 and 8850)');focusField('i9_ein');return;}
  const s2={
    doc_path:path,
    listA_title:val('i9_a_title'),listA_auth:val('i9_a_auth'),listA_num:val('i9_a_num'),listA_exp:mdyToIso(val('i9_a_exp')),
    listB_title:val('i9_b_title'),listB_auth:val('i9_b_auth'),listB_num:val('i9_b_num'),listB_exp:mdyToIso(val('i9_b_exp')),
    listC_title:val('i9_c_title'),listC_auth:val('i9_c_auth'),listC_num:val('i9_c_num'),listC_exp:mdyToIso(val('i9_c_exp')),
    additional_info:val('i9_addl'),
    employer_business_name:val('i9_bizname'),employer_rep:employerSignatureName(val('i9_rep')),
    employer_ein:val('i9_ein'),ca_payroll_acct:val('i9_capayroll'),
    employer_name_address:(val('i9_bizname')+', '+val('i9_addr'))
  };
  localStorage.setItem('hh_company_name',val('i9_bizname'));
  localStorage.setItem('hh_company_addr',val('i9_addr'));
  localStorage.setItem('hh_company_ein',val('i9_ein'));
  localStorage.setItem('hh_company_capayroll',val('i9_capayroll'));
  // Only advance status locally on genuine first-time completion — matches
  // the backend's own rule exactly (actionVerifyI9 only writes 'I9_done'
  // when the hire's status was 'A_done'). Editing an already-saved I-9
  // (status already I9_done/Training/etc.) leaves h.status untouched here
  // too, so the New Hires list never shows an incorrect regression even
  // before the next full refresh.
  if(h.status==='A_done') h.status='I9_done';
  h.i9_section2=s2;
  await save('verifyI9',{token:h.token,employer_address:val('i9_addr'),first_day:mdyToIso(val('i9_day')),section2:s2});
  toast('I-9 Section 2 verified & stored'); setView('hr');
}

/* ---- signature pad ---- */
function initSig(){const c=$('sigpad');if(!c)return;const r=c.getBoundingClientRect();c.width=r.width;c.height=r.height;const ctx=c.getContext('2d');ctx.lineWidth=2;ctx.lineCap='round';ctx.strokeStyle='#0f2038';let d=false,last=null;
  const pos=e=>{const b=c.getBoundingClientRect();const p=e.touches?e.touches[0]:e;return{x:p.clientX-b.left,y:p.clientY-b.top};};
  const st=e=>{d=true;last=pos(e);e.preventDefault();};
  const mv=e=>{if(!d)return;const p=pos(e);ctx.beginPath();ctx.moveTo(last.x,last.y);ctx.lineTo(p.x,p.y);ctx.stroke();last=p;drawnSig=c.toDataURL('image/png');if(sigKind==='draw'){signature=drawnSig;setSigState(true);}e.preventDefault();};
  c.onmousedown=st;c.onmousemove=mv;window.onmouseup=()=>d=false;c.ontouchstart=st;c.ontouchmove=mv;c.ontouchend=()=>d=false;}
function clearSig(){const c=$('sigpad');if(!c)return;c.getContext('2d').clearRect(0,0,c.width,c.height);drawnSig=null;if(sigKind==='draw'){signature=null;setSigState(false);}}
const FORMS_COUNT=Object.keys(FORMS).length;
(async function(){var tok=APPLICANT_TOKEN;
  if(tok){
    currentToken=tok;var ph=APPLICANT_PHASE;
    var idx=hires.findIndex(function(x){return x.token===tok;});
    if(APPLICANT_HIRE){if(idx>=0)hires[idx]=APPLICANT_HIRE;else hires.unshift(APPLICANT_HIRE);}
    else if(idx<0){hires.unshift({token:tok,first:'',last:'',email:'',position:'',site:'',hire:'',status:ph==='B'?'B_sent':'A_sent'});}
    // The page template can be cached by Apps Script. Fetch the row once more
    // so invitees always receive the HR manager's latest details.
    const fresh=await loadHireByToken(tok);
    if(fresh){const freshIdx=hires.findIndex(function(x){return x.token===tok;});if(freshIdx>=0)hires[freshIdx]=fresh;else hires.unshift(fresh);}
    view=ph==='B'?'b':'a';
  } else if(APPS_SCRIPT_URL){
    await loadAllHires();
  }
  if(tok){var vs=document.querySelector('.viewswitch');if(vs)vs.style.display='none';}
  else{var db=$('docsNavBtn');if(db)db.style.display='inline-block';var dl=$('deletedNavBtn');if(dl)dl.style.display='inline-block';var i9h=$('i9hrNavBtn');if(i9h)i9h.style.display='inline-block';var bb=$('backToWorkspaceBtn');if(bb)bb.style.display='inline-block';}
  render();
})();
</script></body></html>
