{"id":85,"date":"2026-09-22T04:32:46","date_gmt":"2026-09-22T04:32:46","guid":{"rendered":"https:\/\/gwkitchen.com\/wp2026\/?page_id=85"},"modified":"2026-12-03T04:02:01","modified_gmt":"2026-12-03T04:02:01","slug":"gw-employee-portal","status":"publish","type":"page","link":"https:\/\/gwkitchen.com\/wp2026\/?page_id=85","title":{"rendered":"Employee Portal"},"content":{"rendered":"\n<style data-wp-block-html=\"css\">\n\/* GW Kitchen & Bath \u2014 Employee Portal Phase 1 responsive CSS *\/\n.gw-login,.gw-login *{box-sizing:border-box;min-width:0}\n.gw-login{width:100%;max-width:420px;margin:30px auto;padding:28px;background:#f5f9ff;border:1px solid #d5e4f5;border-radius:14px;color:#243447;font-size:16px;line-height:1.5}\n.gw-login:has(#gw-job-search:not([hidden])){max-width:960px}\n.gw-login [hidden]{display:none!important}\n.gw-login:has(#gw-job-search:not([hidden]))>h2{display:none}\n.gw-login h2{color:#174a80;text-align:center;font-size:25px;margin:12px 0 22px}\n.gw-login h3{color:#174a80;font-size:21px;margin:12px 0 20px}\n.gw-login h4{color:#245787;font-size:18px;margin:22px 0 12px}\n.gw-login label{display:block;margin:16px 0 7px;font-weight:600;font-size:15px}\n.gw-login input:not([type=checkbox]),.gw-login select,.gw-login textarea{display:block;width:100%;max-width:100%;min-height:48px;padding:12px 14px;border:1px solid #aabbd0;border-radius:8px;background:#fff;color:#243447;font:inherit;font-size:16px;line-height:1.4}\n.gw-login textarea{min-height:100px;resize:vertical}\n.gw-login input[type=file]{height:auto;padding:12px}\n.gw-login label.gw-remember,.gw-login label:has(>input[type=checkbox]){display:flex;align-items:flex-start;gap:12px;margin:18px 0;font-size:16px;font-weight:500;cursor:pointer}\n.gw-login input[type=checkbox]{display:inline-block;flex:0 0 22px;width:22px;height:22px;min-width:22px;margin:1px 0 0;padding:0;accent-color:#1769aa;cursor:pointer}\n.gw-login button{display:block;width:100%;max-width:100%;min-height:48px;margin-top:16px;padding:12px 16px;background:#1769aa;color:#fff;border:0;border-radius:9px;font:inherit;font-weight:600;line-height:1.35;text-align:center;white-space:normal;overflow-wrap:anywhere;cursor:pointer;touch-action:manipulation}\n.gw-login button:hover:not(:disabled){background:#12568d}\n.gw-login button:disabled{opacity:.55;cursor:not-allowed}\n.gw-login :is(button,input,select,textarea):focus-visible{outline:3px solid #70a9e0;outline-offset:2px}\n.gw-login #gw-language-switcher{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:6px;margin-bottom:14px}\n.gw-login #gw-language-switcher .gw-lang-btn{min-width:0;min-height:40px;margin:0;padding:8px 4px;font-size:14px}\n.gw-login #gw-language-switcher .gw-lang-btn.active{outline:2px solid #0b4f9c;outline-offset:2px}\n.gw-login #gw-job-search{width:100%}\n.gw-login .gw-search-row{display:grid;grid-template-columns:minmax(0,1fr) minmax(90px,auto);align-items:stretch;gap:8px}\n.gw-login .gw-search-row button{width:auto;margin:0;padding:8px 12px}\n.gw-login #gw-job-result{white-space:pre-line;overflow-wrap:anywhere;line-height:1.7}\n.gw-login #gw-job-dashboard{width:100%;margin-top:24px;padding-top:18px;border-top:2px solid #d5e4f5}\n.gw-login :is(#gw-measurement-form,#gw-preparation-form,#gw-photo-form,#gw-installer-review-form){width:100%;max-width:100%;margin:18px 0;padding:20px;background:#fff;border:1px solid #d5e4f5;border-radius:12px}\n.gw-login #gw-photo-gallery{width:100%;max-width:100%;margin-top:20px;overflow-wrap:anywhere}\n.gw-login #gw-photo-gallery img{display:block;width:100%;max-width:400px;height:auto;border-radius:8px}\n.gw-login #gw-photo-gallery>button{max-width:400px}\n.gw-login :is(p,section,div){overflow-wrap:anywhere}\n.gw-login [role=status]{line-height:1.6}\n.gw-login table{display:block;max-width:100%;overflow-x:auto}\n\/* Compact fixed-width job cards; same dimensions across dashboard groups *\/\n.gw-login #gw-monthly-job-ids .gw-board-grid{display:grid;grid-template-columns:repeat(auto-fill,128px);gap:8px;justify-content:start}\n.gw-login #gw-monthly-job-ids .gw-job-icon{width:128px;height:84px;min-height:84px;margin:0;padding:7px 4px;cursor:pointer}\n.gw-login #gw-monthly-job-ids .gw-job-code{font-size:13px;white-space:nowrap;overflow-wrap:normal}\n.gw-login #gw-monthly-job-ids .gw-job-address{display:block;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;font-size:12px}\n.gw-login #gw-monthly-job-ids .gw-job-stars{display:flex;justify-content:center;gap:7px}\n\/* Shared layout hooks for Phase 1 JavaScript *\/\n.gw-login :is(.gw-action-row,.gw-status-row,.gw-job-heading-row){display:flex;align-items:center;flex-wrap:wrap;gap:8px}\n.gw-login :is(.gw-action-row,.gw-status-row) > :is(button,select){flex:1 1 110px;width:auto;margin:0}\n.gw-login .gw-job-info-header{padding:12px;background:#fff;border:1px solid #d5e4f5;border-radius:10px;margin-bottom:14px}\n.gw-login .gw-dashboard-footer,.gw-login .gw-dashboard-entrances{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:8px;margin:16px 0}\n.gw-login :is(.gw-dashboard-footer,.gw-dashboard-entrances) button{margin:0;padding:10px 4px;font-size:13px;min-height:52px}\n.gw-login .gw-gallery-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(100px,1fr));gap:8px}\n.gw-login .gw-gallery-grid img{width:100%;aspect-ratio:1;object-fit:cover;border-radius:8px;cursor:pointer}\n@media(max-width:600px){.gw-login{max-width:100%;margin:12px auto;padding:16px;border-radius:10px}.gw-login:has(#gw-job-search:not([hidden])){max-width:100%}.gw-login h2{font-size:23px}.gw-login h3{font-size:20px}.gw-login h4{font-size:17px}.gw-login :is(#gw-measurement-form,#gw-preparation-form,#gw-photo-form,#gw-installer-review-form){padding:14px;margin:14px 0}.gw-login #gw-photo-gallery img{max-width:100%}}\n@media(max-width:360px){.gw-login{padding:10px}.gw-login :is(#gw-measurement-form,#gw-preparation-form,#gw-photo-form,#gw-installer-review-form){padding:10px}.gw-login #gw-monthly-job-ids .gw-board-grid{gap:6px}}\n\n\/* Revision 2: responsive layout; state and gallery behavior supplied by Revision 2 JS. *\/\n.gw-login{font-size:16px;line-height:1.5;width:100%;max-width:420px;}\n.gw-login:has(#gw-job-search:not([hidden])),.gw-login:has(#gw-focused-job-details:not([hidden])){max-width:1100px!important;width:100%!important;}\n.gw-login #gw-focused-job-details{width:100%;max-width:100%!important;margin:14px 0;padding:18px;}\n.gw-login #gw-office-portal-link{position:static!important;float:none!important;display:block;margin:0 0 12px!important;}\n.gw-login #gw-office-portal-link[hidden]{display:none!important;}\n.gw-login #gw-language-switcher{clear:both;position:relative;gap:8px;}\n.gw-login #gw-language-switcher .gw-lang-btn{font-size:15px;min-height:44px;}\n.gw-login #gw-monthly-job-ids .gw-board-grid{grid-template-columns:repeat(auto-fill,132px);gap:10px;}\n.gw-login #gw-monthly-job-ids .gw-job-icon{width:132px;height:86px;min-height:86px;}\n.gw-login #gw-monthly-job-ids .gw-job-code{font-size:14px;}\n.gw-login #gw-monthly-job-ids .gw-job-address{font-size:12px;}\n.gw-login #gw-monthly-job-ids .gw-job-stars{font-size:18px;letter-spacing:0;}\n.gw-login .gw-job-info-header .gw-field-code{font-size:22px;font-weight:800;color:#174c70;}\n.gw-login .gw-job-info-header .gw-field-customer{font-size:17px;font-weight:700;}\n.gw-login .gw-job-info-header .gw-field-address{font-size:15px;}\n.gw-login .gw-photo-heading-row{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:12px;}\n.gw-login .gw-photo-heading-row h3{margin:0;font-size:21px;}\n.gw-login .gw-photo-heading-row button{width:auto;margin:0;flex:0 0 auto;}\n.gw-login #gw-photo-editor{padding:12px 0;}\n.gw-login #gw-gallery-first{min-width:0;}\n.gw-login .gw-dashboard-footer{align-items:stretch;}\n.gw-login .gw-dashboard-footer :is(button,a){position:static!important;display:flex;align-items:center;justify-content:center;width:100%!important;margin:0!important;min-height:48px;padding:8px 5px!important;background:#1769aa;color:white;border-radius:8px;text-align:center;font-size:14px;text-decoration:none;}\n.gw-login .gw-dashboard-footer [hidden]{display:none!important;}\n.gw-login .gw-action-row{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px;margin-bottom:12px;}\n.gw-login .gw-action-row>button{width:100%!important;margin:0!important;}\n.gw-login .gw-status-row{display:flex;flex-wrap:wrap;gap:8px;align-items:center;}\n.gw-login .gw-status-row select{width:auto;flex:1 1 130px;}\n.gw-login #gw-photo-gallery img{cursor:zoom-in;}\n.gw-login #gw-gallery-first #gw-photo-gallery{margin-top:0;}\n.gw-login #gw-focused-job-details .gw-field-action{font-size:16px;min-height:96px;}\n.gw-login #gw-focused-job-details .gw-field-action small{font-size:13px;}\n@media(max-width:600px){\n.gw-login{padding:12px;}\n.gw-login #gw-focused-job-details{padding:12px;}\n.gw-login #gw-monthly-job-ids .gw-board-grid{grid-template-columns:repeat(auto-fill,minmax(125px,1fr));gap:8px;}\n.gw-login #gw-monthly-job-ids .gw-job-icon{width:100%;}\n.gw-login .gw-dashboard-footer :is(button,a),.gw-login .gw-dashboard-entrances button{font-size:12px;}\n.gw-login .gw-photo-heading-row h3{font-size:18px;}\n}\n\n\/* Revision 3: preserve tested job cards and gallery; style new controls. *\/\n.gw-login .gw-dashboard-footer{grid-auto-rows:1fr;align-items:stretch;}\n.gw-login .gw-dashboard-footer > :is(button,a){height:100%!important;min-height:52px!important;align-self:stretch;box-sizing:border-box;line-height:1.35!important;}\n.gw-login :is(.gw-photo-source-actions,.gw-photo-submit-actions,.gw-measurement-actions){display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px;margin:12px 0;align-items:stretch;}\n.gw-login :is(.gw-photo-source-actions,.gw-photo-submit-actions,.gw-measurement-actions)>button{margin:0!important;width:100%;min-height:48px;}\n.gw-login #gw-gallery-cancel{background:#fff;color:#1769aa;border:1px solid #aabbd0;}\n.gw-login #gw-photo-editor:has(#gw-photo-source-actions:not([hidden])) :is(#gw-photo-file,label[for=\"gw-photo-file\"]){display:none!important;}\n.gw-login #gw-camera-file[hidden]{display:none!important;}\n.gw-login .gw-pending-photo-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(100px,1fr));gap:10px;margin:12px 0;}\n.gw-login .gw-pending-photo{position:relative;border:1px solid #d5e4f5;border-radius:8px;overflow:hidden;}\n.gw-login .gw-pending-photo img{display:block;width:100%;aspect-ratio:1;object-fit:cover;}\n.gw-login .gw-pending-photo button{position:absolute;top:4px;right:4px;width:36px;min-height:36px;margin:0;padding:4px;background:#fff;color:#a51e25;border:1px solid #d5e4f5;}\n.gw-login .gw-status-row select{min-height:44px;font-size:14px;}\n.gw-login .gw-photo-delete{background:#a51e25;color:#fff;}\n@media(max-width:600px){.gw-login :is(.gw-photo-source-actions,.gw-photo-submit-actions,.gw-measurement-actions)>button{font-size:14px;padding:8px 4px;}.gw-login .gw-status-row{gap:6px;}}\n\n\/* Revision 4: center Office Portal link and keep preview grid visible. *\/\n.gw-login .gw-dashboard-footer > #gw-office-portal-link:not([hidden]){display:flex!important;align-items:center!important;justify-content:center!important;padding:0 5px!important;line-height:1.35!important;}\n.gw-login #gw-photo-pending-list.gw-pending-photo-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(90px,1fr));gap:10px;}\n\n.gw-v5-status{display:grid;grid-template-columns:1fr 1fr;gap:6px;margin-top:8px}.gw-v5-status select{min-width:0;width:100%;font-size:14px}.gw-v5-message{grid-column:1\/-1;font-size:12px;font-weight:400}\n<\/style>\n\n<script data-wp-block-html=\"js\">\n\/\/ GW Employee Portal Revision 12.1RE17.4 \u2014 Shared job header and compact additional work\n(function () {\n  function startPortal() {\n    const URL = \"https:\/\/tepzhgerltbdbhcgksog.supabase.co\";\n    const KEY = \"sb_publishable_12lkMKENfEprSCo__ldjhQ_1Yqd2V0U\";\n    const STORAGE_KEY = \"gw-portal-auth\";\n\n    const form = document.getElementById(\"gw-login-form\");\n    const email = document.getElementById(\"gw-email\");\n    const password = document.getElementById(\"gw-password\");\n    const remember = document.getElementById(\"gw-remember\");\n    const message = document.getElementById(\"gw-login-message\");\nconst jobSearch = document.getElementById(\"gw-job-search\");\nconst setPasswordForm =\n  document.getElementById(\"gw-set-password\");\n\nconst newPassword =\n  document.getElementById(\"gw-new-password\");\n\nconst confirmPassword =\n  document.getElementById(\"gw-confirm-password\");\n\nconst savePassword =\n  document.getElementById(\"gw-save-password\");\n\nconst passwordMessage =\n  document.getElementById(\"gw-password-message\");\n    if (!form || !email || !password || !remember || !message ||\n        !setPasswordForm || !newPassword || !confirmPassword ||\n        !savePassword || !passwordMessage) return;\n\n    \/\/ Keep the password form outside the login form, so either can be hidden.\n    if (form.contains(setPasswordForm)) form.insertAdjacentElement(\"afterend\", setPasswordForm);\n    setPasswordForm.hidden = true;\n    \/\/ Manual password reset controls removed from the Portal UI.\n    let recoveringPassword = false;\n    \/\/ Remember only a short-lived recovery *intent*, never the email link,\n    \/\/ access token, new password, or app password. A mobile browser may reload\n    \/\/ when switching to another app, after Supabase has cleaned the URL.\n    const RECOVERY_MARKER_KEY = \"gw-portal-recovery-pending-v1\";\n    const RECOVERY_MARKER_MS = 30 * 60 * 1000;\n    function clearRecoveryMarker() {\n      try { localStorage.removeItem(RECOVERY_MARKER_KEY); } catch (_error) { \/* best effort *\/ }\n    }\n    function getRecoveryMarker() {\n      try {\n        const raw = localStorage.getItem(RECOVERY_MARKER_KEY);\n        if (!raw) return null;\n        const marker = JSON.parse(raw);\n        if (!marker || typeof marker.userId !== \"string\" || !marker.userId ||\n            !Number.isFinite(marker.createdAt) || marker.createdAt > Date.now() ||\n            Date.now() - marker.createdAt > RECOVERY_MARKER_MS) {\n          clearRecoveryMarker();\n          return null;\n        }\n        return marker;\n      } catch (_error) {\n        clearRecoveryMarker();\n        return null;\n      }\n    }\n    function saveRecoveryMarker(userId) {\n      if (typeof userId !== \"string\" || !userId) return;\n      try {\n        const existing = getRecoveryMarker();\n        if (existing && existing.userId === userId) return; \/\/ Do not extend the window on app switches.\n        localStorage.setItem(RECOVERY_MARKER_KEY, JSON.stringify({\n          userId: userId, createdAt: Date.now()\n        }));\n      } catch (_error) { \/* recovery still works while the current page stays open *\/ }\n    }\n    function showPasswordSetup() {\n      gw94SetName('');\n      gwScheduleReset();\n      recoveringPassword = true;\n      gw92ClearNotes();\n      authViewRequestId++;\n      form.hidden = true;\n      logout.hidden = true;\n      officePortalLink.hidden = true;\n      jobSearch.hidden = true;\n      monthlyJobPanel.hidden = true;\n      dashboard.hidden = true;\n      employeeDirectoryToggle.hidden = true;\n      employeeDirectoryPanel.hidden = true;\n      if (typeof resetBulletinBoard === \"function\") resetBulletinBoard();\n      const opening = setPasswordForm.hidden;\n      setPasswordForm.hidden = false;\n      if (opening) {\n        passwordMessage.textContent = \"Set your password to finish account setup.\";\n        newPassword.focus();\n      }\n    }\n    \/\/ Deliberate exit, not an automatic loss of the form when Safari reloads.\n    const cancelPasswordSetup = document.createElement(\"button\");\n    cancelPasswordSetup.type = \"button\";\n    cancelPasswordSetup.textContent = \"Cancel Password Setup \/ Return to Log In\";\n    cancelPasswordSetup.style.cssText = \"display:block;margin:12px 0;\";\n    setPasswordForm.appendChild(cancelPasswordSetup);\n    cancelPasswordSetup.addEventListener(\"click\", async function () {\n      if (!client || !recoveringPassword || cancelPasswordSetup.disabled) return;\n      if (!window.confirm(\"Cancel password setup and return to the login page?\")) return;\n      cancelPasswordSetup.disabled = true;\n      try {\n        const { error } = await client.auth.signOut();\n        if (error) throw error;\n        clearRecoveryMarker();\n        newPassword.value = \"\";\n        confirmPassword.value = \"\";\n        showSignedOut();\n        message.textContent = \"Password setup canceled. You can request another setup link.\";\n      } catch (_error) {\n        passwordMessage.textContent = \"Unable to exit securely. Please try again.\";\n      } finally {\n        cancelPasswordSetup.disabled = false;\n      }\n    });\n    if (!form || !email || !password || !remember || !message) return;\n\n    let client = null;\n    const gw94Greeting = document.createElement('p');\n    gw94Greeting.id = 'gw-signed-in-name';\n    gw94Greeting.hidden = true;\n    gw94Greeting.style.cssText = 'text-align:center;font-weight:700;color:#174a80;margin:0 0 12px;';\n    document.getElementById('gw-home-heading').insertAdjacentElement('afterend',gw94Greeting);\n    let gw94Name = '';\n    function gw94SetName(name){gw94Name=String(name||'').trim();gw94Greeting.hidden=!gw94Name;gw94Greeting.textContent=gw94Name?({en:'Welcome, ',zh:'\u6b61\u8fce\uff0c',es:'Bienvenido\/a, '}[getGwPortalLanguage()]||'Welcome, ')+gw94Name:'';}\n    window.addEventListener('gw-language-changed',()=>gw94SetName(gw94Name));\n\n    \/\/ ------------------------------------------------------------\n    \/\/ Bulletin Board translation bridge\n    \/\/ Uses the signed-in Supabase client to call gw-translate-text.\n    \/\/ Original database text is never overwritten.\n    \/\/ ------------------------------------------------------------\n    const gwTranslationCache = new Map();\n\n    async function gwTranslateTexts(texts, targetLang, mode = \"user\") {\n      const list = Array.isArray(texts) ? texts.map(function (v) {\n        return String(v == null ? \"\" : v);\n      }) : [];\n\n      if (!list.length || targetLang === \"en\") return list;\n      if (!client) throw new Error(\"Portal connection is not ready.\");\n\n      const cacheKey = targetLang + \"|\" + mode + \"|\" + JSON.stringify(list);\n      if (gwTranslationCache.has(cacheKey)) {\n        return gwTranslationCache.get(cacheKey);\n      }\n\n      const { data, error } = await client.functions.invoke(\"gw-translate-text\", {\n        body: {\n          texts: list,\n          target_lang: targetLang,\n          mode: mode\n        }\n      });\n\n      if (error) throw error;\n\n      if (!data || !Array.isArray(data.translations) ||\n          data.translations.length !== list.length) {\n        throw new Error(\"Invalid translation response.\");\n      }\n\n      const translated = data.translations.map(function (v) {\n        return String(v == null ? \"\" : v);\n      });\n\n      gwTranslationCache.set(cacheKey, translated);\n      return translated;\n    }\n\n\n    \/\/ RE3: scoped display-only translations; never write translated text to a record.\n    const gwRE3Labels = {\"Map\":[\"\u5730\u5716\",\"Mapa\"],\"Add Note\":[\"\u65b0\u589e\u5099\u8a3b\",\"A\u00f1adir nota\"],\"Measurement Photos\":[\"\u91cf\u5c3a\u7167\u7247\",\"Fotos de medici\u00f3n\"],\"+ Add Note\": [\"+ \u65b0\u589e\u5099\u8a3b\", \"+ A\u00f1adir nota\"], \"On-Site Work\": [\"\u73fe\u5834\u65bd\u5de5\", \"Trabajo en sitio\"], \"Field Job Details\": [\"\u73fe\u5834\u5de5\u7a0b\u8a73\u60c5\", \"Detalles del trabajo en sitio\"], \"\u2190 Back to Job Board\": [\"\u2190 \u8fd4\u56de\u5de5\u7a0b\u5217\u8868\", \"\u2190 Volver a la lista de trabajos\"], \"Important Job Notes\": [\"\u91cd\u8981\u5de5\u7a0b\u5099\u8a3b\", \"Notas importantes del trabajo\"], \"Before Photos\": [\"\u65bd\u5de5\u524d\u7167\u7247\", \"Fotos antes\"], \"After Photos\": [\"\u65bd\u5de5\u5f8c\u7167\u7247\", \"Fotos despu\u00e9s\"], \"Issue Photo\": [\"\u554f\u984c\u7167\u7247\", \"Fotos de problemas\"], \"Issue Photos\": [\"\u554f\u984c\u7167\u7247\", \"Fotos de problemas\"], \"Additional Work\": [\"\u984d\u5916\u5de5\u7a0b\", \"Trabajo adicional\"], \"Extra on-site work\": [\"\u984d\u5916\u73fe\u5834\u65bd\u5de5\", \"Trabajo adicional en sitio\"], \"Before installation\": [\"\u5b89\u88dd\u524d\", \"Antes de instalar\"], \"After installation\": [\"\u5b89\u88dd\u5f8c\", \"Despu\u00e9s de instalar\"], \"Issues & damage\": [\"\u554f\u984c\u53ca\u640d\u58de\", \"Problemas y da\u00f1os\"], \"Job Details\": [\"\u5de5\u7a0b\u8a73\u60c5\", \"Detalles del trabajo\"], \"Measurements & specifications\": [\"\u91cf\u5c3a\u53ca\u898f\u683c\", \"Medidas y especificaciones\"], \"Completed\": [\"\u5df2\u5b8c\u6210\", \"Completado\"], \"Not completed\": [\"\u672a\u5b8c\u6210\", \"No completado\"], \"Checking\u2026\": [\"\u6aa2\u67e5\u4e2d\u2026\", \"Comprobando\u2026\"], \"Photo count unavailable\": [\"\u7167\u7247\u6578\u91cf\u672a\u80fd\u53d6\u5f97\", \"Cantidad de fotos no disponible\"], \"Status unavailable\": [\"\u72c0\u614b\u672a\u80fd\u53d6\u5f97\", \"Estado no disponible\"], \"No Issue\": [\"\u6c92\u6709\u554f\u984c\", \"Sin problemas\"], \"Issue\": [\"\u6709\u554f\u984c\", \"Problema\"], \"Solved\": [\"\u5df2\u89e3\u6c7a\", \"Resuelto\"], \"In Process\": [\"\u9032\u884c\u4e2d\", \"En proceso\"], \"Fabricated\": [\"\u5df2\u52a0\u5de5\", \"Fabricado\"], \"On Hold\": [\"\u66ab\u505c\", \"En espera\"], \"Copy Address\": [\"\u8907\u88fd\u5730\u5740\", \"Copiar direcci\u00f3n\"], \"\ud83d\udccd Map\": [\"\ud83d\udccd \u5730\u5716\", \"\ud83d\udccd Mapa\"], \"\u260e Call\": [\"\u260e \u81f4\u96fb\", \"\u260e Llamar\"], \"+ Add Location\": [\"+ \u65b0\u589e\u4f4d\u7f6e\", \"+ Agregar ubicaci\u00f3n\"], \"Save Note\": [\"\u5132\u5b58\u5099\u8a3b\", \"Guardar nota\"], \"Add Photo\": [\"\u65b0\u589e\u7167\u7247\", \"Agregar foto\"], \"Take Photo\": [\"\u62cd\u7167\", \"Tomar foto\"], \"Select Photos\": [\"\u9078\u64c7\u7167\u7247\", \"Seleccionar fotos\"], \"Remove\": [\"\u79fb\u9664\", \"Eliminar\"], \"Write the location and work details...\": [\"\u8f38\u5165\u4f4d\u7f6e\u53ca\u65bd\u5de5\u8a73\u60c5\u2026\", \"Escriba la ubicaci\u00f3n y los detalles del trabajo...\"], \"Photo description (optional)\": [\"\u7167\u7247\u8aaa\u660e\uff08\u9078\u586b\uff09\", \"Descripci\u00f3n de la foto (opcional)\"], \"Note saved.\": [\"\u5099\u8a3b\u5df2\u5132\u5b58\u3002\", \"Nota guardada.\"], \"Photos saved.\": [\"\u7167\u7247\u5df2\u5132\u5b58\u3002\", \"Fotos guardadas.\"], \"Translate\": [\"\u7ffb\u8b6f\", \"Traducir\"], \"Show Original\": [\"\u986f\u793a\u539f\u6587\", \"Mostrar original\"]};\n    function gwRE3Text(source) {\n      const lang=getGwPortalLanguage(), i=lang==='zh'?0:lang==='es'?1:-1;\n      if(i<0)return source;\n      return source.split(' \u00b7 ').map(part=>{\n        const m=\/^(\\d+) Photos?$\/.exec(part);\n        if(m)return m[1]+(i===0?' \u5f35\u7167\u7247':m[1]==='1'?' foto':' fotos');\n        return gwRE3Labels[part]?.[i]||part;\n      }).join(' \u00b7 ');\n    }\n    function gwRE3Label(el,source){el.dataset.gwRe3Label=source;el.textContent=gwRE3Text(source);return el;}\n    function gwRE3Optional(el,source){\n      if(!source||!String(source).trim())return;\n      const wrap=document.createElement('span');wrap.dataset.gwRe3Optional='1';wrap.style.cssText='display:block;white-space:pre-wrap;';\n      const original=document.createElement('span');original.dataset.gwRe3Original='1';original.textContent=String(source);\n      const translated=document.createElement('span');translated.dataset.gwRe3Translated='1';translated.hidden=true;\n      const button=document.createElement('button');button.type='button';button.dataset.gwRe3Toggle='1';button.style.cssText='display:block;width:auto;min-height:32px;padding:4px 10px;margin:6px 0;font-size:13px;background:#fff;color:#174a80;border:1px solid #aabbd0;';\n      const status=document.createElement('span');status.dataset.gwRe3Status='1';status.setAttribute('role','status');status.style.cssText='display:block;font-size:12px;';\n      button.textContent=gwRE3Text('Translate');button.hidden=getGwPortalLanguage()==='en';button.style.display=button.hidden?'none':'block';wrap.append(original,translated,button,status);el.replaceChildren(wrap);\n    }\n    function gwRE3Reset(wrap){\n      const o=wrap.querySelector('[data-gw-re3-original]'),t=wrap.querySelector('[data-gw-re3-translated]'),b=wrap.querySelector('[data-gw-re3-toggle]'),m=wrap.querySelector('[data-gw-re3-status]');\n      if(!o||!t||!b||!m)return;delete wrap.dataset.gwRe3Request;o.hidden=false;t.hidden=true;t.textContent='';b.disabled=false;b.hidden=getGwPortalLanguage()==='en';b.style.display=b.hidden?'none':'block';b.textContent=gwRE3Text('Translate');m.textContent='';\n    }\n    let gwRE3Sequence=0;\n    document.addEventListener('click',async event=>{\n      const b=event.target.closest?.('[data-gw-re3-toggle]');if(!b||b.disabled||!client||logout.hidden)return;\n      const wrap=b.closest('[data-gw-re3-optional]'),o=wrap.querySelector('[data-gw-re3-original]'),t=wrap.querySelector('[data-gw-re3-translated]'),m=wrap.querySelector('[data-gw-re3-status]');\n      if(!t.hidden){gwRE3Reset(wrap);return;}\n      const lang=getGwPortalLanguage();if(lang==='en')return;\n      const req=String(++gwRE3Sequence);wrap.dataset.gwRe3Request=req;b.disabled=true;m.textContent=lang==='zh'?'\u7ffb\u8b6f\u4e2d\u2026':'Traduciendo\u2026';\n      const current=()=>wrap.isConnected&&!logout.hidden&&getGwPortalLanguage()===lang&&wrap.dataset.gwRe3Request===req;\n      try{\n        \/\/ Keep numeric tokens, access credentials and job identifiers out of translation requests.\n        const protectedParts=[];const original=o.textContent;\n        const masked=original.replace(\/\\b(?:code|pin|password|passcode|c\u00f3digo|clave)\\s*[:=#]?\\s*[A-Za-z0-9#*_-]+|(?:\u9580\u7981\u78bc|\u5bc6\u78bc|\u4ee3\u78bc)\\s*[:\uff1a]?\\s*[A-Za-z0-9#*_-]+|[A-Za-z0-9_#*.\/-]*\\d[A-Za-z0-9_#*.\/-]*\/gi,part=>{const token='GWKEEP'+String.fromCharCode(65+protectedParts.length%26)+Math.floor(protectedParts.length\/26)+'END';protectedParts.push([token,part]);return token;});\n        let result=(await gwTranslateTexts([masked],lang,'user'))[0];if(!result||typeof result!=='string')throw Error('Translation unavailable');\n        let last=-1;for(const [token] of protectedParts){const pos=result.indexOf(token);if(pos<=last||result.split(token).length!==2)throw Error('Protected text changed');last=pos;}\n        for(const [token,part] of protectedParts)result=result.replace(token,()=>part);\n        if(!current())return;t.textContent=result;t.hidden=false;o.hidden=true;b.textContent=gwRE3Text('Show Original');m.textContent=lang==='zh'?'\u6a5f\u5668\u7ffb\u8b6f\uff0c\u65bd\u5de5\u524d\u8acb\u6838\u5c0d\u539f\u6587\u3002':'Traducci\u00f3n autom\u00e1tica; revise el original antes de trabajar.';\n      }catch(_error){if(current()){o.hidden=false;t.hidden=true;m.textContent=lang==='zh'?'\u672a\u80fd\u5b89\u5168\u7ffb\u8b6f\uff0c\u8acb\u53c3\u95b1\u539f\u6587\u3002':'No se pudo traducir con seguridad. Consulte el original.';}}\n      finally{if(current())b.disabled=false;}\n    });\n    window.addEventListener('gw-language-changed',()=>{\n      document.querySelectorAll('[data-gw-re3-label]').forEach(e=>{e.textContent=gwRE3Text(e.dataset.gwRe3Label);});\n      document.querySelectorAll('[data-gw-re3-optional]').forEach(gwRE3Reset);\n      document.querySelectorAll('[data-gw-re3-placeholder]').forEach(e=>{e.placeholder=gwRE3Text(e.dataset.gwRe3Placeholder);});\n    });\n\n    function getGwPortalLanguage() {\n      try {\n        const lang = localStorage.getItem(\"gwPortalLanguage\") || \"en\";\n        return lang === \"zh\" || lang === \"es\" ? lang : \"en\";\n      } catch (_error) {\n        return \"en\";\n      }\n    }\n\n    \/\/ Only these database fields are natural-language notes and are safe\n    \/\/ to translate for display. Core job\/customer\/material data is excluded.\n    const GW_SAFE_WORK_NOTE_COLUMNS = new Set([\n      \"field_notes\",\n      \"plumbing_notes\",\n      \"electrical_notes\",\n      \"protection_notes\",\n      \"special_access_notes\",\n      \"installer_notes\"\n    ]);\n\n    async function translateSafeWorkNoteElement(element) {\n      if (!element || !element.dataset) return;\n\n      const source = element.dataset.gwSafeNoteSource || \"\";\n      const lang = getGwPortalLanguage();\n\n      \/\/ English always restores the exact stored\/original text.\n      if (lang === \"en\" || !source) {\n        element.textContent = source || \"\u2014\";\n        return;\n      }\n\n      if (!client) return;\n\n      const requestedLang = lang;\n\n      try {\n        const translated = await gwTranslateTexts([source], requestedLang, \"user\");\n\n        if (getGwPortalLanguage() !== requestedLang) return;\n        if (!element.isConnected) return;\n\n        element.textContent = translated[0] || source;\n      } catch (error) {\n        \/\/ Translation failure must never affect the saved work record or UI.\n        element.textContent = source;\n        console.warn(\"GW work-note translation failed:\", error);\n      }\n    }\n\n    function refreshSafeWorkNoteTranslations() {\n      document.querySelectorAll(\"[data-gw-safe-note-source]\").forEach(function (element) {\n        translateSafeWorkNoteElement(element);\n      });\n    }\n\n    async function translateBulletinCard(titleElement, bodyElement, decoded) {\n      const lang = getGwPortalLanguage();\n      if (lang === \"en\" || !client) return;\n\n      const requestedLang = lang;\n\n      try {\n        const translated = await gwTranslateTexts(\n          [decoded.title || \"\", decoded.body || \"\"],\n          requestedLang,\n          \"user\"\n        );\n\n        \/\/ Do not write an old translation if the user changed language\n        \/\/ while the request was in flight.\n        if (getGwPortalLanguage() !== requestedLang) return;\n        if (!titleElement.isConnected || !bodyElement.isConnected) return;\n\n        titleElement.textContent = translated[0] || decoded.title || \"\";\n        bodyElement.textContent = translated[1] || decoded.body || \"\";\n      } catch (error) {\n        \/\/ Translation failure must never break Bulletin Board.\n        console.warn(\"GW Bulletin translation failed:\", error);\n      }\n    }\n\n    \/\/ Re-render Bulletin Board when the user switches language.\n    window.addEventListener(\"gw-language-changed\", function () {\n      if (!client || logout.hidden) return;\n\n      \/\/ Final Measurement \/ Site Preparation safe note fields.\n      refreshSafeWorkNoteTranslations();\n\n      \/\/ Bulletin Board title\/body.\n      if (typeof loadBulletinNotes === \"function\") {\n        loadBulletinNotes().catch(function (error) {\n          console.warn(\"Unable to refresh Bulletin Board translation:\", error);\n        });\n      }\n    });\n\n    let staySignedIn = !!localStorage.getItem(STORAGE_KEY);\n\n    const logout = document.createElement(\"button\");\n    logout.type = \"button\";\n    logout.textContent = \"Log Out\";\n    logout.hidden = true;\n    form.parentElement.appendChild(logout);\n\n    \/\/ Portal navigation only; Office Portal independently checks login and access.\n    const officePortalLink = document.createElement(\"a\");\n    officePortalLink.id = \"gw-office-portal-link\";\n    officePortalLink.href = \"https:\/\/gwkitchen.com\/wp2026\/?page_id=272\";\n    officePortalLink.target = \"_blank\";\n    officePortalLink.rel = \"noopener noreferrer\";\n    officePortalLink.textContent = \"Office Portal \/ \u8fa6\u516c\u5ba4\u5165\u53e3\";\n    officePortalLink.hidden = true;\n    officePortalLink.style.cssText =\n      \"box-sizing:border-box;padding:10px 16px;margin:0 0 16px;\" +\n      \"border:1px solid #1769aa;border-radius:8px;background:#1769aa;\" +\n      \"color:#fff;font-weight:600;text-decoration:none;text-align:center;\";\n    form.parentElement.insertBefore(officePortalLink, form.parentElement.firstChild);\n\n\n    \/\/ Owner-only employee directory. The database RPC checks owner status;\n    \/\/ non-owners never get the full roster through this interface.\n    const employeeDirectoryToggle = document.createElement(\"button\");\n    employeeDirectoryToggle.type = \"button\";\n    employeeDirectoryToggle.id = \"gw-employee-directory-toggle\";\n    employeeDirectoryToggle.textContent = \"Employee Accounts (Owner Only)\";\n    employeeDirectoryToggle.hidden = true;\n    employeeDirectoryToggle.setAttribute(\"aria-expanded\", \"false\");\n    employeeDirectoryToggle.style.cssText = \"width:100%;margin:12px 0;\";\n    const employeeDirectoryPanel = document.createElement(\"section\");\n    employeeDirectoryPanel.id = \"gw-employee-directory-panel\";\n    employeeDirectoryPanel.hidden = true;\n    employeeDirectoryPanel.style.cssText =\n      \"padding:16px;margin:12px 0 20px;border:1px solid #cbd5e1;border-radius:8px;\";\n    const employeeDirectoryHeading = document.createElement(\"h3\");\n    employeeDirectoryHeading.textContent = \"Employee Accounts (Owner Only)\";\n    const employeeDirectoryBody = document.createElement(\"div\");\n    const employeeDirectoryMessage = document.createElement(\"p\");\n    employeeDirectoryMessage.setAttribute(\"role\", \"status\");\n    employeeDirectoryPanel.append(\n      employeeDirectoryHeading, employeeDirectoryBody, employeeDirectoryMessage\n    );\n    \/\/ Owner-only invite form. The Edge Function independently verifies the caller's\n    \/\/ active Owner profile; hiding this UI is not the security boundary.\n    const inviteToggle = document.createElement(\"button\");\n    inviteToggle.type = \"button\";\n    inviteToggle.textContent = \"Add Employee\";\n    inviteToggle.style.cssText = \"display:block;width:100%;margin:12px 0;\";\n    inviteToggle.setAttribute(\"aria-expanded\", \"false\");\n    const inviteForm = document.createElement(\"form\");\n    inviteForm.hidden = true;\n    inviteForm.autocomplete = \"off\";\n    inviteForm.style.cssText = \"padding:12px;border:1px solid #cbd5e1;border-radius:8px;margin:8px 0 18px;\";\n    function inviteInput(labelText, type, maxLength) {\n      const label = document.createElement(\"label\");\n      label.textContent = labelText;\n      label.style.cssText = \"display:block;margin:8px 0;font-weight:600;\";\n      const input = document.createElement(\"input\");\n      input.type = type;\n      input.required = true;\n      input.maxLength = maxLength;\n      input.style.cssText = \"display:block;box-sizing:border-box;width:100%;font-size:16px;margin-top:5px;\";\n      input.autocomplete = \"off\";\n      label.appendChild(input);\n      inviteForm.appendChild(label);\n      return input;\n    }\n    const inviteName = inviteInput(\"Employee name\", \"text\", 100);\n    const inviteEmail = inviteInput(\"Employee email\", \"email\", 254);\n    const inviteRoleLabel = document.createElement(\"label\");\n    inviteRoleLabel.textContent = \"Employee role\";\n    inviteRoleLabel.style.cssText = \"display:block;margin:8px 0;font-weight:600;\";\n    const inviteRole = document.createElement(\"select\");\n    inviteRole.required = true;\n    inviteRole.style.cssText = \"display:block;width:100%;font-size:16px;margin-top:5px;\";\n    for (const [value, title] of [\n      [\"\", \"Select role\"], [\"installer\", \"Installer\"], [\"fabricator\", \"Fabricator\"],\n      [\"office\", \"Office\"], [\"project_manager\", \"Project Manager\"]\n    ]) {\n      const option = document.createElement(\"option\");\n      option.value = value;\n      option.textContent = title;\n      inviteRole.appendChild(option);\n    }\n    inviteRoleLabel.appendChild(inviteRole);\n    inviteForm.appendChild(inviteRoleLabel);\n    const inviteSubmit = document.createElement(\"button\");\n    inviteSubmit.type = \"submit\";\n    inviteSubmit.textContent = \"Send Employee Invitation\";\n    inviteSubmit.style.cssText = \"display:block;width:100%;margin:12px 0;\";\n    const inviteCancel = document.createElement(\"button\");\n    inviteCancel.type = \"button\";\n    inviteCancel.textContent = \"Cancel\";\n    inviteCancel.style.cssText = \"display:block;width:100%;margin:8px 0;\";\n    const inviteMessage = document.createElement(\"p\");\n    inviteMessage.setAttribute(\"role\", \"status\");\n    inviteMessage.setAttribute(\"aria-live\", \"polite\");\n    inviteForm.append(inviteSubmit, inviteCancel, inviteMessage);\n    employeeDirectoryPanel.insertBefore(inviteToggle, employeeDirectoryBody);\n    employeeDirectoryPanel.insertBefore(inviteForm, employeeDirectoryBody);\n    let inviteBusy = false;\n    function resetInviteForm() {\n      inviteForm.hidden = true;\n      inviteToggle.setAttribute(\"aria-expanded\", \"false\");\n      inviteName.value = \"\";\n      inviteEmail.value = \"\";\n      inviteRole.value = \"\";\n      inviteMessage.textContent = \"\";\n    }\n    inviteToggle.addEventListener(\"click\", function () {\n      if (employeeDirectoryPanel.hidden || employeeDirectoryToggle.hidden || logout.hidden || inviteBusy) return;\n      inviteForm.hidden = !inviteForm.hidden;\n      inviteToggle.setAttribute(\"aria-expanded\", String(!inviteForm.hidden));\n      if (!inviteForm.hidden) inviteName.focus();\n      else resetInviteForm();\n    });\n    inviteCancel.addEventListener(\"click\", function () {\n      if (!inviteBusy) resetInviteForm();\n    });\n    inviteForm.addEventListener(\"submit\", async function (event) {\n      event.preventDefault();\n      if (!client || logout.hidden || employeeDirectoryToggle.hidden ||\n          employeeDirectoryPanel.hidden || inviteForm.hidden || inviteBusy) return;\n      const displayName = inviteName.value.trim();\n      const employeeEmail = inviteEmail.value.trim().toLowerCase();\n      const role = inviteRole.value;\n      if (!displayName || displayName.length > 100 || \/[\\x00-\\x1f\\x7f]\/.test(displayName) ||\n          employeeEmail.length > 254 || !\/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$\/.test(employeeEmail) ||\n          ![\"installer\", \"fabricator\", \"office\", \"project_manager\"].includes(role)) {\n        inviteMessage.textContent = \"Enter a valid name, email and employee role.\";\n        return;\n      }\n      if (!window.confirm(\"Send an invitation to \" + employeeEmail +\n          \" as \" + role + \"? This will create an employee account with this role.\")) return;\n      inviteBusy = true;\n      inviteSubmit.disabled = true;\n      inviteCancel.disabled = true;\n      inviteToggle.disabled = true;\n      inviteMessage.textContent = \"Sending invitation...\";\n      try {\n        \/\/ supabase-js invokes the user-authenticated Edge Function using the\n        \/\/ current session. Never send a service-role or secret key from the page.\n        const { data, error } = await client.functions.invoke(\"gw-invite-employee\", {\n          body: { email: employeeEmail, displayName, role }\n        });\n        if (error || !data || data.invitationSent !== true || data.profileCreated !== true) {\n          const extra = data && typeof data.message === \"string\" ? data.message : \"\";\n          throw new Error(extra || \"Invitation could not be confirmed. Check Supabase before retrying.\");\n        }\n        if (logout.hidden || employeeDirectoryPanel.hidden) return;\n        resetInviteForm();\n        const refreshed = await loadEmployeeDirectory();\n        if (refreshed && !employeeDirectoryPanel.hidden && !logout.hidden)\n          employeeDirectoryMessage.textContent = \"Invitation sent and employee account created. \" +\n            \"The employee must open their email and set their own password.\";\n      } catch (_error) {\n        if (!logout.hidden && !employeeDirectoryPanel.hidden)\n          inviteMessage.textContent = \"Invitation not confirmed. Check Supabase Auth Users and employee_profiles before retrying; \" +\n            \"the email may already have been sent.\";\n      } finally {\n        inviteBusy = false;\n        inviteSubmit.disabled = false;\n        inviteCancel.disabled = false;\n        inviteToggle.disabled = false;\n      }\n    });\n    logout.insertAdjacentElement(\"afterend\", employeeDirectoryToggle);\n    employeeDirectoryToggle.insertAdjacentElement(\"afterend\", employeeDirectoryPanel);\n\n\n    \/\/ ================================================================\n    \/\/ BULLETIN BOARD \/ NOTES V2\n    \/\/ Separate in-Portal view, same browser tab. Uses existing bulletin RPCs.\n    \/\/ Title is stored inside note_text with a private prefix so no DB migration\n    \/\/ is required. Unread state is per signed-in user on this device\/browser.\n    \/\/ ================================================================\n    const BULLETIN_TITLE_PREFIX = \"[[GW_TITLE:\";\n    const BULLETIN_TITLE_SUFFIX = \"]]\";\n    const BULLETIN_SEEN_KEY = \"gw-bulletin-seen-v2\";\n\n    const bulletinEntry = document.createElement(\"button\");\n    bulletinEntry.type = \"button\";\n    bulletinEntry.id = \"gw-bulletin-entry\";\n    bulletinEntry.textContent = \"Bulletin Board\";\n    bulletinEntry.hidden = true;\n    bulletinEntry.style.cssText =\n      \"width:100%;margin:14px 0;padding:15px 16px;text-align:left;font-size:18px;font-weight:700;\" +\n      \"border:1px solid #b9c7d6;border-radius:10px;background:#fff;cursor:pointer;\";\nbulletinEntry.style.setProperty(\"color\", \"#ffffff\", \"important\");\nbulletinEntry.style.setProperty(\"-webkit-text-fill-color\", \"#ffffff\", \"important\");\n\n    const bulletinBoard = document.createElement(\"section\");\n    bulletinBoard.id = \"gw-bulletin-board\";\n    bulletinBoard.hidden = true;\n    bulletinBoard.style.cssText =\n      \"box-sizing:border-box;width:100%;margin:14px 0 20px;padding:16px;\" +\n      \"border:1px solid #cbd5e1;border-radius:10px;background:#fff;\";\n\n    const bulletinTop = document.createElement(\"div\");\n    bulletinTop.style.cssText =\n      \"display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;margin-bottom:14px;\";\n    const bulletinBack = document.createElement(\"button\");\n    bulletinBack.type = \"button\";\n    bulletinBack.textContent = \"\u2190 Back to Portal\";\n    bulletinBack.style.cssText = \"margin:0;padding:8px 10px;font-size:14px;\";\n    const bulletinHeading = document.createElement(\"h2\");\n    bulletinHeading.textContent = \"Bulletin Board\";\n    bulletinHeading.style.cssText = \"margin:0;font-size:26px;line-height:1.2;\";\n    const bulletinAdd = document.createElement(\"button\");\n    bulletinAdd.type = \"button\";\n    bulletinAdd.textContent = \"+ Add Announcement\";\n    bulletinAdd.hidden = true;\n    bulletinAdd.style.cssText = \"margin:0;padding:9px 12px;\";\n    bulletinTop.append(bulletinBack, bulletinHeading, bulletinAdd);\n\n    const bulletinMessage = document.createElement(\"p\");\n    bulletinMessage.setAttribute(\"role\", \"status\");\n    bulletinMessage.setAttribute(\"aria-live\", \"polite\");\n    bulletinMessage.style.cssText = \"margin:8px 0;font-size:14px;\";\n\n    const bulletinEditor = document.createElement(\"form\");\n    bulletinEditor.hidden = true;\n    bulletinEditor.autocomplete = \"off\";\n    bulletinEditor.style.cssText =\n      \"margin:12px 0 18px;padding:14px;border:1px solid #dbe3ea;border-radius:8px;background:#f8fafc;\";\n\n    function bulletinFieldLabel(labelText) {\n      const label = document.createElement(\"label\");\n      label.textContent = labelText;\n      label.style.cssText = \"display:block;margin:9px 0;font-weight:600;\";\n      return label;\n    }\n\n    const bulletinTitleLabel = bulletinFieldLabel(\"Title\");\n    const bulletinNoteTitle = document.createElement(\"input\");\n    bulletinNoteTitle.type = \"text\";\n    bulletinNoteTitle.required = true;\n    bulletinNoteTitle.maxLength = 200;\n    bulletinNoteTitle.placeholder = \"Example: Smith Kitchen \/ Tomorrow Installation\";\n    bulletinNoteTitle.style.cssText =\n      \"display:block;box-sizing:border-box;width:100%;font-size:17px;margin-top:5px;padding:9px;\";\n    bulletinTitleLabel.appendChild(bulletinNoteTitle);\n\n    const bulletinAudienceLabel = bulletinFieldLabel(\"For\");\n    const bulletinAudience = document.createElement(\"select\");\n    bulletinAudience.required = true;\n    bulletinAudience.style.cssText =\n      \"display:block;width:100%;font-size:16px;margin-top:5px;padding:8px;\";\n    for (const [value, label] of [\n      [\"everyone\", \"Everyone\"],\n      [\"installer\", \"Installer\"],\n      [\"fabricator\", \"Fabricator\"],\n      [\"office\", \"Office\"],\n      [\"project_manager\", \"Project Manager\"]\n    ]) {\n      const option = document.createElement(\"option\");\n      option.value = value;\n      option.textContent = label;\n      bulletinAudience.appendChild(option);\n    }\n    bulletinAudienceLabel.appendChild(bulletinAudience);\n\n    const bulletinJobLabel = bulletinFieldLabel(\"Job ID (optional)\");\n    const bulletinJob = document.createElement(\"input\");\n    bulletinJob.type = \"text\";\n    bulletinJob.maxLength = 80;\n    bulletinJob.placeholder = \"Example: 1234\";\n    bulletinJob.style.cssText =\n      \"display:block;box-sizing:border-box;width:100%;font-size:16px;margin-top:5px;padding:8px;\";\n    bulletinJobLabel.appendChild(bulletinJob);\n\n    const bulletinTextLabel = bulletinFieldLabel(\"Note\");\n    const bulletinText = document.createElement(\"textarea\");\n    bulletinText.required = true;\n    bulletinText.maxLength = 20000;\n    bulletinText.rows = 5;\n    bulletinText.placeholder = \"Example: Installation moved to Friday. Bring sink support tools.\";\n    bulletinText.style.cssText =\n      \"display:block;box-sizing:border-box;width:100%;font-size:18px;line-height:1.5;\" +\n      \"margin-top:5px;padding:9px;resize:vertical;\";\n    bulletinTextLabel.appendChild(bulletinText);\n\n    const bulletinSave = document.createElement(\"button\");\n    bulletinSave.type = \"submit\";\n    bulletinSave.textContent = \"Post Note\";\n    bulletinSave.style.cssText = \"margin:10px 8px 0 0;\";\n    const bulletinCancel = document.createElement(\"button\");\n    bulletinCancel.type = \"button\";\n    bulletinCancel.textContent = \"Cancel\";\n    bulletinCancel.style.cssText = \"margin:10px 0 0;\";\n    const bulletinEditorMessage = document.createElement(\"p\");\n    bulletinEditorMessage.setAttribute(\"role\", \"status\");\n    bulletinEditorMessage.style.cssText = \"margin:8px 0 0;font-size:14px;\";\n    bulletinEditor.append(\n      bulletinTitleLabel, bulletinTextLabel,\n      bulletinSave, bulletinCancel, bulletinEditorMessage\n    );\n\n    const bulletinOpenList = document.createElement(\"div\");\n    bulletinOpenList.id = \"gw-bulletin-open-notes\";\n\n    const bulletinCompletedToggle = document.createElement(\"button\");\n    bulletinCompletedToggle.type = \"button\";\n    bulletinCompletedToggle.textContent = \"Closed Announcements\";\n    bulletinCompletedToggle.setAttribute(\"aria-expanded\", \"false\");\n    bulletinCompletedToggle.style.cssText =\n      \"display:block;width:100%;margin:18px 0 8px;padding:10px;font-size:14px;\";\n    const bulletinCompletedList = document.createElement(\"div\");\n    bulletinCompletedList.hidden = true;\n    bulletinCompletedList.id = \"gw-bulletin-completed-notes\";\n\n    bulletinBoard.append(\n      bulletinTop, bulletinMessage, bulletinEditor,\n      bulletinOpenList, bulletinCompletedToggle, bulletinCompletedList\n    );\n    logout.insertAdjacentElement(\"afterend\", bulletinEntry);\n    bulletinEntry.insertAdjacentElement(\"afterend\", bulletinBoard);\n\n    let bulletinRole = null;\n    let bulletinUserId = null;\n    let bulletinEditingId = null;\n    let bulletinBusy = false;\n    let bulletinGeneration = 0;\n    let bulletinOpenNotes = [];\n    let bulletinCompletedNotes = [];\n    let bulletinPortalState = null;\n\n    let bulletinReads = [], bulletinNames = new Map();\n    function bulletinCanWrite(){return ['owner','office'].includes(bulletinRole);}\n    function formatBulletinDate(v){return v ? new Date(v).toLocaleString() : '';}\n    function bulletinUnreadCount(){return bulletinOpenNotes.filter(n=>!bulletinReads.some(r=>r.bulletin_id===n.id&&r.employee_id===bulletinUserId)).length;}\n    function updateBulletinEntry(){\n      const count=bulletinUnreadCount(); bulletinEntry.textContent='Bulletin Board';\n      if(count){const dot=document.createElement('span');dot.textContent=' \u25cf '+count;dot.style.cssText='color:#dc2626;-webkit-text-fill-color:#dc2626';bulletinEntry.append(dot);}\n    }\n    const bulletinPin=document.createElement('input');bulletinPin.type='checkbox';\n    const pinLabel=bulletinFieldLabel('Pin announcement ');pinLabel.append(bulletinPin);bulletinEditor.insertBefore(pinLabel,bulletinSave);\n    function closeBulletinEditor(){bulletinEditingId=null;bulletinEditor.hidden=true;bulletinNoteTitle.value='';bulletinText.value='';bulletinPin.checked=false;bulletinEditorMessage.textContent='';}\n    function openBulletinEditor(n){if(!bulletinCanWrite()||bulletinBusy)return;bulletinEditingId=n?.id||null;bulletinNoteTitle.value=n?.title||'';bulletinText.value=n?.body||'';bulletinPin.checked=!!n?.pinned;bulletinSave.textContent=n?'Save Changes':'Post Announcement';bulletinEditor.hidden=false;}\n    function bulletinAction(parent,label,fn){const b=document.createElement('button');b.type='button';b.textContent=label;b.style.cssText='margin:5px 5px 5px 0;padding:8px;';b.onclick=async()=>{if(bulletinBusy)return;bulletinBusy=true;try{await fn();}catch(e){bulletinMessage.textContent=e.message||String(e);}finally{bulletinBusy=false;}};parent.append(b);return b;}\n    function bulletinLine(parent,tag,value){const e=document.createElement(tag);e.textContent=value;parent.append(e);return e;}\n    function renderBulletinNotes(container,notes,closed){container.replaceChildren();if(!notes.length)bulletinLine(container,'p','No announcements.');for(const n of notes){\n      const card=document.createElement('article');card.style.cssText='border:1px solid #cbd5e1;border-radius:9px;padding:14px;margin:10px 0;overflow-wrap:anywhere;';container.append(card);\n      const reads=bulletinReads.filter(r=>r.bulletin_id===n.id), mine=reads.find(r=>r.employee_id===bulletinUserId);\n      bulletinLine(card,'h3',(n.pinned?'\ud83d\udccc ':'')+n.title);\n      bulletinLine(card,'small',(bulletinNames.get(n.created_by)||n.created_by)+' \u00b7 '+formatBulletinDate(n.created_at));\n      bulletinLine(card,'p',n.body).style.whiteSpace='pre-wrap';\n      if(mine)bulletinLine(card,'p','\u2713 Acknowledged '+formatBulletinDate(mine.read_at));\n      else if(!closed)bulletinAction(card,'Confirm Read',async()=>{const {error}=await client.from('gw_bulletin_reads').insert({bulletin_id:n.id});if(error&&error.code!=='23505')throw error;await loadBulletinNotes();});\n      if(closed)bulletinLine(card,'p','Closed '+formatBulletinDate(n.closed_at));\n      if(bulletinCanWrite()){\n        if(!closed){const edit=bulletinAction(card,'Edit',async()=>{bulletinBusy=false;openBulletinEditor(n);});\n        bulletinAction(card,n.pinned?'Unpin':'Pin',async()=>{const {error}=await client.from('gw_bulletins').update({pinned:!n.pinned}).eq('id',n.id);if(error)throw error;await loadBulletinNotes();});\n        bulletinAction(card,'Close Announcement',async()=>{if(!confirm('Close this announcement and keep it in history?'))return;const {error}=await client.from('gw_bulletins').update({status:'Closed'}).eq('id',n.id);if(error)throw error;await loadBulletinNotes();});}\n        const details=document.createElement('details');card.append(details);bulletinLine(details,'summary','Read confirmations ('+reads.length+')');for(const r of reads)bulletinLine(details,'p',(bulletinNames.get(r.employee_id)||\"Name unavailable\")+' \u00b7 '+formatBulletinDate(r.read_at));\n      }\n    }}\n    async function loadBulletinNotes(){if(!client||logout.hidden)return false;const gen=bulletinGeneration;try{\n      const [notes,reads,profiles]=await Promise.all([client.from('gw_bulletins').select('*').order('pinned',{ascending:false}).order('created_at',{ascending:false}),client.from('gw_bulletin_reads').select('*'),client.from('employee_profiles').select('user_id,display_name')]);\n      if(gen!==bulletinGeneration||logout.hidden)return false;if(notes.error)throw notes.error;if(reads.error)throw reads.error;\n      bulletinReads=reads.data||[];bulletinNames=new Map((profiles.data||[]).map(p=>[p.user_id,String(p.display_name||'').trim()]));\n      if(bulletinCanWrite()){\n        const names=await client.rpc('gw_bulletin_reader_names');\n        if(gen!==bulletinGeneration||logout.hidden)return false;\n        if(!names.error){for(const p of names.data||[])if(p.display_name)bulletinNames.set(p.user_id,p.display_name.trim());}\n        else console.warn('Bulletin reader names unavailable',names.error);\n      }bulletinOpenNotes=(notes.data||[]).filter(n=>n.status==='Open');bulletinCompletedNotes=(notes.data||[]).filter(n=>n.status==='Closed');\n      renderBulletinNotes(bulletinOpenList,bulletinOpenNotes,false);renderBulletinNotes(bulletinCompletedList,bulletinCompletedNotes,true);bulletinCompletedToggle.textContent='Closed Announcements ('+bulletinCompletedNotes.length+')';updateBulletinEntry();bulletinMessage.textContent='';return true;\n    }catch(e){if(gen===bulletinGeneration)bulletinMessage.textContent='Unable to load announcements: '+e.message;return false;}}\n    function openBulletinView() {\n      if (bulletinEntry.hidden || logout.hidden) return;\n      bulletinPortalState = {\n        jobSearchHidden: jobSearch.hidden,\n        dashboardHidden: dashboard.hidden,\n        monthlyHidden: monthlyJobPanel.hidden,\n        employeeToggleHidden: employeeDirectoryToggle.hidden,\n        employeePanelHidden: employeeDirectoryPanel.hidden\n      };\n      jobSearch.hidden = true;\n      monthlyJobPanel.hidden = true;\n      dashboard.hidden = true;\n      employeeDirectoryToggle.hidden = true;\n      employeeDirectoryPanel.hidden = true;\n      bulletinEntry.hidden = true;\n      bulletinBoard.hidden = false;\n      closeBulletinEditor();\n      renderBulletinNotes(bulletinOpenList, bulletinOpenNotes, false);\n      void loadBulletinNotes();\n      bulletinHeading.scrollIntoView({ behavior: \"smooth\", block: \"start\" });\n    }\n    function closeBulletinView() {\n      if (bulletinBoard.hidden) return;\n      closeBulletinEditor();\n      bulletinBoard.hidden = true;\n      bulletinEntry.hidden = false;\n      if (bulletinPortalState) {\n        jobSearch.hidden = bulletinPortalState.jobSearchHidden;\n        monthlyJobPanel.hidden = bulletinPortalState.monthlyHidden;\n        if (!monthlyJobPanel.hidden) void loadMonthlyJobIds();\n        dashboard.hidden = bulletinPortalState.dashboardHidden;\n        employeeDirectoryToggle.hidden = bulletinPortalState.employeeToggleHidden;\n        employeeDirectoryPanel.hidden = bulletinPortalState.employeePanelHidden;\n      } else {\n        jobSearch.hidden = false;\n        monthlyJobPanel.hidden = false;\n        void loadMonthlyJobIds();\n        dashboard.hidden = true;\n      }\n      bulletinPortalState = null;\n      updateBulletinEntry();\n      bulletinEntry.scrollIntoView({ behavior: \"smooth\", block: \"center\" });\n    }\n    async function loadBulletinBoard() {\n      const generation = ++bulletinGeneration;\n      \/\/ showSignedIn() has already verified that this is an active employee.\n      \/\/ The Bulletin Board entry must therefore stay visible even if the\n      \/\/ optional profile\/role lookup or note loading has a problem.\n      bulletinEntry.hidden = false;\n      bulletinBoard.hidden = true;\n      bulletinEntry.textContent = \"Bulletin Board\";\n      closeBulletinEditor();\n      bulletinMessage.textContent = \"\";\n      bulletinOpenList.replaceChildren();\n      bulletinCompletedList.replaceChildren();\n      bulletinCompletedList.hidden = true;\n      bulletinCompletedToggle.setAttribute(\"aria-expanded\", \"false\");\n      bulletinRole = null;\n      bulletinUserId = null;\n      bulletinAdd.hidden = true;\n      if (!client || logout.hidden) {\n        bulletinEntry.hidden = true;\n        return;\n      }\n      try {\n        const { data: auth, error: authError } = await client.auth.getUser();\n        if (authError || !auth.user) throw new Error(\"Unable to verify signed-in employee.\");\n        if (generation !== bulletinGeneration || logout.hidden) return;\n\n        bulletinUserId = auth.user.id;\n\n        \/\/ Role controls Add\/Edit\/Delete only. It must never hide the board entry.\n        const { data: profile, error: profileError } = await client\n          .from(\"employee_profiles\").select(\"role\").eq(\"user_id\", auth.user.id).maybeSingle();\n        if (!profileError && profile && profile.role) {\n          bulletinRole = profile.role;\n          bulletinAdd.hidden = !bulletinCanWrite();\n        }\n\n        bulletinEntry.hidden = false;\n        updateBulletinEntry();\n        bulletinMessage.textContent = \"Loading notes...\";\n        const loaded = await loadBulletinNotes();\n        if (loaded && generation === bulletinGeneration && !logout.hidden) {\n          bulletinMessage.textContent = \"\";\n        } else if (generation === bulletinGeneration && !logout.hidden && !bulletinMessage.textContent) {\n          bulletinMessage.textContent = \"Notes are temporarily unavailable.\";\n        }\n      } catch (error) {\n        if (generation === bulletinGeneration && !logout.hidden) {\n          \/\/ Fail open for navigation\/read UI, but keep all write controls hidden.\n          bulletinRole = null;\n          bulletinAdd.hidden = true;\n          bulletinEntry.hidden = false;\n          bulletinEntry.textContent = \"Bulletin Board\";\n          bulletinMessage.textContent = \"Bulletin Board is temporarily unavailable. Please try again.\";\n        }\n      }\n    }\n\n    function resetBulletinBoard() {\n      bulletinGeneration++;\n      bulletinRole = null;\n      bulletinUserId = null;\n      bulletinBusy = false;\n      bulletinPortalState = null;\n      bulletinOpenNotes = [];\n      bulletinCompletedNotes = [];\n      bulletinReads = []; bulletinNames.clear();\n      bulletinEntry.hidden = true;\n      bulletinBoard.hidden = true;\n      bulletinAdd.hidden = true;\n      bulletinOpenList.replaceChildren();\n      bulletinCompletedList.replaceChildren();\n      bulletinCompletedList.hidden = true;\n      bulletinCompletedToggle.setAttribute(\"aria-expanded\", \"false\");\n      bulletinCompletedToggle.textContent = \"Closed Announcements\";\n      bulletinMessage.textContent = \"\";\n      closeBulletinEditor();\n    }\n\n    bulletinEntry.addEventListener(\"click\", openBulletinView);\n    bulletinBack.addEventListener(\"click\", closeBulletinView);\n    bulletinAdd.addEventListener(\"click\", function () { openBulletinEditor(null); });\n    bulletinCancel.addEventListener(\"click\", function () {\n      if (!bulletinBusy) closeBulletinEditor();\n    });\n    bulletinCompletedToggle.addEventListener(\"click\", function () {\n      if (bulletinBoard.hidden) return;\n      bulletinCompletedList.hidden = !bulletinCompletedList.hidden;\n      bulletinCompletedToggle.setAttribute(\"aria-expanded\", String(!bulletinCompletedList.hidden));\n    });\n    bulletinEditor.addEventListener('submit',async e=>{e.preventDefault();if(!bulletinCanWrite()||bulletinBusy)return;const title=bulletinNoteTitle.value.trim(),body=bulletinText.value.trim();if(!title||!body)return;bulletinBusy=true;bulletinSave.disabled=true;try{const values={title,body,pinned:bulletinPin.checked};const result=bulletinEditingId?await client.from('gw_bulletins').update(values).eq('id',bulletinEditingId):await client.from('gw_bulletins').insert(values);if(result.error)throw result.error;closeBulletinEditor();await loadBulletinNotes();}catch(e){bulletinEditorMessage.textContent=e.message;}finally{bulletinBusy=false;bulletinSave.disabled=false;}});\n\n    let employeeDirectoryRequestId = 0;\n    let employeeStatusBusy = false;\n    function resetEmployeeDirectory() {\n      employeeDirectoryRequestId++;\n      employeeDirectoryToggle.hidden = true;\n      employeeDirectoryToggle.setAttribute(\"aria-expanded\", \"false\");\n      employeeDirectoryPanel.hidden = true;\n      employeeDirectoryBody.replaceChildren();\n      employeeDirectoryMessage.textContent = \"\";\n      resetInviteForm();\n    }\n    async function checkEmployeeDirectoryAccess() {\n      const requestId = ++employeeDirectoryRequestId;\n      employeeDirectoryToggle.hidden = true;\n      employeeDirectoryPanel.hidden = true;\n      try {\n        const { data: auth, error: authError } = await client.auth.getUser();\n        if (authError || !auth.user) return;\n        const { data: profile, error: profileError } = await client\n          .from(\"employee_profiles\")\n          .select(\"role\")\n          .eq(\"user_id\", auth.user.id)\n          .maybeSingle();\n        if (profileError || requestId !== employeeDirectoryRequestId ||\n            logout.hidden || !profile || profile.role !== \"owner\") return;\n        employeeDirectoryToggle.hidden = false;\n      } catch (_error) {\n        \/\/ Directory access is optional; ordinary login remains available.\n      }\n    }\n    \/\/ Names are edited through an owner-checked database RPC. UI controls alone\n    \/\/ are not an authorization boundary; owner profiles are deliberately read-only.\n    async function loadEmployeeDirectory() {\n      const requestId = ++employeeDirectoryRequestId;\n      employeeDirectoryBody.textContent = \"Loading employees...\";\n      employeeDirectoryMessage.textContent = \"\";\n      try {\n        const { data: employees, error } =\n          await client.rpc(\"gw_owner_list_employees\");\n        if (error) throw error;\n        if (!Array.isArray(employees)) throw new Error(\"Employee list unavailable.\");\n        \/\/ Separate owner-only RPC avoids changing the established roster RPC return type.\n        const { data: statuses, error: statusError } =\n          await client.rpc(\"gw_owner_list_employee_statuses\");\n        if (statusError) throw statusError;\n        if (!Array.isArray(statuses)) throw new Error(\"Employee statuses unavailable.\");\n        const statusByUserId = new Map();\n        for (const statusRow of statuses) {\n          if (!statusRow || !statusRow.user_id ||\n              typeof statusRow.is_active !== \"boolean\" ||\n              statusByUserId.has(statusRow.user_id)) {\n            throw new Error(\"Employee status information is invalid.\");\n          }\n          statusByUserId.set(statusRow.user_id, statusRow.is_active);\n        }\n        for (const employee of employees) {\n          if (!statusByUserId.has(employee.user_id))\n            throw new Error(\"Employee status could not be verified.\");\n        }\n        if (requestId !== employeeDirectoryRequestId ||\n            employeeDirectoryPanel.hidden || employeeDirectoryToggle.hidden ||\n            logout.hidden) return false;\n        employeeDirectoryBody.replaceChildren();\n        if (!employees || employees.length === 0) {\n          employeeDirectoryBody.textContent = \"No employee profiles found.\";\n          return true;\n        }\n        \/\/ Email lookup is optional; failure must not block the employee roster.\n        const emailById = new Map();\n        try {\n          for (let offset = 0; offset < employees.length; offset += 20) {\n            const userIds = employees.slice(offset, offset + 20).map(e => e.user_id);\n            const result = await client.functions.invoke(\"gw-manage-employee\", {\n              body: { action: \"list_emails\", userIds }\n            });\n            if (result.error || !Array.isArray(result.data?.emails)) break;\n            for (const entry of result.data.emails) {\n              if (userIds.includes(entry.userId) && typeof entry.email === \"string\") emailById.set(entry.userId, entry.email);\n            }\n          }\n        } catch (_error) { \/* Keep the roster usable when email lookup fails. *\/ }\n        if (requestId !== employeeDirectoryRequestId || employeeDirectoryPanel.hidden || employeeDirectoryToggle.hidden || logout.hidden) return false;\n        const sortedEmployees = [...employees].sort(function (a, b) {\n          const aOwner = a.role === \"owner\" ? 0 : 1;\n          const bOwner = b.role === \"owner\" ? 0 : 1;\n          if (aOwner !== bOwner) return aOwner - bOwner;\n          return String(a.display_name || \"\").localeCompare(String(b.display_name || \"\"));\n        });\n        for (const employee of sortedEmployees) {\n          const row = document.createElement(\"div\");\n          row.style.cssText =\n            \"border-bottom:1px solid #e3e8ed;overflow-wrap:anywhere;\";\n\n          const isOwnerAccount = employee.role === \"owner\";\n          const isEditableEmployee =\n            [\"installer\", \"fabricator\", \"office\", \"project_manager\"].includes(employee.role);\n          const isActive = statusByUserId.get(employee.user_id);\n\n          \/\/ Keep the main Employee Accounts screen simple: one small user icon + name.\n          \/\/ All management controls are inside the selected employee row.\n          const accountButton = document.createElement(\"button\");\n          accountButton.type = \"button\";\n          accountButton.setAttribute(\"aria-expanded\", \"false\");\n          accountButton.style.cssText =\n            \"display:flex;align-items:center;gap:9px;width:100%;padding:12px 4px;\" +\n            \"border:0;background:transparent;text-align:left;cursor:pointer;font:inherit;\";\n          const accountIcon = document.createElement(\"span\");\n          accountIcon.textContent = \"\ud83d\udc64\";\n          accountIcon.setAttribute(\"aria-hidden\", \"true\");\n          accountIcon.style.cssText = \"font-size:18px;line-height:1;flex:0 0 auto;\";\n          const accountName = document.createElement(\"strong\");\n          accountName.textContent = employee.display_name || \"(Name not set)\";\n          accountName.style.cssText = \"font-size:16px;line-height:1.3;color:#0b4f8a;font-weight:600;\";\n          const accountIdentity = document.createElement(\"span\");\n          accountIdentity.style.cssText = \"display:flex;flex-direction:column;min-width:0;text-align:left;\";\n          const accountEmail = document.createElement(\"span\");\n          accountEmail.style.cssText = \"font-size:13px;color:#475569;overflow-wrap:anywhere;\";\n          accountEmail.textContent = emailById.get(employee.user_id) || \"Login email unavailable\";\n          accountIdentity.append(accountName, accountEmail);\n          accountButton.append(accountIcon, accountIdentity);\n\n          const accountPanel = document.createElement(\"div\");\n          accountPanel.hidden = true;\n          accountPanel.style.cssText =\n            \"padding:2px 8px 14px 35px;box-sizing:border-box;\";\n\n          const accountSummary = document.createElement(\"p\");\n          if (isOwnerAccount) {\n            accountSummary.textContent = \"Owner account \u2014 read only.\";\n          } else {\n            accountSummary.textContent =\n              \"Role: \" + employee.role + \" \u00b7 Portal: \" +\n              (isActive ? \"Active\" : \"Disabled\");\n          }\n          accountSummary.style.cssText = \"margin:4px 0 10px;font-size:14px;\";\n          accountPanel.appendChild(accountSummary);\n\n          accountButton.addEventListener(\"click\", function () {\n            if (employeeDirectoryPanel.hidden || logout.hidden) return;\n            accountPanel.hidden = !accountPanel.hidden;\n            accountButton.setAttribute(\"aria-expanded\", String(!accountPanel.hidden));\n          });\n\n          row.append(accountButton, accountPanel);\n\n          if (isEditableEmployee) {\n            const editButton = document.createElement(\"button\");\n            editButton.type = \"button\";\n            editButton.textContent = \"Edit Name\";\n            editButton.style.cssText = \"display:block;width:100%;margin:8px 0;\";\n            const editor = document.createElement(\"div\");\n            editor.hidden = true;\n            const nameLabel = document.createElement(\"label\");\n            nameLabel.textContent = \"Employee display name\";\n            nameLabel.style.display = \"block\";\n            const nameInput = document.createElement(\"input\");\n            nameInput.type = \"text\";\n            nameInput.maxLength = 80;\n            nameInput.autocomplete = \"off\";\n            nameInput.value = employee.display_name || \"\";\n            nameInput.style.cssText = \"width:100%;max-width:380px;margin:6px 0;\";\n            nameLabel.appendChild(nameInput);\n            const saveButton = document.createElement(\"button\");\n            saveButton.type = \"button\";\n            saveButton.textContent = \"Save Name\";\n            const cancelButton = document.createElement(\"button\");\n            cancelButton.type = \"button\";\n            cancelButton.textContent = \"Cancel\";\n            cancelButton.style.marginLeft = \"8px\";\n            const rowMessage = document.createElement(\"p\");\n            rowMessage.setAttribute(\"role\", \"status\");\n            editor.append(nameLabel, saveButton, cancelButton, rowMessage);\n            editButton.addEventListener(\"click\", function () {\n              if (employeeDirectoryPanel.hidden || logout.hidden) return;\n              editor.hidden = !editor.hidden;\n              if (!editor.hidden) nameInput.focus();\n            });\n            cancelButton.addEventListener(\"click\", function () {\n              if (saveButton.disabled) return;\n              nameInput.value = employee.display_name || \"\";\n              rowMessage.textContent = \"\";\n              editor.hidden = true;\n            });\n            saveButton.addEventListener(\"click\", async function () {\n              if (!client || logout.hidden || employeeDirectoryPanel.hidden ||\n                  employeeDirectoryToggle.hidden || requestId !== employeeDirectoryRequestId ||\n                  saveButton.disabled) return;\n              const newName = nameInput.value.trim();\n              if (!newName || newName.length > 80) {\n                rowMessage.textContent = \"Enter a name between 1 and 80 characters.\";\n                return;\n              }\n              if (newName === (employee.display_name || \"\").trim()) {\n                rowMessage.textContent = \"Name is unchanged.\";\n                return;\n              }\n              if (!window.confirm(\"Change \" + (employee.display_name || \"this employee\") +\n                  \"'s display name to \" + newName + \"?\")) return;\n              saveButton.disabled = true;\n              cancelButton.disabled = true;\n              editButton.disabled = true;\n              rowMessage.textContent = \"Saving name...\";\n              try {\n                const { data: savedName, error: saveError } = await client.rpc(\n                  \"gw_owner_update_employee_name\",\n                  { p_user_id: employee.user_id, p_display_name: newName }\n                );\n                if (saveError) throw saveError;\n                if (savedName !== newName) throw new Error(\"Saved name could not be verified.\");\n                if (requestId !== employeeDirectoryRequestId || logout.hidden ||\n                    employeeDirectoryPanel.hidden) return;\n                const refreshed = await loadEmployeeDirectory();\n                if (refreshed && !employeeDirectoryPanel.hidden && !logout.hidden)\n                  employeeDirectoryMessage.textContent = \"Employee name saved: \" + savedName + \".\";\n              } catch (saveError) {\n                if (requestId === employeeDirectoryRequestId &&\n                    !employeeDirectoryPanel.hidden && !logout.hidden)\n                  rowMessage.textContent = \"Save failed: \" + saveError.message;\n              } finally {\n                saveButton.disabled = false;\n                cancelButton.disabled = false;\n                editButton.disabled = false;\n              }\n            });\n            accountPanel.append(editButton, editor);\n\n            const roleButton = document.createElement(\"button\");\n            roleButton.type = \"button\";\n            roleButton.textContent = \"Edit Role\";\n            roleButton.style.cssText = \"display:block;width:100%;margin:8px 0;\";\n            const roleEditor = document.createElement(\"div\");\n            roleEditor.hidden = true;\n            const roleLabel = document.createElement(\"label\");\n            roleLabel.textContent = \"Employee role\";\n            roleLabel.style.display = \"block\";\n            const roleSelect = document.createElement(\"select\");\n            roleSelect.style.cssText = \"width:100%;max-width:380px;margin:6px 0;\";\n            const roleChoices = [\n              [\"installer\", \"Installer\"],\n              [\"fabricator\", \"Fabricator\"],\n              [\"office\", \"Office\"],\n              [\"project_manager\", \"Project Manager\"]\n            ];\n            for (const [value, label] of roleChoices) {\n              const option = document.createElement(\"option\");\n              option.value = value;\n              option.textContent = label;\n              roleSelect.appendChild(option);\n            }\n            roleSelect.value = employee.role;\n            roleLabel.appendChild(roleSelect);\n            const saveRoleButton = document.createElement(\"button\");\n            saveRoleButton.type = \"button\";\n            saveRoleButton.textContent = \"Save Role\";\n            const cancelRoleButton = document.createElement(\"button\");\n            cancelRoleButton.type = \"button\";\n            cancelRoleButton.textContent = \"Cancel\";\n            cancelRoleButton.style.marginLeft = \"8px\";\n            const roleMessage = document.createElement(\"p\");\n            roleMessage.setAttribute(\"role\", \"status\");\n            roleEditor.append(roleLabel, saveRoleButton, cancelRoleButton, roleMessage);\n            roleButton.addEventListener(\"click\", function () {\n              if (employeeDirectoryPanel.hidden || logout.hidden) return;\n              roleEditor.hidden = !roleEditor.hidden;\n              if (!roleEditor.hidden) roleSelect.focus();\n            });\n            cancelRoleButton.addEventListener(\"click\", function () {\n              if (saveRoleButton.disabled) return;\n              roleSelect.value = employee.role;\n              roleMessage.textContent = \"\";\n              roleEditor.hidden = true;\n            });\n            saveRoleButton.addEventListener(\"click\", async function () {\n              if (!client || logout.hidden || employeeDirectoryPanel.hidden ||\n                  employeeDirectoryToggle.hidden || requestId !== employeeDirectoryRequestId ||\n                  saveRoleButton.disabled) return;\n              const newRole = roleSelect.value;\n              if (![\"installer\", \"fabricator\", \"office\", \"project_manager\"].includes(newRole)) {\n                roleMessage.textContent = \"Select a valid employee role.\";\n                return;\n              }\n              if (newRole === employee.role) {\n                roleMessage.textContent = \"Role is unchanged.\";\n                return;\n              }\n              const employeeName = employee.display_name || \"this employee\";\n              if (!window.confirm(\"Change \" + employeeName + \" from \" + employee.role +\n                  \" to \" + newRole + \"? This changes their access to Portal features. \" +\n                  \"Installers with assigned jobs cannot change to another role until assignments are removed.\")) return;\n              saveRoleButton.disabled = true;\n              cancelRoleButton.disabled = true;\n              roleButton.disabled = true;\n              roleSelect.disabled = true;\n              roleMessage.textContent = \"Saving role...\";\n              try {\n                const { data: savedRole, error: saveError } = await client.rpc(\n                  \"gw_owner_update_employee_role\",\n                  { p_user_id: employee.user_id, p_new_role: newRole }\n                );\n                if (saveError) throw saveError;\n                if (savedRole !== newRole) throw new Error(\"Saved role could not be verified.\");\n                if (requestId !== employeeDirectoryRequestId || logout.hidden ||\n                    employeeDirectoryPanel.hidden) return;\n                const refreshed = await loadEmployeeDirectory();\n                if (refreshed && !employeeDirectoryPanel.hidden && !logout.hidden) {\n                  employeeDirectoryMessage.textContent =\n                    \"Employee role saved: \" + employeeName + \" \u2014 \" + newRole + \".\";\n                }\n              } catch (saveError) {\n                if (requestId === employeeDirectoryRequestId &&\n                    !employeeDirectoryPanel.hidden && !logout.hidden) {\n                  roleMessage.textContent = \"Role change failed: \" + saveError.message;\n                }\n              } finally {\n                saveRoleButton.disabled = false;\n                cancelRoleButton.disabled = false;\n                roleButton.disabled = false;\n                roleSelect.disabled = false;\n              }\n            });\n            accountPanel.append(roleButton, roleEditor);\n            \/\/ Owner-only password reset. The server verifies authorization again.\n            if (isActive) {\n              const resetButton = document.createElement(\"button\");\n              resetButton.type = \"button\";\n              resetButton.textContent = \"Reset Password\";\n              const resetForm = document.createElement(\"form\");\n              resetForm.hidden = true;\n              resetForm.autocomplete = \"off\";\n              function makeResetField(labelText) {\n                const label = document.createElement(\"label\");\n                label.textContent = labelText;\n                const input = document.createElement(\"input\");\n                input.type = \"password\";\n                input.required = true;\n                input.minLength = 8;\n                input.maxLength = 72;\n                input.autocomplete = \"new-password\";\n                label.append(input);\n                resetForm.append(label);\n                return input;\n              }\n              const resetPassword = makeResetField(\"New Password (8+ characters)\");\n              const resetConfirm = makeResetField(\"Confirm New Password\");\n              const showPasswordLabel = document.createElement(\"label\");\n              const showPasswordCheck = document.createElement(\"input\");\n              showPasswordCheck.type = \"checkbox\";\n              showPasswordLabel.append(showPasswordCheck, document.createTextNode(\"Show Password\"));\n              resetForm.append(showPasswordLabel);\n              showPasswordCheck.addEventListener(\"change\", function () {\n                const fieldType = showPasswordCheck.checked ? \"text\" : \"password\";\n                resetPassword.type = fieldType;\n                resetConfirm.type = fieldType;\n              });\n              const resetSave = document.createElement(\"button\");\n              resetSave.type = \"submit\";\n              resetSave.textContent = \"Save Password\";\n              const resetCancel = document.createElement(\"button\");\n              resetCancel.type = \"button\";\n              resetCancel.textContent = \"Cancel\";\n              const resetMessage = document.createElement(\"p\");\n              resetMessage.setAttribute(\"role\", \"status\");\n              resetForm.append(resetSave, resetCancel, resetMessage);\n              function clearResetFields() {\n                resetPassword.value = \"\";\n                resetConfirm.value = \"\";\n                showPasswordCheck.checked = false;\n                resetPassword.type = \"password\";\n                resetConfirm.type = \"password\";\n              }\n              function resetAvailable() {\n                if (!client || logout.hidden || employeeDirectoryPanel.hidden || employeeDirectoryToggle.hidden || accountPanel.hidden) return false;\n                return requestId === employeeDirectoryRequestId;\n              }\n              resetButton.addEventListener(\"click\", function () {\n                if (!resetAvailable() || resetSave.disabled) return;\n                clearResetFields();\n                resetMessage.textContent = \"\";\n                resetForm.hidden = !resetForm.hidden;\n                if (!resetForm.hidden) resetPassword.focus();\n              });\n              resetCancel.addEventListener(\"click\", function () {\n                clearResetFields();\n                resetForm.hidden = true;\n                resetMessage.textContent = \"\";\n              });\n              accountButton.addEventListener(\"click\", function () {\n                if (accountPanel.hidden) {\n                  clearResetFields();\n                  resetForm.hidden = true;\n                }\n              });\n              resetForm.addEventListener(\"submit\", async function (event) {\n                event.preventDefault();\n                if (!resetAvailable() || resetSave.disabled) return;\n                const value = resetPassword.value;\n                const bytes = new TextEncoder().encode(value).length;\n                if (Math.max(8, value.length) !== value.length || Math.min(72, bytes) !== bytes || !value.trim() || value !== resetConfirm.value) {\n                  resetMessage.textContent = \"Passwords must match, contain at least 8 characters, and use at most 72 UTF-8 bytes.\";\n                  return;\n                }\n                if (!window.confirm(\"Reset the password for \" + (employee.display_name || \"this employee\") + \" (\" + (emailById.get(employee.user_id) || \"email unavailable\") + \")?\")) return;\n                resetSave.disabled = resetCancel.disabled = resetButton.disabled = true;\n                resetMessage.textContent = \"Saving password...\";\n                try {\n                  const result = await client.functions.invoke(\"gw-manage-employee\", {\n                    body: { action: \"reset\", userId: employee.user_id, password: value }\n                  });\n                  if (result.error || !result.data || result.data.passwordReset !== true) throw new Error(\"Reset not confirmed\");\n                  if (resetAvailable()) {\n                    resetForm.hidden = true;\n                    employeeDirectoryMessage.textContent = \"Password reset for \" + (employee.display_name || \"employee\") + \".\";\n                  }\n                } catch (_error) {\n                  if (resetAvailable()) resetMessage.textContent = \"Password reset not confirmed. Check Supabase before retrying.\";\n                } finally {\n                  clearResetFields();\n                  resetSave.disabled = resetCancel.disabled = resetButton.disabled = false;\n                }\n              });\n              accountPanel.append(resetButton, resetForm);\n            }\n\n            const accessButton = document.createElement(\"button\");\n            accessButton.type = \"button\";\n            accessButton.textContent = isActive\n              ? \"Disable Portal Access\" : \"Restore Portal Access\";\n            accessButton.style.cssText = \"display:block;width:100%;margin:8px 0;\";\n            const accessMessage = document.createElement(\"p\");\n            accessMessage.setAttribute(\"role\", \"status\");\n            accessButton.addEventListener(\"click\", async function () {\n              if (!client || logout.hidden || employeeDirectoryPanel.hidden ||\n                  employeeDirectoryToggle.hidden ||\n                  requestId !== employeeDirectoryRequestId ||\n                  employeeStatusBusy || accessButton.disabled) return;\n              const employeeName = employee.display_name || \"this employee\";\n              const nextStatus = !isActive;\n              const question = nextStatus\n                ? \"Restore Portal access for \" + employeeName +\n                  \"? Existing job assignments will become accessible again.\"\n                : \"Disable Portal access for \" + employeeName +\n                  \"? Their job assignments and records will remain saved.\";\n              if (!window.confirm(question)) return;\n              employeeStatusBusy = true;\n              accessButton.disabled = true;\n              accessMessage.textContent = nextStatus\n                ? \"Restoring Portal access...\" : \"Disabling Portal access...\";\n              try {\n                const { data: savedStatus, error: saveError } = await client.rpc(\n                  \"gw_owner_set_employee_active\",\n                  { p_user_id: employee.user_id, p_is_active: nextStatus }\n                );\n                if (saveError) throw saveError;\n                if (savedStatus !== nextStatus)\n                  throw new Error(\"Account status could not be verified.\");\n                if (requestId !== employeeDirectoryRequestId ||\n                    employeeDirectoryPanel.hidden || logout.hidden) return;\n                const refreshed = await loadEmployeeDirectory();\n                if (refreshed && !employeeDirectoryPanel.hidden && !logout.hidden) {\n                  employeeDirectoryMessage.textContent = employeeName +\n                    (nextStatus ? \" \u2014 Portal access restored.\" : \" \u2014 Portal access disabled.\");\n                }\n              } catch (saveError) {\n                if (requestId === employeeDirectoryRequestId &&\n                    !employeeDirectoryPanel.hidden && !logout.hidden)\n                  accessMessage.textContent = \"Status change failed: \" + saveError.message;\n              } finally {\n                employeeStatusBusy = false;\n                accessButton.disabled = false;\n              }\n            });\n            accountPanel.append(accessButton, accessMessage);\n          }\n\n          employeeDirectoryBody.appendChild(row);\n        }\n        employeeDirectoryMessage.textContent =\n          employees.length + \" account(s). Tap a name to open account controls. \" +\n          \"Owner account remains visible and read-only.\";\n        return true;\n      } catch (error) {\n        if (requestId !== employeeDirectoryRequestId ||\n            employeeDirectoryPanel.hidden || logout.hidden) return false;\n        employeeDirectoryBody.textContent = \"Unable to load employee accounts.\";\n        employeeDirectoryMessage.textContent = error.message;\n        return false;\n      }\n    }\n    employeeDirectoryToggle.addEventListener(\"click\", async function () {\n      if (employeeDirectoryToggle.hidden || !client || logout.hidden) return;\n      employeeDirectoryPanel.hidden = !employeeDirectoryPanel.hidden;\n      employeeDirectoryToggle.setAttribute(\n        \"aria-expanded\", String(!employeeDirectoryPanel.hidden)\n      );\n      if (employeeDirectoryPanel.hidden) {\n        employeeDirectoryRequestId++;\n        resetInviteForm();\n        return;\n      }\n      await loadEmployeeDirectory();\n    });\n\n\n    \/\/ ================================================================\n    \/\/ OWNER-ONLY ANNUAL JOB PROBLEM REPORT\n    \/\/ The RPC gw_owner_annual_problem_report also verifies active Owner access\n    \/\/ on the server, so hiding this button is not the security boundary.\n    \/\/ ================================================================\n    let annualProblemAllowed = false;\n    let annualProblemRequestId = 0;\n\n    const annualProblemToggle = document.createElement(\"button\");\n    annualProblemToggle.type = \"button\";\n    annualProblemToggle.id = \"gw-annual-problem-toggle\";\n    annualProblemToggle.textContent = \"Annual Issues Report (Owner \/ Office)\";\n    annualProblemToggle.hidden = true;\n    annualProblemToggle.setAttribute(\"aria-expanded\", \"false\");\n    annualProblemToggle.style.cssText =\n      \"width:100%;margin:12px 0;padding:12px;font-size:17px;font-weight:700;\";\n\n    const annualProblemPanel = document.createElement(\"section\");\n    annualProblemPanel.id = \"gw-annual-problem-panel\";\n    annualProblemPanel.hidden = true;\n    annualProblemPanel.style.cssText =\n      \"box-sizing:border-box;width:100%;margin:8px 0 18px;padding:16px;\" +\n      \"border:1px solid #cbd5e1;border-radius:10px;background:#fff;overflow-wrap:anywhere;\";\n\n    const annualProblemHeading = document.createElement(\"h3\");\n    annualProblemHeading.textContent = \"Annual Job Problem Report\";\n    annualProblemHeading.style.cssText = \"margin:0 0 12px;font-size:24px;\";\n\n    const annualProblemControls = document.createElement(\"div\");\n    annualProblemControls.style.cssText =\n      \"display:flex;align-items:end;gap:10px;flex-wrap:wrap;margin:8px 0 14px;\";\n\n    const annualProblemYearLabel = document.createElement(\"label\");\n    annualProblemYearLabel.textContent = \"Year\";\n    annualProblemYearLabel.style.cssText = \"display:block;font-weight:600;\";\n    const annualProblemYear = document.createElement(\"input\");\n    annualProblemYear.type = \"number\";\n    annualProblemYear.min = \"2020\";\n    annualProblemYear.max = \"2100\";\n    annualProblemYear.step = \"1\";\n    annualProblemYear.value = String(new Date().getFullYear());\n    annualProblemYear.style.cssText =\n      \"display:block;width:120px;box-sizing:border-box;font-size:17px;padding:8px;margin-top:5px;\";\n    annualProblemYearLabel.appendChild(annualProblemYear);\n\n    const annualProblemLoad = document.createElement(\"button\");\n    annualProblemLoad.type = \"button\";\n    annualProblemLoad.textContent = \"Load Report\";\n    annualProblemLoad.style.cssText = \"padding:9px 14px;font-size:16px;\";\n\n    annualProblemControls.append(annualProblemYearLabel, annualProblemLoad);\n\n    const annualProblemMessage = document.createElement(\"p\");\n    annualProblemMessage.setAttribute(\"role\", \"status\");\n    annualProblemMessage.setAttribute(\"aria-live\", \"polite\");\n    annualProblemMessage.style.cssText = \"margin:8px 0 12px;\";\n\n    const annualProblemSummary = document.createElement(\"div\");\n    annualProblemSummary.id = \"gw-annual-problem-summary\";\n    annualProblemSummary.style.cssText =\n      \"display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));\" +\n      \"gap:10px;margin:10px 0 16px;\";\n\n    const annualProblemBreakdowns = document.createElement(\"div\");\n    annualProblemBreakdowns.style.cssText =\n      \"display:grid;grid-template-columns:repeat(auto-fit,minmax(240px,1fr));\" +\n      \"gap:14px;margin:10px 0 18px;\";\n\n    const annualProblemListHeading = document.createElement(\"h4\");\n    annualProblemListHeading.textContent = \"Report Details\";\n    annualProblemListHeading.style.cssText = \"margin:18px 0 8px;font-size:20px;\";\n\n    const annualProblemList = document.createElement(\"div\");\n    annualProblemList.id = \"gw-annual-problem-list\";\n\n    annualProblemPanel.append(\n      annualProblemHeading,\n      annualProblemControls,\n      annualProblemMessage,\n      annualProblemSummary,\n      annualProblemBreakdowns,\n      annualProblemListHeading,\n      annualProblemList\n    );\n\n\n    form.parentElement.append(annualProblemToggle, annualProblemPanel);\n    \/\/ Revision 9.3 \u2014 confidential issue classification and annual note reports.\n    const gw93Report=document.createElement('section'); annualProblemPanel.append(gw93Report);\n    let gw94Formal=null, gw94Notes=null, gw94Year=null;\n    const gw94PrintFull=gw93Button(annualProblemControls,'Print full annual report \/ PDF',()=>gw94Print(gw94Notes,gw94Formal,'All records'));\n    gw94PrintFull.disabled=true;\n    function gw94ClearPrint(){gw94Formal=gw94Notes=gw94Year=null;gw94PrintFull.disabled=true;}\n    function gw94PrintReady(){gw94PrintFull.disabled=gw94Formal===null||gw94Notes===null;}\n    function gw94Print(notes,formal,scope){\n      if(!annualProblemAllowed||logout.hidden||annualProblemPanel.hidden||gw94Year===null||notes===null||formal===null)return;\n      const win=window.open('','_blank');if(!win){alert('Allow pop-ups to print the report.');return;}win.opener=null;\n      const d=win.document;d.title='GW Kitchen & Bath \u2014 Annual Issues '+gw94Year;\n      const style=d.createElement('style');style.textContent='body{font:12pt Arial,sans-serif;color:#111;margin:24px}h1{font-size:22pt}h2{font-size:16pt;border-bottom:1px solid #aaa;padding-bottom:5px}h3{font-size:13pt;margin-bottom:4px}p{white-space:pre-wrap;overflow-wrap:anywhere;margin:5px 0}article{border-bottom:1px solid #bbb;padding:9px 0;break-inside:avoid} @media print{body{margin:0}button{display:none}}';d.head.append(style);\n      const add=(tag,t,parent=d.body)=>{const e=d.createElement(tag);e.textContent=String(t??'');parent.append(e);return e;};\n      add('h1','GW Kitchen & Bath \u2014 Annual Issues Report');add('p','Confidential \u2022 Owner \/ Office');add('p','Year: '+gw94Year+' | Printed: '+new Date().toLocaleString('en-US',{timeZone:'America\/Chicago'})+' (Texas time)');add('p','Scope: '+scope);\n      if(formal.length||scope==='All records'){\n        add('h2','Formal job problem reports ('+formal.length+')');\n        add('p','Open: '+formal.filter(r=>r.status==='Open').length+' | Resolved: '+formal.filter(r=>r.status==='Resolved').length+' | Rework cost: $'+formal.reduce((a,r)=>a+(Number(r.rework_cost)||0),0).toFixed(2));\n        for(const r of formal){const a=add('article','');add('h3',r.job_id+' \u00b7 '+(r.issue_type||'Other')+' \u00b7 '+r.status,a);add('p',annualProblemDate(r.reported_at)+' \u00b7 '+(r.reported_by_name||''),a);add('p','Workers: '+(r.worker_names||'Not recorded'),a);for(const [k,v] of [['Description',r.description],['Action needed',r.action_needed],['Internal notes',r.notes],['Resolution',r.resolution_notes],['Resolved at',r.resolved_at?annualProblemDate(r.resolved_at):''],['Resolved by',r.resolved_by_name],['Rework cost',r.rework_cost==null?'':'$'+r.rework_cost]])if(v)add('p',k+': '+v,a);}\n      }\n      add('h2','Classified issue notes ('+notes.length+')');add('p','Separate from formal reports; totals may overlap.');\n      for(const n of notes){const a=add('article','');add('h3',n.job_id+' \u00b7 '+n.category+' \u00b7 '+n.note_type,a);add('p',n.author_name+' \u00b7 '+annualProblemDate(n.note_date),a);add('p',n.note_body,a);add('p','Workers: '+((n.workers_json||[]).map(w=>w.name+' \u2014 '+w.responsibility).join('; ')||'None selected'),a);}\n      const b=add('button','Print \/ Save as PDF');b.onclick=()=>win.print();win.focus();win.print();\n    }\n    const gw93Categories=['Measurement','Fabrication','Installation','Material','Customer','Worker','Other'];\n    function gw93El(tag,text,parent){const e=document.createElement(tag);if(text!=null)e.textContent=text;if(parent)parent.append(e);return e;}\n    function gw93Button(parent,label,fn){const b=gw93El('button',label,parent);b.type='button';b.onclick=fn;return b;}\n    function gw93Select(parent,label,choices,value=''){const l=gw93El('label',label,parent),s=gw93El('select',null,l);for(const [v,t] of choices)s.add(new Option(t,String(v)));s.value=String(value);return s;}\n    async function gw93Result(p){const r=await p;if(r.error)throw r.error;return r.data;}\n    function gw93WorkerText(w){return w.worker_name+(w.active?'':' (Inactive)');}\n    async function gw93NoteControl(parent,n,table,current){\n      const open=table==='gw_job_notes',field=open?'open_note_id':'private_note_id';\n      const status=gw93El('small','',parent);let issue=null;\n      const button=gw93Button(parent,'Issue classification',async()=>{button.disabled=true;try{\n        issue=await gw93Result(client.from('gw_note_issues').select('issue_id,category').eq(field,n.id).maybeSingle());\n        let workers=[];if(issue)workers=await gw93Result(client.from('gw_note_issue_workers').select('worker_id,worker_name,responsibility').eq('issue_id',issue.issue_id));\n        if(!current()||!parent.isConnected)return;\n        await gw93Editor(parent,issue,workers,{open_note_id:open?n.id:null,private_note_id:open?null:n.id},()=>current()&&parent.isConnected,()=>{status.textContent='Classification saved.';});\n      }catch(e){if(current())status.textContent=e.message||'Unable to load classification.';}finally{button.disabled=false;}});\n      button.style.cssText='width:auto;min-height:36px;padding:6px 12px;font-size:14px;';\n    }\n    async function gw93Editor(parent,issue,selected,note,current,done,prepareNote=null){\n      const existing=parent.querySelector('.gw93-editor');if(existing){existing.remove();return;}\n      const roster=await gw93Result(client.rpc('gw_issue_worker_list'));if(!current())return;\n      const panel=gw93El('div',null,parent);panel.className='gw93-editor';panel.style.cssText='padding:12px;border:1px solid #cbd5e1;border-radius:8px;margin:8px 0;';\n      const category=gw93Select(panel,'Issue Category',[['','Select category'],...gw93Categories.map(v=>[v,v])],issue?.category||'');\n      const lines=gw93El('div',null,panel), msg=gw93El('p','',panel);msg.setAttribute('role','status');\n      const rows=[];let busy=false;\n      function add(w={}){const row=gw93El('div',null,lines);row.style.cssText='border-top:1px solid #ddd;padding:8px 0';const select=gw93Select(row,'Worker (optional)',[['','Select worker'],...(roster||[]).map(x=>[x.worker_id,gw93WorkerText(x)])],w.worker_id||'');const responsibility=gw93Select(row,'Responsibility',[['Involved','Involved'],['Confirmed Responsible','Confirmed Responsible']],w.responsibility||'Involved');const entry={row,select,responsibility};rows.push(entry);gw93Button(row,'Remove worker',()=>{if(busy)return;rows.splice(rows.indexOf(entry),1);row.remove();});}\n      (selected.length?selected:[{}]).forEach(add);\n      gw93Button(panel,'+ Add worker',()=>{if(!busy)add();});\n      let reason;if(issue){gw93El('label','Correction reason',panel);reason=gw93El('textarea',null,panel);reason.rows=2;reason.maxLength=10000;}\n      const save=gw93Button(panel,issue?'Save correction':'Save classification',async()=>{if(busy||!current())return;const workers=rows.filter(r=>r.select.value).map(r=>({worker_id:r.select.value,responsibility:r.responsibility.value}));if(!category.value||new Set(workers.map(w=>w.worker_id)).size!==workers.length||issue&&!reason.value.trim()){msg.textContent='Select a category, avoid duplicate workers, and provide a correction reason when required.';return;}busy=true;save.disabled=true;try{if(prepareNote)await prepareNote(note);if(!current())return;const args=issue?{p_issue_id:issue.issue_id,p_category:category.value,p_workers:workers,p_reason:reason.value.trim()}:{p_open_note_id:note.open_note_id,p_private_note_id:note.private_note_id,p_category:category.value,p_workers:workers};await gw93Result(client.rpc(issue?'gw_correct_note_issue':'gw_classify_note_issue',args));if(current()){panel.remove();done();}}catch(e){if(current())msg.textContent=e.message||'Unable to save classification.';}finally{busy=false;save.disabled=false;}});\n      gw93Button(panel,'Cancel',()=>{if(!busy)panel.remove();});\n      if(issue)gw93Button(panel,'Correction history',async()=>{try{const data=await gw93Result(client.from('gw_note_issue_history').select('*').eq('issue_id',issue.issue_id).order('history_id',{ascending:false}));if(!current()||!panel.isConnected)return;let h=panel.querySelector('.gw93-history');if(h){h.remove();return;}h=gw93El('div',null,panel);h.className='gw93-history';for(const r of data){gw93El('p',r.changed_by_name+' \u00b7 '+annualProblemDate(r.changed_at)+' \u00b7 '+r.change_reason,h);gw93El('p',r.previous_category+' \u2192 '+r.new_category,h);const fmt=a=>(a||[]).map(w=>w.name+' ('+w.responsibility+')').join(', ')||'None';gw93El('p',fmt(r.previous_workers)+' \u2192 '+fmt(r.new_workers),h);}if(!data.length)gw93El('p','No corrections yet.',h);}catch(e){msg.textContent=e.message;}});\n    }\n    async function gw93Annual(year,requestId){\n      const current=()=>requestId===annualProblemRequestId&&annualProblemAllowed&&!logout.hidden;\n      gw94Notes=null;gw94PrintReady();gw93Report.replaceChildren();gw93El('h3','Classified Issue Notes',gw93Report);gw93El('p','Separate from formal job problem reports; do not add the two totals as unique incidents.',gw93Report);\n      const status=gw93El('p','Loading issue notes\u2026',gw93Report);try{\n        const data=await gw93Result(client.rpc('gw_annual_note_issues',{p_year:year}));if(!current())return;gw94Notes=data;gw94PrintReady();\n        const workers=new Map();for(const n of data)for(const w of n.workers_json||[])workers.set(String(w.worker_id),w.name);\n        const filters=gw93El('div',null,gw93Report);const worker=gw93Select(filters,'Worker',[['','All workers'],...Array.from(workers).sort((a,b)=>a[1].localeCompare(b[1]))]);const category=gw93Select(filters,'Category',[['','All categories'],...gw93Categories.map(v=>[v,v])]);const responsibility=gw93Select(filters,'Responsibility',[['','All'],['Involved','Involved'],['Confirmed Responsible','Confirmed Responsible']]);gw93El('label','Job ID',filters);const job=gw93El('input',null,filters);job.placeholder='All jobs';const list=gw93El('div',null,gw93Report);let gw94Filtered=[];gw93Button(filters,'Print filtered issue notes \/ PDF',()=>gw94Print(gw94Filtered,[], 'Worker: '+worker.selectedOptions[0].textContent+' | Category: '+category.value+' | Responsibility: '+responsibility.value+' | Job: '+(job.value||'All')));\n        function render(){if(!current())return;list.replaceChildren();const rows=data.filter(n=>(!category.value||n.category===category.value)&&(!job.value.trim()||String(n.job_id).toLowerCase().includes(job.value.trim().toLowerCase()))&&((!worker.value&&!responsibility.value)||(n.workers_json||[]).some(w=>(!worker.value||String(w.worker_id)===worker.value)&&(!responsibility.value||w.responsibility===responsibility.value))));gw94Filtered=rows;status.textContent=rows.length+' classified note(s)';const totals=new Map();for(const n of rows)for(const w of n.workers_json||[]){const key=String(w.worker_id),t=totals.get(key)||{name:w.name,involved:0,responsible:0};t[w.responsibility==='Confirmed Responsible'?'responsible':'involved']++;totals.set(key,t);}for(const [id,t] of totals){const b=gw93Button(list,t.name+' \u2014 Involved: '+t.involved+' \u00b7 Confirmed responsible: '+t.responsible,()=>{worker.value=id;render();});b.style.cssText='text-align:left;';}for(const n of rows){const a=gw93El('article',null,list);a.style.cssText='padding:12px 0;border-top:1px solid #cbd5e1;';gw93El('strong',n.job_id+' \u00b7 '+n.category+' \u00b7 '+n.note_type,a);gw93El('p',n.author_name+' \u00b7 '+annualProblemDate(n.note_date),a);gw93El('p',n.note_body,a).style.cssText='white-space:pre-wrap;overflow-wrap:anywhere;';gw93El('p',(n.workers_json||[]).map(w=>w.name+' \u2014 '+w.responsibility).join('; ')||'No workers selected',a);gw93Button(a,'Correct classification \/ history',async()=>{try{await gw93Editor(a,n,n.workers_json||[],null,()=>current()&&a.isConnected,()=>void gw93Annual(year,requestId));}catch(e){if(current())status.textContent=e.message;}});}}\n        worker.onchange=category.onchange=responsibility.onchange=job.oninput=render;render();\n      }catch(e){if(current())status.textContent='Unable to load classified notes: '+e.message;}\n    }\n\n    function annualProblemMetric(label, value) {\n      const box = document.createElement(\"div\");\n      box.style.cssText =\n        \"padding:12px;border:1px solid #dbe3ea;border-radius:8px;background:#f8fafc;\";\n      const title = document.createElement(\"div\");\n      title.textContent = label;\n      title.style.cssText = \"font-size:13px;color:#526579;margin-bottom:4px;\";\n      const number = document.createElement(\"strong\");\n      number.textContent = String(value);\n      number.style.cssText = \"font-size:22px;\";\n      box.append(title, number);\n      return box;\n    }\n\n    function annualProblemBreakdownBox(titleText, counts) {\n      const box = document.createElement(\"section\");\n      box.style.cssText =\n        \"padding:12px;border:1px solid #dbe3ea;border-radius:8px;background:#fff;\";\n      const title = document.createElement(\"h4\");\n      title.textContent = titleText;\n      title.style.cssText = \"margin:0 0 8px;font-size:17px;\";\n      box.appendChild(title);\n\n      const entries = Array.from(counts.entries()).sort(function (a, b) {\n        if (b[1] !== a[1]) return b[1] - a[1];\n        return String(a[0]).localeCompare(String(b[0]));\n      });\n\n      if (entries.length === 0) {\n        const empty = document.createElement(\"p\");\n        empty.textContent = \"None\";\n        empty.style.margin = \"0\";\n        box.appendChild(empty);\n        return box;\n      }\n\n      for (const entry of entries) {\n        const row = document.createElement(\"div\");\n        row.style.cssText =\n          \"display:flex;justify-content:space-between;gap:12px;padding:5px 0;\" +\n          \"border-bottom:1px solid #edf2f7;\";\n        const name = document.createElement(\"span\");\n        name.textContent = entry[0];\n        const count = document.createElement(\"strong\");\n        count.textContent = String(entry[1]);\n        row.append(name, count);\n        box.appendChild(row);\n      }\n      return box;\n    }\n\n    function annualProblemDate(value) {\n      if (!value) return \"Not recorded\";\n      const date = new Date(value);\n      if (Number.isNaN(date.getTime())) return \"Not recorded\";\n      return date.toLocaleString([], {\n        timeZone: \"America\/Chicago\",\n        year: \"numeric\",\n        month: \"short\",\n        day: \"numeric\",\n        hour: \"numeric\",\n        minute: \"2-digit\"\n      });\n    }\n\n    function renderAnnualProblemReport(rows, year) {\n      annualProblemSummary.replaceChildren();\n      annualProblemBreakdowns.replaceChildren();\n      annualProblemList.replaceChildren();\n\n      let openCount = 0;\n      let resolvedCount = 0;\n      let totalReworkCost = 0;\n      const issueCounts = new Map();\n      const workerCounts = new Map();\n\n      for (const row of rows) {\n        if (row.status === \"Open\") openCount++;\n        if (row.status === \"Resolved\") resolvedCount++;\n\n        const cost = Number(row.rework_cost);\n        if (Number.isFinite(cost)) totalReworkCost += cost;\n\n        const issueName = row.issue_type || \"Other\";\n        issueCounts.set(issueName, (issueCounts.get(issueName) || 0) + 1);\n\n        const workerRows = Array.isArray(row.workers_json) ? row.workers_json : [];\n        if (workerRows.length > 0) {\n          for (const worker of workerRows) {\n            const workerName =\n              worker && worker.name ? String(worker.name).trim() : \"\";\n            if (workerName) {\n              workerCounts.set(workerName, (workerCounts.get(workerName) || 0) + 1);\n            }\n          }\n        } else if (row.worker_names) {\n          const workerName = String(row.worker_names).trim();\n          if (workerName) {\n            workerCounts.set(workerName, (workerCounts.get(workerName) || 0) + 1);\n          }\n        }\n      }\n\n      annualProblemSummary.append(\n        annualProblemMetric(\"Year\", year),\n        annualProblemMetric(\"Total Issues\", rows.length),\n        annualProblemMetric(\"Open\", openCount),\n        annualProblemMetric(\"Resolved\", resolvedCount),\n        annualProblemMetric(\"Rework Cost\", \"$\" + totalReworkCost.toFixed(2))\n      );\n\n      annualProblemBreakdowns.append(\n        annualProblemBreakdownBox(\"Issues by Type\", issueCounts),\n        annualProblemBreakdownBox(\"Issues by Worker\", workerCounts)\n      );\n\n      if (rows.length === 0) {\n        const empty = document.createElement(\"p\");\n        empty.textContent = \"No problem reports found for \" + year + \".\";\n        annualProblemList.appendChild(empty);\n        return;\n      }\n\n      for (const row of rows) {\n        const card = document.createElement(\"section\");\n        card.style.cssText =\n          \"padding:14px 0;border-bottom:1px solid #dbe3ea;overflow-wrap:anywhere;\";\n\n        const heading = document.createElement(\"h4\");\n        heading.textContent =\n          \"Report #\" + row.id + \" \u2014 \" + (row.issue_type || \"Issue\") +\n          \" \u2014 \" + (row.status || \"Unknown\");\n        heading.style.cssText = \"margin:0 0 7px;font-size:18px;\";\n\n        const meta = document.createElement(\"p\");\n        meta.textContent =\n          \"Job ID: \" + (row.job_id || \"Not recorded\") +\n          \" | Reported: \" + annualProblemDate(row.reported_at) +\n          \" | By: \" + (row.reported_by_name || \"Not recorded\");\n        meta.style.cssText = \"margin:4px 0;font-size:14px;color:#526579;\";\n\n        const workers = document.createElement(\"p\");\n        workers.textContent =\n          \"Worker(s): \" + (row.worker_names || \"Not recorded\");\n        workers.style.cssText = \"margin:6px 0;\";\n\n        const description = document.createElement(\"p\");\n        description.textContent = row.description || \"\";\n        description.style.cssText =\n          \"white-space:pre-wrap;margin:8px 0;font-size:16px;line-height:1.45;\";\n\n        card.append(heading, meta, workers, description);\n\n        if (row.action_needed) {\n          const action = document.createElement(\"p\");\n          action.textContent = \"Action Needed: \" + row.action_needed;\n          action.style.cssText = \"white-space:pre-wrap;margin:6px 0;\";\n          card.appendChild(action);\n        }\n\n        if (row.rework_cost !== null && row.rework_cost !== undefined && row.rework_cost !== \"\") {\n          const costValue = Number(row.rework_cost);\n          const cost = document.createElement(\"p\");\n          cost.textContent =\n            \"Rework Cost: \" +\n            (Number.isFinite(costValue) ? \"$\" + costValue.toFixed(2) : String(row.rework_cost));\n          cost.style.cssText = \"margin:6px 0;\";\n          card.appendChild(cost);\n        }\n\n        if (row.notes) {\n          const notes = document.createElement(\"p\");\n          notes.textContent = \"Internal Notes: \" + row.notes;\n          notes.style.cssText = \"white-space:pre-wrap;margin:6px 0;\";\n          card.appendChild(notes);\n        }\n\n        if (row.status === \"Resolved\") {\n          const resolved = document.createElement(\"p\");\n          resolved.textContent =\n            \"Resolved: \" + annualProblemDate(row.resolved_at) +\n            \" | By: \" + (row.resolved_by_name || \"Not recorded\");\n          resolved.style.cssText = \"margin:6px 0;font-size:14px;color:#526579;\";\n          card.appendChild(resolved);\n\n          const resolution = document.createElement(\"p\");\n          resolution.textContent =\n            \"Resolution Notes: \" + (row.resolution_notes || \"None\");\n          resolution.style.cssText = \"white-space:pre-wrap;margin:6px 0;\";\n          card.appendChild(resolution);\n        }\n\n        annualProblemList.appendChild(card);\n      }\n    }\n\n    async function loadAnnualProblemReport() {\n      if (!annualProblemAllowed) return;\n      if (!client) return;\n      if (logout.hidden) return;\n\n      const year = Number(annualProblemYear.value);\n      if (!Number.isInteger(year) || year < 2020 || year > 2100) {\n        annualProblemMessage.textContent = \"Enter a valid year from 2020 to 2100.\";\n        return;\n      }\n\n      const requestId = ++annualProblemRequestId;\n      gw94ClearPrint();gw94Year=year;\n      annualProblemLoad.disabled = true;\n      annualProblemYear.disabled = true;\n      gw93Report.replaceChildren();\n      annualProblemMessage.textContent = \"Loading \" + year + \" report...\";\n\n      try {\n        const result = await client.rpc(\n          \"gw_owner_annual_problem_report\",\n          { p_year: year }\n        );\n        if (result.error) throw result.error;\n        if (requestId !== annualProblemRequestId) return;\n        if (!annualProblemAllowed) return;\n        if (logout.hidden) return;\n\n        const rows = Array.isArray(result.data) ? result.data : [];\n        gw94Formal=rows;gw94PrintReady();\n        renderAnnualProblemReport(rows, year);\n        void gw93Annual(year, requestId);\n        annualProblemMessage.textContent =\n          rows.length + \" issue report(s) found for \" + year + \".\";\n      } catch (error) {\n        if (requestId !== annualProblemRequestId) return;\n        annualProblemSummary.replaceChildren();\n        annualProblemBreakdowns.replaceChildren();\n        annualProblemList.replaceChildren();\n        annualProblemMessage.textContent =\n          \"Unable to load annual report: \" + error.message;\n      } finally {\n        if (requestId === annualProblemRequestId) {\n          if (!logout.hidden) {\n            annualProblemLoad.disabled = false;\n            annualProblemYear.disabled = false;\n          }\n        }\n      }\n    }\n\n    function resetAnnualProblemReport() {\n      gw94ClearPrint();\n      annualProblemRequestId++;\n      annualProblemToggle.hidden = true;\n      annualProblemToggle.setAttribute(\"aria-expanded\", \"false\");\n      annualProblemPanel.hidden = true;\n      annualProblemLoad.disabled = false;\n      annualProblemYear.disabled = false;\n      annualProblemMessage.textContent = \"\";\n      annualProblemSummary.replaceChildren();\n      annualProblemBreakdowns.replaceChildren();\n      annualProblemList.replaceChildren();\n      gw93Report.replaceChildren();\n    }\n\n    annualProblemToggle.addEventListener(\"click\", function () {\n      if (!annualProblemAllowed) return;\n      if (logout.hidden) return;\n\n      annualProblemPanel.hidden = !annualProblemPanel.hidden;\n      annualProblemToggle.setAttribute(\n        \"aria-expanded\",\n        String(!annualProblemPanel.hidden)\n      );\n\n      if (!annualProblemPanel.hidden) {\n        void loadAnnualProblemReport();\n      }\n    });\n\n    annualProblemLoad.addEventListener(\"click\", function () {\n      void loadAnnualProblemReport();\n    });\n\n    annualProblemYear.addEventListener(\"keydown\", function (event) {\n      if (event.key === \"Enter\") {\n        event.preventDefault();\n        void loadAnnualProblemReport();\n      }\n    });\n\n  let authViewRequestId = 0;\n  async function showSignedIn() {\n    if (recoveringPassword) { showPasswordSetup(); return; }\n    const requestId = ++authViewRequestId;\n    gw94SetName('');\n    gwScheduleReset();\n    form.hidden = true;\n    logout.hidden = true;\n      officePortalLink.hidden = true;\n    jobSearch.hidden = true;\n    dashboard.hidden = true;\n    resetCreateJob();\n    resetCustomerCodeView();\n    resetPhotoApprovalView();\n    resetDrawingView();\n    resetProblemView();\n    annualProblemAllowed = false;\n    resetAnnualProblemReport();\n    message.textContent = \"Checking Portal access...\";\n    try {\n      const { data: auth, error: authError } = await client.auth.getUser();\n      if (authError || !auth.user) throw new Error(\"Please log in again.\");\n      const { data: isActive, error: accessError } =\n        await client.rpc(\"gw_employee_is_active\");\n      if (accessError) throw new Error(\"Unable to verify Portal access. Please try again.\");\n      if (requestId !== authViewRequestId) return;\n      if (isActive !== true) {\n        let signOutFailed = false;\n        try {\n          const { error: signOutError } = await client.auth.signOut();\n          signOutFailed = !!signOutError;\n        } catch (_error) {\n          signOutFailed = true;\n        }\n        if (requestId !== authViewRequestId) return;\n        showSignedOut();\n        message.textContent = \"This account's Portal access is disabled. Contact the office.\" +\n          (signOutFailed ? \" Sign-out failed; close this browser and contact the office.\" : \"\");\n        return;\n      }\n      \/\/ Resolve the employee role at login so Office Accounting is a true\n      \/\/ Portal-level entry instead of appearing only after a successful Job search.\n      const { data: accountingProfile, error: accountingProfileError } = await client\n        .from(\"employee_profiles\")\n        .select(\"role,display_name\")\n        .eq(\"user_id\", auth.user.id)\n        .maybeSingle();\n      if (requestId !== authViewRequestId) return;\n      accountingRoleAllowed = !accountingProfileError && !!accountingProfile &&\n        [\"owner\", \"office\"].includes(accountingProfile.role);\n      annualProblemAllowed =\n        !accountingProfileError &&\n        !!accountingProfile &&\n        [\"owner\", \"office\"].includes(accountingProfile.role);\n\n      \/\/ Office is handled outside the Field Portal.\n      \/\/ Keep the legacy accounting code available, but do not show its button here.\n      accountingToggle.hidden = true;\n      accountingPanel.hidden = true;\n      accountingToggle.setAttribute(\"aria-expanded\", \"false\");\n      if (accountingToggle.isConnected) accountingToggle.remove();\n      if (accountingPanel.isConnected) accountingPanel.remove();\n\n      \/\/ Report navigation remains in the administrative footer.\n      annualProblemToggle.hidden = !annualProblemAllowed;\n      annualProblemPanel.hidden = true;\n      annualProblemToggle.setAttribute(\"aria-expanded\", \"false\");\n\n      form.hidden = true;\n      logout.hidden = false;\n      officePortalLink.hidden = !accountingRoleAllowed;\n      jobSearch.hidden = false;\n      monthlyJobPanel.hidden = false;\n      void loadMonthlyJobIds();\n      gw94SetName(!accountingProfileError ? accountingProfile?.display_name : '');\n      message.textContent = \"Login successful!\";\n      bulletinEntry.hidden = false;\n      bulletinEntry.textContent = \"Bulletin Board\";\n      void checkEmployeeDirectoryAccess();\n       void checkCreateJobAccess();\n      void loadBulletinBoard();\n    } catch (error) {\n      if (requestId !== authViewRequestId) return;\n      try { await client.auth.signOut(); } catch (_error) { \/* fail closed *\/ }\n      if (requestId !== authViewRequestId) return;\n      showSignedOut();\n      message.textContent = error.message || \"Unable to verify Portal access.\";\n    }\n  }\n\n    function showSignedOut() {\n      document.querySelectorAll('[data-gw-priority-notes]').forEach(el=>el.remove());\n      gw94SetName('');\n      gwScheduleReset();\n      clearRecoveryMarker();\n      recoveringPassword = false;\n      setPasswordForm.hidden = true;\n      authViewRequestId++;\n       resetEmployeeDirectory();\n       resetCreateJob();\n       resetCustomerCodeView();\n       resetPhotoApprovalView();\n       resetDrawingView();\n       resetProblemView();\n       annualProblemAllowed = false;\n       resetAnnualProblemReport();\n       resetBulletinBoard();\n    form.hidden = false;\n      logout.hidden = true;\n      officePortalLink.hidden = true;\n   jobSearch.hidden = true;\nmonthlyJobPanel.hidden = true;\nmonthlyJobList.replaceChildren();\ndashboard.hidden = true;\naccountingRoleAllowed = false;\nresetAccounting();\nresetCompletion();\nresetOwnerAssignments();\nresetWorkDashboards();\nresetPhotoView();\nif (!photoUploadBusy) clearPendingPhotos();\nallReviewsPanel.hidden = true;\nallReviewsContent.replaceChildren();\nmeasurementLoadedJobId = null;\ndocument.getElementById(\"gw-save-measurement\").disabled = true;\ndocument.getElementById(\"gw-review-notes\").value = \"\";\ndocument.getElementById(\"gw-review-confirmed\").checked = false;\ndocument.getElementById(\"gw-review-ready\").checked = false;\ndocument.getElementById(\"gw-save-review\").disabled = true;\n      message.textContent = \"You have logged out.\";\n    }\n\n    \/\/ Stop the form from navigating to the company homepage.\n    form.addEventListener(\"submit\", async function (event) {\n      event.preventDefault();\n\n      if (!client) {\n        message.textContent = \"Login system is still loading. Please wait.\";\n        return;\n      }\n\n      staySignedIn = remember.checked;\n      message.textContent = \"Signing in...\";\n\n      try {\n        const { error } = await client.auth.signInWithPassword({\n          email: email.value.trim(),\n          password: password.value\n        });\n\n        password.value = \"\";\n\n        if (error) {\n          message.textContent =\n            \"Login failed. Please check your email and password.\";\n          return;\n        }\n\n        await showSignedIn();\n      } catch (error) {\n        password.value = \"\";\n        message.textContent = \"Connection error. Please try again.\";\n      }\n    });\n\n    logout.addEventListener(\"click\", async function () {\n      if (!client) return;\n\n      const { error } = await client.auth.signOut();\n\n      if (error) {\n        message.textContent = \"Unable to log out. Please try again.\";\n        return;\n      }\n\n      showSignedOut();\n    });\n\n    message.textContent = \"Loading login system...\";\n\n    const script = document.createElement(\"script\");\n    script.src =\n      \"https:\/\/cdn.jsdelivr.net\/npm\/@supabase\/supabase-js@2\";\n\n    script.onload = async function () {\n      try {\n        const storage = {\n          getItem(key) {\n            return localStorage.getItem(key) ||\n                   sessionStorage.getItem(key);\n          },\n          setItem(key, value) {\n            localStorage.removeItem(key);\n            sessionStorage.removeItem(key);\n\n            const destination = staySignedIn\n              ? localStorage\n              : sessionStorage;\n\n            destination.setItem(key, value);\n          },\n          removeItem(key) {\n            localStorage.removeItem(key);\n            sessionStorage.removeItem(key);\n          }\n        };\n\n        client = window.supabase.createClient(URL, KEY, {\n          auth: {\n            storage,\n            storageKey: STORAGE_KEY,\n            persistSession: true,\n            autoRefreshToken: true,\n            detectSessionInUrl: true\n          }\n        });\n           \/\/ PASSWORD_RECOVERY fires when Supabase processes the emailed recovery URL.\n        \/\/ Register before checking session to avoid routing the user to the dashboard.\n        client.auth.onAuthStateChange((event, session) => {\n          if (event === \"PASSWORD_RECOVERY\" && session && session.user && session.user.id) {\n            saveRecoveryMarker(session.user.id);\n            showPasswordSetup();\n          }\n        });\n        const urlFlags = new URLSearchParams(window.location.hash.replace(\/^#\/, \"\"));\n        const queryFlags = new URLSearchParams(window.location.search);\n        if (urlFlags.get(\"type\") === \"recovery\" || queryFlags.get(\"type\") === \"recovery\") {\n          recoveringPassword = true;\n        }\n        const { data, error } = await client.auth.getSession();\n        const marker = getRecoveryMarker();\n        if (error) {\n          message.textContent = \"Unable to check login status.\";\n        } else if (data.session && data.session.user &&\n                   (recoveringPassword || (marker && marker.userId === data.session.user.id))) {\n          \/\/ A recovery session must still belong to the same authenticated user.\n          \/\/ A stale marker alone never authenticates anybody.\n          const { data: verified, error: verifyError } = await client.auth.getUser();\n          if (!verifyError && verified.user && verified.user.id === data.session.user.id) {\n            if (recoveringPassword) saveRecoveryMarker(verified.user.id);\n            showPasswordSetup();\n          } else {\n            message.textContent = \"Unable to verify the password setup session. Reopen your email link or request a new one.\";\n          }\n        } else if (data.session) {\n          if (marker && marker.userId !== data.session.user.id) clearRecoveryMarker();\n          await showSignedIn();\n        } else if (recoveringPassword || marker) {\n          \/\/ Do not show password-entry UI without a valid Supabase session.\n          clearRecoveryMarker();\n          recoveringPassword = false;\n          form.hidden = false;\n              message.textContent = \"Password setup session is no longer available. Reopen your email link or request a new one.\";\n        } else {\n          message.textContent = \"Please log in.\";\n        }\n      } catch (error) {\n        message.textContent = \"Unable to initialize login system.\";\n      }\n    };\n\n    script.onerror = function () {\n      message.textContent = \"Unable to load login system.\";\n    };\n    let recoveryResumeBusy = false;\n    async function restoreRecoveryAfterAppSwitch() {\n      if (!client || recoveryResumeBusy || savePassword.disabled) return;\n      const marker = getRecoveryMarker();\n      if (!marker) return;\n      recoveryResumeBusy = true;\n      try {\n        const { data: sessionResult, error: sessionError } = await client.auth.getSession();\n        if (sessionError || !sessionResult.session || !sessionResult.session.user ||\n            sessionResult.session.user.id !== marker.userId) return;\n        const { data: userResult, error: userError } = await client.auth.getUser();\n        if (!userError && userResult.user && userResult.user.id === marker.userId) {\n          if (!getRecoveryMarker()) return; \/\/ User may have completed setup while we awaited.\n          showPasswordSetup();\n        }\n      } catch (_error) { \/* leave current UI unchanged; user can reopen the email link *\/ }\n      finally { recoveryResumeBusy = false; }\n    }\n    window.addEventListener(\"pageshow\", function () {\n      void restoreRecoveryAfterAppSwitch();\n    });\n    document.addEventListener(\"visibilitychange\", function () {\n      if (!document.hidden) void restoreRecoveryAfterAppSwitch();\n    });\nconst findJob = document.getElementById(\"gw-find-job\");\nconst jobIdInput = document.getElementById(\"gw-job-id\");\nconst jobResult = document.getElementById(\"gw-job-result\");\nconst dashboard = document.getElementById(\"gw-job-dashboard\");\n\n\/\/ ================================================================\n\/\/ THIS MONTH JOB ID LIST\n\/\/ Purpose: show only Job IDs already registered in the Portal,\n\/\/ so staff can quickly avoid duplicate Job ID entry.\n\/\/ ================================================================\n\n\/\/ ================================================================\n\/\/ JOB BOARD \u2014 In Process \/ Recently Completed\n\/\/ Replaces the old \"This Month Jobs\" display only.\n\/\/ ================================================================\nconst monthlyJobPanel = document.createElement(\"section\");\nmonthlyJobPanel.id = \"gw-monthly-job-ids\";\nmonthlyJobPanel.hidden = true;\nmonthlyJobPanel.style.cssText = \"margin:12px 0 16px;padding:14px;border:1px solid #cbd5e1;border-radius:10px;background:white;\";\n\nconst monthlyJobList = document.createElement(\"div\");\nmonthlyJobList.id = \"gw-monthly-job-list\";\nconst boardStyle = document.createElement(\"style\");\nboardStyle.textContent = `\n:is(#gw-monthly-job-ids,#gw-re17-quotations) .gw-board-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(124px,1fr));gap:10px;margin:10px 0 20px}\n:is(#gw-monthly-job-ids,#gw-re17-quotations) .gw-job-icon{position:relative;width:100%;min-height:76px;padding:10px 7px;border:1px solid #cbd5e1;border-radius:9px;background:#f8fafc;color:#163b5a;text-align:center;cursor:default}\n:is(#gw-monthly-job-ids,#gw-re17-quotations) .gw-job-icon:hover,:is(#gw-monthly-job-ids,#gw-re17-quotations) .gw-job-icon:focus-visible{border-color:#1769aa;background:#e7eadf}\n:is(#gw-monthly-job-ids,#gw-re17-quotations) .gw-job-code{display:block;margin:0 auto;padding:0;border:0;background:transparent;color:#0b4f8a;font-size:14px;font-weight:800;white-space:nowrap;cursor:pointer;width:auto;min-height:0}:is(#gw-monthly-job-ids,#gw-re17-quotations) .gw-job-code:hover{text-decoration:underline}\n:is(#gw-monthly-job-ids,#gw-re17-quotations) .gw-job-stars{display:flex;justify-content:center;align-items:center;gap:8px;white-space:nowrap;margin:3px 0}\n:is(#gw-monthly-job-ids,#gw-re17-quotations) .gw-job-address{display:block;font-size:12px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}\n#gw-monthly-job-ids .gw-job-alert{position:absolute;top:-7px;right:-6px;background:#c62828;color:white;border-radius:50%;font-size:12px;font-weight:bold;width:19px;height:19px;line-height:19px}\n#gw-monthly-job-ids .gw-board-heading{font-size:18px;margin:12px 0 4px;color:#0b4f8a}\n@media(max-width:380px){:is(#gw-monthly-job-ids,#gw-re17-quotations) .gw-board-grid{grid-template-columns:repeat(2,minmax(0,1fr))}:is(#gw-monthly-job-ids,#gw-re17-quotations) .gw-job-icon{width:100%}}\n`;\nconst gwMonthNav=document.createElement(\"button\");\ngwMonthNav.type=\"button\"; gwMonthNav.id=\"gw-monthly-jobs-nav\"; gwMonthNav.textContent=\"Monthly Jobs\";\nconst gwMonthControls=document.createElement(\"div\"); gwMonthControls.hidden=true;\nconst gwMonthBack=document.createElement(\"button\"); gwMonthBack.type=\"button\"; gwMonthBack.textContent=\"\u2190 Dashboard\";\nconst gwMonthPick=document.createElement(\"input\"); gwMonthPick.type=\"month\"; gwMonthPick.setAttribute(\"aria-label\",\"Job month\");\nconst nowMonth=new Intl.DateTimeFormat(\"en-CA\",{timeZone:\"America\/Chicago\",year:\"numeric\",month:\"2-digit\"}).formatToParts(new Date());\ngwMonthPick.value=nowMonth.find(p=>p.type===\"year\").value+\"-\"+nowMonth.find(p=>p.type===\"month\").value;\nconst gwMonthFilter=document.createElement(\"select\"); gwMonthFilter.setAttribute(\"aria-label\",\"Job status filter\");\nfor(const v of [\"All\",\"In Process\",\"Completed\"])gwMonthFilter.add(new Option(v,v));\nconst gwMonthSummary=document.createElement(\"p\"); gwMonthSummary.setAttribute(\"role\",\"status\");\ngwMonthControls.append(gwMonthBack,gwMonthPick,gwMonthFilter,gwMonthSummary);\nlet gwMonthMode=false;\nfunction gwMonthSwitch(open){gwMonthMode=open;gwMonthNav.hidden=open;gwMonthControls.hidden=!open;jobSearch.style.display=open?\"none\":\"\";void loadMonthlyJobIds();}\ngwMonthNav.onclick=()=>gwMonthSwitch(true);gwMonthBack.onclick=()=>gwMonthSwitch(false);\ngwMonthPick.onchange=gwMonthFilter.onchange=()=>void loadMonthlyJobIds();\nmonthlyJobPanel.append(boardStyle,gwMonthNav,gwMonthControls,monthlyJobList);\njobSearch.insertAdjacentElement(\"afterend\", monthlyJobPanel);\n\/\/ V3: focused Job Details view, reached only by clicking the Job ID.\nconst gwDetailView = document.createElement(\"section\");\ngwDetailView.id = \"gw-focused-job-details\";\ngwDetailView.hidden = true;\nconst gwFieldStyle = document.createElement(\"style\");\ngwFieldStyle.textContent = `\n#gw-focused-job-details{box-sizing:border-box;max-width:620px;margin:14px auto;padding:16px;border:1px solid #d7e2ea;border-radius:18px;background:#fff;color:#20374a;font-family:system-ui,-apple-system,Arial,sans-serif}\n#gw-focused-job-details *{box-sizing:border-box}\n:is(#gw-focused-job-details,#gw-re173-action-header) .gw-field-eyebrow{font-size:11px;letter-spacing:1.4px;font-weight:800;color:#607e90}\n:is(#gw-focused-job-details,#gw-re173-action-header) .gw-field-title{font-size:24px;font-weight:800;margin:3px 0 14px}\n:is(#gw-focused-job-details,#gw-re173-action-header) .gw-field-job{background:#e9eee4;border-radius:14px;padding:16px;margin-bottom:20px}\n:is(#gw-focused-job-details,#gw-re173-action-header) .gw-field-code{font-size:21px;font-weight:850;color:#174c70;overflow-wrap:anywhere}\n:is(#gw-focused-job-details,#gw-re173-action-header) .gw-field-customer{font-weight:700;font-size:17px;margin-top:9px}\n:is(#gw-focused-job-details,#gw-re173-action-header) .gw-field-address{font-size:14px;color:#526a79;margin:7px 0 11px;overflow-wrap:anywhere}\n:is(#gw-focused-job-details,#gw-re173-action-header) .gw-field-contact{display:flex;flex-wrap:wrap;gap:9px}\n:is(#gw-focused-job-details,#gw-re173-action-header) .gw-field-contact a{display:inline-flex;align-items:center;justify-content:center;text-decoration:none;border:1px solid #b7cbd9;border-radius:9px;background:#fff;color:#174c70;padding:9px 14px;font-weight:700;font-size:13px}\n:is(#gw-focused-job-details,#gw-re173-action-header) .gw-field-heading{font-size:17px;font-weight:800;margin:0 0 12px}\n:is(#gw-focused-job-details,#gw-re173-action-header) .gw-field-actions{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:11px}\n:is(#gw-focused-job-details,#gw-re173-action-header) .gw-field-action{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:5px;min-height:76px;padding:8px 6px;border:1px solid #d5e1e8;border-radius:13px;background:#f5f0e7;color:#16435f;font-weight:750;font-size:14px;line-height:1.25;text-align:center;white-space:normal;cursor:pointer}\n:is(#gw-focused-job-details,#gw-re173-action-header) .gw-field-action .gw-field-icon{font-size:28px;line-height:1.1}\n:is(#gw-focused-job-details,#gw-re173-action-header) .gw-field-action small{font-size:11px;font-weight:500;color:#657b8b}\n\n:is(#gw-focused-job-details,#gw-re173-action-header) .gw-field-action{position:relative}\n:is(#gw-focused-job-details,#gw-re173-action-header) .gw-field-action[data-state=\"done\"]{background:#eaf5ec;border-color:#b8d9c1}\n:is(#gw-focused-job-details,#gw-re173-action-header) .gw-field-action[data-state=\"alert\"]{background:#fff0ef;border-color:#e4aaa5}\n:is(#gw-focused-job-details,#gw-re173-action-header) .gw-field-mark{position:absolute;top:7px;right:8px;font-size:16px;line-height:1;font-weight:800;color:#82909b}\n:is(#gw-focused-job-details,#gw-re173-action-header) .gw-field-action[data-state=\"done\"] .gw-field-mark,:is(#gw-focused-job-details,#gw-re173-action-header) .gw-field-action[data-state=\"done\"] small{color:#258344}\n:is(#gw-focused-job-details,#gw-re173-action-header) .gw-field-action[data-state=\"alert\"] .gw-field-mark,:is(#gw-focused-job-details,#gw-re173-action-header) .gw-field-action[data-state=\"alert\"] small{color:#b42318}\n:is(#gw-focused-job-details,#gw-re173-action-header) .gw-field-action:focus-visible{outline:3px solid #2584c4;outline-offset:2px}\n:is(#gw-focused-job-details,#gw-re173-action-header) .gw-field-quick{margin-top:20px;border-top:1px solid #e1e9ee;padding-top:16px}\n:is(#gw-focused-job-details,#gw-re173-action-header) .gw-field-camera{display:block;width:100%;min-height:58px;border:0;border-radius:12px;background:#116c9d;color:#fff;font-size:17px;font-weight:800;cursor:pointer}\n:is(#gw-focused-job-details,#gw-re173-action-header) .gw-field-note{font-size:12px;color:#697d8b;margin:8px 0 0}\n:is(#gw-focused-job-details,#gw-re173-action-header) .gw-field-back{border:0;background:transparent;color:#176c9d;font-size:14px;font-weight:750;padding:7px 0;margin:0 0 7px;cursor:pointer}\n@media(max-width:380px){#gw-focused-job-details{padding:12px}:is(#gw-focused-job-details,#gw-re173-action-header) .gw-field-action{font-size:12px;min-height:102px}}\n`;\nconst gwDetailBack = document.createElement(\"button\");\ngwDetailBack.type = \"button\";\ngwDetailBack.className = \"gw-field-back\";\ngwRE3Label(gwDetailBack,\"Back to Dashboard\");\ngwDetailBack.classList.add(\"gw-re173-back\");\nconst gwFieldEyebrow = document.createElement(\"div\");\ngwFieldEyebrow.className = \"gw-field-eyebrow\";\ngwFieldEyebrow.textContent = \"GW KITCHEN & BATH\";\nconst gwFieldTitle = document.createElement(\"div\");\ngwFieldTitle.className = \"gw-field-title\";\ngwFieldTitle.className=\"gw-re174-job-id gw-re17-id\";\nconst gwSharedJobTop=document.createElement(\"div\");gwSharedJobTop.className=\"gw-re174-job-top\";gwSharedJobTop.append(gwFieldTitle,gwDetailBack);\nconst gwDetailInfo = document.createElement(\"div\");\ngwDetailInfo.className = \"gw-field-job\";\nconst gwDetailHeading = document.createElement(\"div\");\ngwDetailHeading.className = \"gw-field-heading\";\ngwRE3Label(gwDetailHeading,\"On-Site Work\");\nconst gwDetailActions = document.createElement(\"div\");\ngwDetailActions.className = \"gw-field-actions\";\nconst gwDetailButtons = {};\nfor (const [key,label,icon,subtitle] of [\n  [\"measurement\",\"Job Details\",\"\ud83d\udccb\",\"Measurements & specifications\"],\n  [\"before\",\"Before Photos\",\"\ud83d\udcf7\",\"Before installation\"],\n  [\"after\",\"After Photos\",\"\ud83d\uddbc\ufe0f\",\"After installation\"],\n  [\"issue\",\"Issue Photo\",\"\u26a0\ufe0f\",\"Issues & damage\"],\n  [\"additional\",\"Additional Work\",\"\ud83d\udd27\",\"Extra on-site work\"]\n]) {\n  const button = document.createElement(\"button\");\n  button.type = \"button\";\n  button.className = \"gw-field-action\"; button.dataset.gwAction=key;\n  const symbol = document.createElement(\"span\");\n  symbol.className = \"gw-field-icon\";\n  symbol.textContent = icon;\n  const name = document.createElement(\"span\");\n  gwRE3Label(name,label);\n  const hint = document.createElement(\"small\");\n  gwRE3Label(hint,subtitle);\n  const mark = document.createElement(\"span\");\n  mark.className = \"gw-field-mark\";\n  mark.setAttribute(\"aria-hidden\",\"true\");\n  button.append(symbol,name,hint,mark);\n  gwDetailActions.appendChild(button);\n  gwDetailButtons[key] = button;\n}\nconst gwQuickArea = document.createElement(\"div\");\ngwQuickArea.className = \"gw-field-quick\";\nconst gwQuickHeading = document.createElement(\"div\");\ngwQuickHeading.className = \"gw-field-heading\";\ngwQuickHeading.textContent = \"Quick Photo\";\nconst gwQuickCamera = document.createElement(\"button\");\ngwQuickCamera.type = \"button\";\ngwQuickCamera.className = \"gw-field-camera\";\ngwQuickCamera.textContent = \"\ud83d\udcf7 Take Photo\";\nconst gwQuickNote = document.createElement(\"p\");\ngwQuickNote.className = \"gw-field-note\";\ngwQuickNote.textContent = \"Automatically linked to the selected Job ID. Choose a photo category before saving.\";\ngwQuickArea.append(gwQuickHeading,gwQuickCamera,gwQuickNote);\nconst gwAdditionalSlot=document.createElement(\"div\");gwAdditionalSlot.className=\"gw-re173-additional\";\ngwAdditionalSlot.append(gwDetailButtons.additional);\ngwDetailActions.classList.add(\"gw-re173-job-nav\");\ngwDetailView.append(gwFieldStyle,gwSharedJobTop,gwDetailActions,gwDetailInfo);\nmonthlyJobPanel.insertAdjacentElement(\"afterend\",gwDetailView);\nlet gwDetailOpen = false;\nlet gwDetailSelectedJobId = \"\";\nconst gwSearchHiddenBranches = new Map();\n\n\/\/ The original dashboard may be NESTED inside #gw-job-search.\n\/\/ Hiding that parent also hides the dashboard, even when dashboard.hidden=false.\nfunction gwShowDashboardBranch(show) {\n  if (show) {\n    jobSearch.style.display = \"\";\n    if (jobSearch.contains(dashboard)) {\n      let child = dashboard;\n      while (child.parentElement && child.parentElement !== jobSearch) {\n        child = child.parentElement;\n      }\n      for (const sibling of jobSearch.children) {\n        if (sibling === child) continue;\n        if (!gwSearchHiddenBranches.has(sibling))\n          gwSearchHiddenBranches.set(sibling, sibling.style.display);\n        sibling.style.display = \"none\";\n      }\n      \/\/ If the dashboard has intermediate wrappers, keep them visible.\n      let parent = dashboard.parentElement;\n      while (parent && parent !== jobSearch) {\n        parent.style.display = \"\";\n        parent = parent.parentElement;\n      }\n    } else {\n      jobSearch.style.display = \"none\";\n    }\n  } else {\n    for (const [element, oldDisplay] of gwSearchHiddenBranches)\n      element.style.display = oldDisplay;\n    gwSearchHiddenBranches.clear();\n  }\n}\nfunction gwShowJobBoard() {\n  if (gwScheduleReturn && !logout.hidden) {\n    gwRestoreActionSections(); gwDetailOpen = false; gwDetailView.hidden = true; dashboard.hidden = true; gwShowDashboardBranch(false);\n    gwScheduleReturn = false; gwScheduleOpen(false); return;\n  }\n  gwRestoreActionSections();\n  gwDetailOpen = false;\n  jobResult.textContent = \"\";\n  gwDetailView.hidden = true;\n  dashboard.hidden = true;\n  gwShowDashboardBranch(false);\n  jobSearch.style.display = gwMonthMode ? \"none\" : \"\";\n  monthlyJobPanel.style.display = \"\";\n  void loadMonthlyJobIds();\n}\nfunction gwRE173Dashboard(){if(photoUploadBusy||drawingUploadBusy)return;gwScheduleDashboard();}\ngwDetailBack.addEventListener(\"click\", gwRE173Dashboard);\n\nlet gwDetailIndicatorSeq = 0;\nasync function gwRefreshDetailIndicators(id) {\n  const seq = ++gwDetailIndicatorSeq;\n  const set = (key,state,label) => {\n    const b = gwDetailButtons[key];\n    b.dataset.state = state;\n    gwRE3Label(b.querySelector(\"small\"),label);\n    b.querySelector(\".gw-field-mark\").textContent = state === \"done\" ? \"\u2713\" : state === \"alert\" ? \"!\" : state === \"empty\" ? \"\u25cb\" : \"\";\n  };\n  for (const key of Object.keys(gwDetailButtons)) if(key!==\"additional\") set(key,\"loading\",\"Checking\u2026\");\n  if (!id || !client) return;\n  const results = await Promise.allSettled([\n    Promise.all([client.from(\"final_measurements\").select(\"id\",{count:\"exact\",head:true}).eq(\"job_id\",id),client.from(\"gw_final_measurement_versions\").select(\"version_id\",{count:\"exact\",head:true}).eq(\"job_id\",id).eq(\"measurement_status\",\"Completed\")]).then(rs=>({count:rs.some(r=>r.count>0)?1:rs.every(r=>!r.error)?0:null,error:rs.every(r=>r.error)?rs[0].error:null})),\n    ...[\"Before\",\"After\",\"Problem\"].map(type=>client.from(\"job_photo\").select(\"id\",{count:\"exact\",head:true}).eq(\"job_id\",id).eq(\"photo_type\",type)),\n    client.from(\"job_problems\").select(\"id\",{count:\"exact\",head:true}).eq(\"job_id\",id),\n    client.from(\"job_problems\").select(\"id\",{count:\"exact\",head:true}).eq(\"job_id\",id).neq(\"status\",\"Resolved\")\n  ]);\n  if(seq!==gwDetailIndicatorSeq || id!==gwDetailSelectedJobId || !gwDetailOpen || logout.hidden) return;\n  const counts=results.map(r=>r.status===\"fulfilled\"&&!r.value.error&&typeof r.value.count===\"number\"?r.value.count:null);\n  const [m,b,a,p,total,open]=counts;\n  const photos=n=>n===null?\"Photo count unavailable\":n+ (n===1?\" Photo\":\" Photos\");\n  set(\"measurement\",m===null?\"unknown\":m?\"done\":\"empty\",m===null?\"Status unavailable\":m?\"Completed\":\"Not completed\");\n  for(const [key,n] of [[\"before\",b],[\"after\",a]]) set(key,n===null?\"unknown\":n?\"done\":\"empty\",photos(n));\n  const issueState=open===null||total===null?\"unknown\":open?\"alert\":total?\"done\":\"empty\";\n  set(\"issue\",issueState,photos(p)+\" \u00b7 \"+(issueState===\"unknown\"?\"Status unavailable\":open?\"Issue\":total?\"Solved\":\"No Issue\"));\n}\n\nfunction gwV5Status(job, code, oldStatus) {\n  const id=job.job_id, row=document.createElement(\"div\"); row.className=\"gw-v5-status\";\n  const msg=document.createElement(\"div\"); msg.setAttribute(\"role\",\"status\"); msg.className=\"gw-v5-message\";\n  const make=(name,values)=>{const el=document.createElement(\"select\"); el.className=\"gw-v5-\"+name; el.setAttribute(\"aria-label\",name===\"job\"?\"Job Status\":\"Issue Status\"); for(const value of values) el.add(new Option(value,value)); el.disabled=true; return el;};\n  const js=make(\"job\",[\"In Process\",\"Fabricated\",\"Completed\"]), issue=make(\"issue\",[\"No Issue\",\"Issue\",\"On Hold\",\"Solved\"]);\n  row.append(js,issue,msg); code.append(row);\n  row.gw81={js,issue,msg,oldStatus};\n\n}\n\n\/\/ Revision 8: independent production workflow and append-only notes.\nlet gw8Context=null;\nfunction gw8Role(id,role){if(gw8Context?.id===id){gw8Context.role=role;gw8Context.render();gw107Preview(id);}}\n\/\/ Optional notes preview: no startup DOM or observers; never blocks authentication.\nfunction gw107Preview(id){\n const ctx=gw8Context;\n if(!ctx||ctx.id!==id||logout.hidden||!gwDetailOpen||gwDetailSelectedJobId!==id)return;\n const host=gwDetailInfo;\n host.querySelector('[data-gw-priority-notes]')?.remove();\n host.querySelector('[data-gw-quick-add-note]')?.remove();\n const panel=document.createElement('div');panel.dataset.gwPriorityNotes='1';host.append(panel);\n const toolbar=document.createElement('div');toolbar.style.cssText='display:flex;gap:8px;align-items:center;flex-wrap:wrap;margin:8px 0;';\n const heading=document.createElement('strong');gwRE3Label(heading,'Important Job Notes');\n const add=document.createElement('button');add.type='button';add.dataset.gwQuickAddNote='1';gwRE3Label(add,'Add Note');add.style.cssText='width:auto!important;min-width:0!important;flex:0 0 auto!important;display:inline-flex!important;align-items:center;justify-content:center;padding:4px 0!important;min-height:44px!important;height:auto!important;margin:0!important;font-size:14px!important;font-weight:600!important;border-radius:0!important;box-sizing:border-box;';add.disabled=!['owner','office','project_manager','installer','fabricator'].includes(ctx.role);toolbar.append(heading);panel.append(toolbar);(host.querySelector(\".gw-field-contact\")||toolbar).append(add);\n const editor=document.createElement('div');editor.hidden=true;editor.style.display='none';\n const input=document.createElement('textarea');input.rows=3;input.maxLength=10000;input.placeholder='Enter job note\u2026';input.style.cssText='width:100%;box-sizing:border-box;';\n const save=document.createElement('button');save.type='button';save.textContent='Save Note';const cancel=document.createElement('button');cancel.type='button';cancel.textContent='Cancel';const message=document.createElement('div');message.setAttribute('role','status');const actions=document.createElement('div');actions.style.cssText='display:flex;gap:8px;justify-content:flex-end;align-items:center;margin:6px 0;';for(const button of [save,cancel])button.style.cssText='width:auto!important;min-width:0!important;flex:0 0 auto!important;display:inline-flex!important;align-items:center;justify-content:center;padding:6px 12px!important;min-height:34px!important;height:auto!important;margin:0!important;font-size:13px!important;';actions.append(save,cancel);editor.append(input,actions,message);panel.append(editor);\n add.onclick=()=>{editor.hidden=false;editor.style.display='block';input.focus();};cancel.onclick=()=>{editor.hidden=true;editor.style.display='none';};\n save.onclick=async()=>{if(save.disabled||!current()||!input.value.trim())return;save.disabled=cancel.disabled=input.disabled=true;try{const {error}=await client.rpc('gw_add_job_note',{p_job_id:id,p_body:input.value.trim()});if(error)throw error;if(current()){input.value='';gw107Preview(id);void gw107BoardNotes(monthlyJobLoadSeq);}}catch(e){if(current())message.textContent=e.message||'Unable to save note.';}finally{save.disabled=cancel.disabled=input.disabled=false;}};\n const empty=document.createElement('div');empty.textContent='Loading job notes\u2026';panel.append(empty);\n const current=()=>panel.isConnected&&gw8Context===ctx&&!logout.hidden&&gwDetailOpen&&gwDetailSelectedJobId===id;\n const tables=[['gw_job_notes','Important Job Notes',false]];\n if(['owner','office'].includes(ctx.role))tables.push(['gw_job_private_notes','Confidential Office \/ Owner Notes',true]);\n for(const [table,title,isPrivate] of tables){\n  Promise.resolve().then(async()=>{\n   let query=client.from(table).select('body,author_name,created_at').eq('job_id',id);\n   if(!isPrivate)query=query.eq('note_source','manual');\n   const {data,error}=await query.order('created_at',{ascending:false}).limit(3);\n   if(error)throw error;\n   if(!current()||(isPrivate&&!['owner','office'].includes(ctx.role)))return; if(!isPrivate){empty.textContent=data?.length?'':'No job notes yet.';} if(!data?.length)return;\n   const box=document.createElement('section');box.style.cssText='margin:10px 0;padding:12px;border:2px solid #e3b341;border-radius:9px;background:'+(isPrivate?'#fff0dc':'#fff6ce')+';color:#513b13;overflow-wrap:anywhere;';\n   const h=document.createElement('strong');if(isPrivate)h.textContent=title;else gwRE3Label(h,title);box.append(h);const noteScroll=document.createElement('div');noteScroll.style.cssText='max-height:200px;overflow-y:auto;overflow-x:hidden;overscroll-behavior-y:contain;';box.append(noteScroll);\n   for(const n of data){const row=document.createElement('div');row.style.cssText='border-top:1px solid #dfc880;margin-top:8px;padding-top:8px;white-space:pre-wrap;overflow-wrap:anywhere;';if(isPrivate)row.textContent=n.body||'';else gwRE3Optional(row,n.body);const meta=document.createElement('small');meta.style.display='block';meta.textContent=(n.author_name||'')+' \u00b7 '+new Date(n.created_at).toLocaleString('en-US',{timeZone:'America\/Chicago'});row.append(meta);noteScroll.append(row);}\n\n   panel.append(box);\n  }).catch(e=>{if(current()&&!isPrivate)empty.textContent='Unable to load job notes.';console.warn('GW optional notes preview:',e);});\n }\n}\nfunction gw107BoardNotes(seq){\n Promise.resolve().then(()=>gwBoardAll('gw_job_notes','job_id','id',false,'manual')).then(rows=>{\n  if(logout.hidden||seq!==monthlyJobLoadSeq)return;\n  const ids=new Set(rows.map(r=>r.job_id));\n  for(const card of monthlyJobList.querySelectorAll('[data-gw-note-job]')){\n   if(!ids.has(card.dataset.gwNoteJob)){card.querySelector('[data-gw-note-marker]')?.remove();const code=card.querySelector('.gw-job-code');if(code)code.setAttribute('aria-label',(code.getAttribute('aria-label')||'').replace(\/, job notes available\/g,''));continue;}\n   if(card.querySelector('[data-gw-note-marker]'))continue;\n   const mark=document.createElement('span');mark.dataset.gwNoteMarker='1';mark.textContent='N';mark.title='Important Job Notes available';mark.style.cssText='position:absolute;top:-5px;left:-5px;background:#ffdf72;color:#513b13;border:1px solid #d5a52c;border-radius:50%;font-weight:800;font-size:11px;width:19px;height:19px;line-height:17px;text-align:center;pointer-events:none;';card.append(mark);\n   const code=card.querySelector('.gw-job-code');if(code)code.setAttribute('aria-label',code.getAttribute('aria-label')+', job notes available');\n  }\n }).catch(e=>console.warn('GW optional board notes:',e));\n}\nfunction gw8Detail(job){\n const id=job.job_id, completed=!!job.completed_at||job.job_status===\"Completed\";\n const panel=document.createElement(\"section\");panel.style.cssText=\"margin-top:12px;padding:10px;border:1px solid #d7e2ea;border-radius:10px;background:white;font-size:14px;\";\n gwDetailInfo.append(panel);\n const ctx={id,role:null,workflow:null,notes:[],noteCount:null,busy:false,expanded:false,adding:false,holding:false,reports:[],render};gw8Context=ctx;\n const current=()=>gw8Context===ctx&&panel.isConnected&&gwDetailSelectedJobId===id&&!logout.hidden;\n const selects=gwDetailInfo.querySelector(\".gw-v5-status\").gw81; const {js,issue}=selects; let done=completed;\n const status=document.createElement(\"div\"), controls=document.createElement(\"div\"), noteList=document.createElement(\"div\"), msg=document.createElement(\"div\");\n msg.setAttribute(\"role\",\"status\");msg.style.color=\"#9b341b\";\n const button=(label,fn)=>{const b=document.createElement(\"button\");b.type=\"button\";b.textContent=label;b.style.cssText=\"margin:4px 4px 4px 0;padding:7px 10px;min-height:34px;\";b.onclick=fn;return b;};\n const reason=document.createElement(\"textarea\");reason.placeholder=\"Reason for On Hold\";reason.rows=2;reason.maxLength=9000;reason.style.width=\"100%\";\n const holdSave=button(\"Confirm On Hold\",()=>{if(reason.value.trim()){ctx.holding=false;action(\"hold\",reason.value.trim());}});\n const holdCancel=button(\"Cancel\",()=>{ctx.holding=false;render();});\n controls.append(reason,holdSave,holdCancel);panel.append(status,controls,msg);\n js.onchange=()=>{const next=js.value;render();if(next===\"Fabricated\")action(\"fabricated\");else if(next===\"In Process\")action(\"reset_fabricated\");else if(next===\"Completed\"&&confirm(\"Complete \"+id+\"? This sets the invoice due date in 30 days and cannot be undone.\"))run(async()=>{if(ctx.workflow.on_hold)throw Error(\"Release hold before completing this job.\");const {error}=await client.rpc(\"gw_mark_job_completed\",{p_job_id:id});if(error)throw error;done=true;selects.oldStatus.textContent=\"Completed\";});};\n issue.onchange=()=>{const next=issue.value;const w=ctx.workflow;const open=ctx.reports.filter(r=>r.status!==\"Resolved\");render();if(next===\"On Hold\"){ctx.holding=true;reason.value=w.hold_reason||\"\";render();return;}if(w.on_hold){if(!confirm(\"Release hold? Existing issues will be preserved.\"))return;action(\"release_hold\");return;}if(next===\"Issue\"){const description=prompt(\"Describe the issue:\");if(!description?.trim())return;run(async()=>{const {data:auth,error:a}=await client.auth.getUser();if(a||!auth.user)throw Error(\"Please log in again.\");const {error}=await client.from(\"job_problems\").insert({job_id:id,issue_type:\"Other\",description:description.trim(),created_by:auth.user.id});if(error)throw error;});}else if(next===\"Solved\"&&open.length&&confirm(\"Resolve all open issues?\")){run(async()=>{for(const r of open){const {error}=await client.rpc(\"gw_resolve_job_problem\",{p_problem_id:r.id,p_resolution_notes:null});if(error)throw error;}});}else if(next===\"No Issue\"&&ctx.reports.length)msg.textContent=\"Issue history is preserved. Select Solved.\";};\n async function load(){const [w,r]=await Promise.all([client.from(\"gw_job_workflow\").select(\"*\").eq(\"job_id\",id).maybeSingle(),client.from(\"job_problems\").select(\"id,status\").eq(\"job_id\",id)]);if(r.error)throw r.error;if(w.error)throw w.error;if(!current())return;ctx.workflow=w.data||{};ctx.reports=r.data||[];render();void gwRefreshDetailIndicators(id);}\n\n async function run(fn){if(!current()||ctx.busy)return;ctx.busy=true;msg.textContent=\"\";render();try{await fn();await load();}catch(e){if(current())msg.textContent=e.message||String(e);}finally{ctx.busy=false;if(current())render();}}\n function action(a,reason=null){return run(async()=>{const {error}=await client.rpc(\"gw_set_job_workflow\",{p_job_id:id,p_action:a,p_reason:reason});if(error)throw error;});}\n function render(){if(!current())return;const w=ctx.workflow;const manager=[\"owner\",\"office\",\"project_manager\"].includes(ctx.role);const fab=manager||ctx.role===\"fabricator\";const active=[\"owner\",\"office\",\"project_manager\",\"fabricator\",\"installer\"].includes(ctx.role);status.textContent=w?(w.on_hold?\"On Hold \u2014 \"+(w.hold_reason||\"\"):\"\"):\"Loading workflow\u2026\";status.style.fontWeight=\"700\";\n js.value=done?\"Completed\":w?.fabricated?\"Fabricated\":\"In Process\";\n issue.value=w?.on_hold?\"On Hold\":ctx.reports.some(r=>r.status!==\"Resolved\")?\"Issue\":ctx.reports.length?\"Solved\":\"No Issue\";\n js.disabled=!w||ctx.busy||done||!fab;issue.disabled=!w||ctx.busy||!active||(w.on_hold&&!manager);\n for(const o of js.options)o.disabled=o.value===\"Completed\"?(!manager||!!w?.on_hold):o.value===\"In Process\"?!manager:false;\n for(const o of issue.options)o.disabled=o.value===\"On Hold\"?(!manager||done):false;\n controls.hidden=!ctx.holding;controls.style.display=ctx.holding?\"\":\"none\";reason.disabled=holdSave.disabled=holdCancel.disabled=ctx.busy;\n panel.style.display=ctx.holding||!w||w.on_hold||msg.textContent?\"\":\"none\";}\n\n \/\/ Load older notes without resetting the current page.\n render();load().catch(e=>{if(current()){msg.textContent=e.message||String(e);render();}});\n}\nfunction gwOpenFocusedDetail(job) {\n  if (!gwSchedulePanel.hidden) { gwScheduleClose(); gwScheduleReturn = true; } else { gwScheduleReturn = false; }\n  gwRestoreActionSections();\n  gwDetailOpen = true;\n  gwDetailSelectedJobId = job.job_id;\n  gwDetailInfo.replaceChildren();\n  const code = document.createElement(\"div\");\n  code.className = \"gw-field-code\";\n  gwFieldTitle.textContent=job.job_id;\n  const customer = document.createElement(\"div\");\n  customer.className = \"gw-field-customer\";\n  customer.textContent = job.customer_name || \"Customer not entered\";\n  const address = document.createElement(\"div\");\n  address.className = \"gw-field-address\";\n  address.textContent = job.job_address || \"Address not entered\";\n  const contact = document.createElement(\"div\");\n  contact.className = \"gw-field-contact\";\n  if (job.customer_phone) {\n    const phone = document.createElement(\"a\");\n    phone.href = \"tel:\" + String(job.customer_phone).replace(\/[^+0-9]\/g,\"\");\n    gwRE3Label(phone,\"\u260e Call\");\n    contact.appendChild(phone);\n  }\n  if (job.job_address) {\n    const map = document.createElement(\"a\");\n    map.href = \"https:\/\/www.google.com\/maps\/search\/?api=1&query=\" + encodeURIComponent(job.job_address);\n    map.target = \"_blank\";\n    map.rel = \"noopener noreferrer\";\n    gwRE3Label(map,\"Map\");\n    contact.appendChild(map);\n    const copy = document.createElement(\"button\");\n    copy.type = \"button\";\n    copy.className = \"gw-copy-address\";\n    gwRE3Label(copy,\"Copy Address\");\n    copy.dataset.gwCopyAddress = String(job.job_address);\n    contact.appendChild(copy);\n  }\n  const status=document.createElement(\"span\");\n  status.textContent=job.job_status || \"\";\n  status.style.cssText=\"font-size:12px;font-weight:600;margin-left:8px;color:#526a79;\";\n  code.appendChild(status);\n  gwV5Status(job, code, status);\n  gwDetailInfo.append(code,customer,address,contact);\n  gw8Detail(job);\n  gw107Preview(job.job_id);\n  gwDetailInfo.classList.add(\"gw-job-info-header\");\n  gwShowDashboardBranch(false);\n  gwDetailView.hidden = false;\n  void gwRefreshDetailIndicators(gwDetailSelectedJobId);\n  jobSearch.style.display = \"none\";\n  monthlyJobPanel.style.display = \"none\";\n  dashboard.hidden = true;\n  gwDetailView.scrollIntoView({block:\"start\",behavior:\"smooth\"});\n}\nfunction gwOpenDetailAction(type) {\n  if (!gwDetailOpen || !gwDetailSelectedJobId) return;\n  if (jobIdInput.value.trim() !== gwDetailSelectedJobId ||\n      currentWorkJobId !== gwDetailSelectedJobId) {\n    alert(\"Job details are still loading. Please try again in a moment.\");\n    return;\n  }\n\n  if(type === \"additional\") { if(photoUploadBusy||drawingUploadBusy)return;gwOpenAdditionalWork(gwDetailSelectedJobId); return; }\n  const measureToggle = document.getElementById(\"gw-final-measurement\");\n  const measurePanel = document.getElementById(\"gw-measurement-dashboard\");\n  const measureForm = document.getElementById(\"gw-measurement-form\");\n  const photoToggle = document.getElementById(\"gw-job-photos\");\n  const photoForm = document.getElementById(\"gw-photo-form\");\n  const photoType = document.getElementById(\"gw-photo-type\");\n  const issueToggle = document.getElementById(\"gw-problem-toggle\");\n  const issuePanel = document.getElementById(\"gw-problem-panel\");\n\n  if (photoUploadBusy || drawingUploadBusy) return;\n  const isMeasurement = type === \"measurement\";\n  if (!isMeasurement) gw92ClearNotes();\n  const isIssue = false; \/\/ Issue Photo uses Job Photos with Problem \/ Damage category\n  const target = isMeasurement ? measureToggle : isIssue ? issueToggle : photoToggle;\n  if (!target || target.hidden) {\n    alert(\"This action is not available for your account.\");\n    return;\n  }\n\n  gwDetailView.hidden = true;\n  dashboard.hidden = false;\n  gwShowDashboardBranch(true);\n  monthlyJobPanel.style.display = \"none\";\n\n  \/\/ Keep the original forms and their existing save\/permission handlers.\n  \/\/ Only the chosen action is visible on this focused screen.\n  if (isMeasurement) {\n    if (measurePanel && measurePanel.hidden) measureToggle.click();\n    const edit = document.getElementById(\"gw-edit-measurement\");\n    if (measureForm) measureForm.hidden = true;\n  } else if (isIssue) {\n    if (issuePanel && issuePanel.hidden) issueToggle.click();\n  } else {\n    if (photoForm && photoForm.hidden) photoToggle.click();\n    if (photoType) {\n      const desired = type === \"before\" ? \"Before\" : type === \"after\" ? \"After\" : type === \"measurementPhoto\" ? \"Measurement\" : \"Problem\";\n      const option = Array.from(photoType.options).find(o =>\n        o.value.toLowerCase() === desired.toLowerCase() ||\n        o.textContent.trim().toLowerCase() === desired.toLowerCase());\n      if (option) {\n        photoType.value = option.value;\n        photoType.disabled = true;\n        photoType.dispatchEvent(new Event(\"change\", {bubbles:true}));\n      }\n    }\n  }\n\n  const chosen = isMeasurement\n    ? (!measureForm?.hidden ? measureForm : measurePanel)\n    : isIssue ? issuePanel : photoForm;\n  \/\/ A scoped container prevents other job sections from appearing.\n  gwActionHeader.append(gwSharedJobTop,gwDetailActions,gwDetailInfo);\n  if(!isMeasurement)gwAdditionalDetails.open=false;\n  gwActionHeader.hidden = false;\n  const sections = Array.from(dashboard.children);\n  for (const element of sections) {\n    if (element === gwDetailReturn || element === gwActionHeader || element === gwDashboardReturn || element === gwNavRow) continue;\n    \/\/ Don't hide ancestor containers of the selected form.\n    if (chosen && (element === chosen || element.contains(chosen) || (isMeasurement && (element === measureForm || element.contains(measureForm))))) {\n      element.style.display = \"\";\n    } else {\n      if (!gwActionDisplayBackup.has(element))\n        gwActionDisplayBackup.set(element, element.style.display);\n      element.style.display = \"none\";\n    }\n  }\n  if (!isMeasurement && !isIssue) {\n    const editor = document.getElementById(\"gw-photo-editor\");\n    const add = document.getElementById(\"gw-gallery-add\");\n    const cancel = document.getElementById(\"gw-gallery-cancel\");\n    const heading = document.getElementById(\"gw-category-heading\");\n    heading.textContent = type === \"before\" ? \"Before Photos\" : type === \"after\" ? \"After Photos\" : type === \"measurementPhoto\" ? \"Measurement Photos\" : \"Issue Photos\";\n    editor.hidden = true; add.hidden = false; cancel.hidden = false;\n    document.getElementById(\"gw-gallery-first\").append(photoGallery);\n    document.getElementById(\"gw-gallery-heading\").hidden = true;\n    viewPhotos.hidden = true;\n    photoType.hidden = true;\n    document.querySelector('label[for=\"gw-photo-type\"]').hidden = true;\n    add.onclick = () => { editor.hidden = false; };\n    cancel.onclick = () => { if (!photoUploadBusy) { clearPendingPhotos(); editor.hidden = true; } };\n    resetPhotoView(); viewPhotos.click();\n  }\n  if (isMeasurement) {gw92OpenNotes(gwDetailSelectedJobId);if(gw10Editor.hidden)gwRE173MeasureDrop.open=false;}\n  if(!isMeasurement){drawingPanel.hidden=true;drawingToggle.setAttribute(\"aria-expanded\",\"false\");gwRE173DrawingMode(false);}\n  if (chosen) gwSharedJobTop.scrollIntoView({block:\"start\",behavior:\"smooth\"});\n}\nconst gwActionHeader = document.createElement(\"div\");\ngwActionHeader.hidden = true;\ngwActionHeader.id=\"gw-re173-action-header\";\ndashboard.prepend(gwActionHeader);\nconst gwActionDisplayBackup = new Map();\nfunction gwRestoreActionSections() {\n  gwDetailView.append(gwSharedJobTop,gwDetailActions,gwDetailInfo);\n  gwAdditionalDetails.open=false;\n  gwActionHeader.hidden = true;\n  gw92ClearNotes();\n  const category=document.getElementById(\"gw-photo-type\");\n  if(category) category.disabled=false;\n  for (const [element, display] of gwActionDisplayBackup)\n    element.style.display = display;\n  gwActionDisplayBackup.clear();\n}\n\n\nfunction gwOpenAdditionalWork(jobId) {\n  const panel=document.createElement('section');panel.dataset.gwRe3Additional='1';\n  panel.style.cssText='position:fixed;inset:0;z-index:2147483000;background:white;color:#17435f;overflow:auto;padding:16px;box-sizing:border-box';\n  const root=qEl('div','',panel);root.style.cssText='max-width:760px;margin:auto';document.body.append(panel);\n  let busy=false,nextLocation=1;\n  const status=qEl('p','',root);status.setAttribute('role','status');\n  function button(parent,label,fn){const b=qEl('button',label,parent);b.type='button';b.style.cssText='margin:5px 5px 5px 0;padding:10px;white-space:normal';b.onclick=async()=>{if(busy)return;busy=true;b.disabled=true;try{await fn();}catch(e){status.textContent=e.message||String(e);}finally{busy=false;b.disabled=false;}};return b;}\n  function check(r){if(r.error)throw r.error;return r.data;}\n  const urls=new Set();\n  button(root,'\u2190 Job Details',()=>{for(const url of urls)window.URL.revokeObjectURL(url);if(gwAdditionalReturnParent)gwAdditionalReturnParent.insertBefore(gwDetailInfo,gwAdditionalReturnNext?.parentNode===gwAdditionalReturnParent?gwAdditionalReturnNext:null);panel.remove();});\n  const gwAdditionalReturnParent=gwDetailInfo.parentNode;\n  const gwAdditionalReturnNext=gwDetailInfo.nextSibling;\n  root.append(gwDetailInfo);\n  const workHeading=qEl('h2','',root);gwRE3Label(qEl('span','',workHeading),'Additional Work');workHeading.append(document.createTextNode(' \u2014 '+jobId));\n  const cards=qEl('div','',root);\n  const add=button(root,'+ Add Location',()=>makeCard('Location '+nextLocation++,[]));add.disabled=true;\n  async function record(location,note){return check(await client.from('gw_job_additional_work').insert({job_id:jobId,work_location:location,work_category:'Other',problem_found:'',work_performed:note,check_result:''}).select('id,created_at,work_performed,work_location').single());}\n  function makeCard(location,rows){\n    const card=qEl('article','',cards);card.style.cssText='border:1px solid #cbd5e1;border-radius:12px;padding:12px;margin:12px 0';qEl('h3',location,card);\n    const notes=qEl('div','',card),photos=qEl('div','',card);let anchor=rows[0]?.id;\n    function showNote(r){const s=[r.problem_found,r.work_performed,r.check_result].filter(Boolean).join('\\n');if(!s)return;const p=qEl('p',s,notes);p.style.whiteSpace='pre-wrap';gwRE3Optional(p,s);qEl('small',new Date(r.created_at).toLocaleString(),notes);}\n    rows.forEach(showNote);\n    photos.style.cssText='display:grid;grid-template-columns:repeat(auto-fill,minmax(96px,1fr));gap:8px;margin:8px 0';\n    function showPhoto(p){\n      const row=qEl('div','',photos);row.style.cssText='min-width:0;overflow-wrap:anywhere';\n      const label=p.description||'Additional Work photo';\n      const thumb=button(row,'',async()=>{const signed=check(await client.storage.from('job-photos').createSignedUrl(p.photo_url,300));openPhotoZoom(signed.signedUrl,label,thumb);});\n      thumb.style.cssText='display:block;width:100%;padding:0;margin:0;overflow:hidden;border:1px solid #cbd5e1;border-radius:8px;background:#f1f5f9;color:#334155';thumb.setAttribute('aria-label','View '+label);\n      const img=qEl('img','',thumb);img.alt=label;img.loading='eager';img.style.cssText='display:block;width:100%;height:100px;object-fit:cover';\n      const fallback=qEl('span','Loading photo\u2026',thumb);fallback.style.cssText='display:block;padding:8px;font-size:12px';\n      const timer=setTimeout(()=>{if(fallback.textContent==='Loading photo\u2026')fallback.textContent='Photo slow to load \u2014 tap to open';},15000);\n      img.onload=()=>{clearTimeout(timer);img.hidden=false;img.style.display='block';fallback.hidden=true;fallback.style.display='none';};\n      img.onerror=()=>{clearTimeout(timer);img.style.display='none';fallback.hidden=false;fallback.style.display='block';fallback.textContent='Preview unavailable \u2014 tap to open';};\n      if(p.description)gwRE3Optional(qEl('small',p.description,row),p.description);\n      (async()=>{const signed=check(await client.storage.from('job-photos').createSignedUrl(p.photo_url,300));if(!signed?.signedUrl)throw Error('No photo URL returned');img.src=signed.signedUrl;})().catch(e=>{clearTimeout(timer);img.style.display='none';fallback.textContent='Photo unavailable \u2014 tap to retry';fallback.title=e.message||String(e);});\n    }\n    qEl('label','Add Note',card).style.display='block';const note=qEl('textarea','',card);note.rows=3;note.dataset.gwRe3Placeholder='Write the location and work details...';note.placeholder=gwRE3Text(note.dataset.gwRe3Placeholder);note.style.cssText='width:100%;box-sizing:border-box';\n    button(card,'Save Note',async()=>{const value=note.value.trim();if(!value)throw Error('Enter a note first.');const r=await record(location,value);if(!anchor)anchor=r.id;showNote(r);note.value='';status.textContent='Note saved.';});\n    const editor=qEl('div','',card);editor.hidden=true;\n    button(card,'Add Photo',()=>{editor.hidden=!editor.hidden;});\n    const input=qEl('input','',editor);input.type='file';input.accept='image\/*';input.hidden=true;\n    const preview=qEl('div','',editor);let pending=[];\n    function render(){preview.replaceChildren();for(const item of pending){const row=qEl('div','',preview);row.style.cssText='display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin:8px 0';const img=qEl('img','',row);img.src=item.url;img.alt=item.file.name;img.style.cssText='width:80px;height:80px;object-fit:cover';qEl('span',item.file.name,row);const d=qEl('input','',row);d.dataset.gwRe3Placeholder='Photo description (optional)';d.placeholder=gwRE3Text(d.dataset.gwRe3Placeholder);d.value=item.desc;d.oninput=()=>item.desc=d.value;button(row,'Remove',()=>{pending=pending.filter(x=>x!==item);window.URL.revokeObjectURL(item.url);urls.delete(item.url);render();});}}\n    input.onchange=()=>{try{for(const file of Array.from(input.files||[])){const url=window.URL.createObjectURL(file);urls.add(url);pending.push({file,url,desc:'',path:null});}render();progress.textContent=pending.length+' photo(s) selected. Tap Upload Photos to save.';}catch(e){progress.textContent='Photo selection failed: '+(e.message||String(e));}finally{input.value='';}};\n    button(editor,'Take Photo',()=>{input.multiple=false;input.setAttribute('capture','environment');input.click();});\n    button(editor,'Select Photos',()=>{input.multiple=true;input.removeAttribute('capture');input.click();});\n    const progress=qEl('p','',editor);progress.setAttribute('role','status');\n    button(editor,'Upload Photos',async()=>{if(!pending.length)throw Error('Select photos first.');const u=check(await client.auth.getUser()).user;if(!u)throw Error('Log in again.');const batch=pending.slice();const types={jpg:'image\/jpeg',jpeg:'image\/jpeg',png:'image\/png',webp:'image\/webp',heic:'image\/heic',heif:'image\/heif'};for(const item of batch){const f=item.file;const ext=f.name.split('.').pop().toLowerCase();if(!types[ext]||!f.size||f.size>20*1024*1024||(f.type&&f.type!==types[ext]))throw Error('Unsupported photo or over 20 MB: '+f.name);}\n      if(!anchor)anchor=(await record(location,'')).id;\n      let done=0;for(const item of batch){progress.textContent='Uploading '+(done+1)+' of '+batch.length;const f=item.file,ext=f.name.split('.').pop().toLowerCase();if(!item.path){const path=u.id+'\/'+jobId+'\/'+crypto.randomUUID()+'.'+ext;check(await client.storage.from('job-photos').upload(path,f,{contentType:types[ext],upsert:false}));item.path=path;}check(await client.from('job_photo').insert({job_id:jobId,additional_work_id:anchor,photo_type:'Additional Work',photo_url:item.path,description:item.desc.trim(),area:location,uploaded_by:u.email||u.id,taken_at:new Date().toISOString(),is_evidence:false}));showPhoto({photo_url:item.path,description:item.desc});pending=pending.filter(x=>x!==item);window.URL.revokeObjectURL(item.url);urls.delete(item.url);done++;render();}progress.textContent=done+' photo(s) saved.';status.textContent='Photos saved.';});\n    return {showPhoto};\n  }\n  (async()=>{const rows=check(await client.from('gw_job_additional_work').select('*').eq('job_id',jobId).order('id'));const groups=new Map();for(const r of rows){const m=\/^Location (\\d+)$\/.exec(r.work_location);if(m)nextLocation=Math.max(nextLocation,Number(m[1])+1);if(!groups.has(r.work_location))groups.set(r.work_location,[]);groups.get(r.work_location).push(r);}for(const [location,group] of groups){const view=makeCard(location,group);const photos=check(await client.from('job_photo').select('id,photo_url,description').eq('job_id',jobId).in('additional_work_id',group.map(r=>r.id)).order('id'));photos.forEach(view.showPhoto);}if(!groups.size)makeCard('Location '+nextLocation++,[]);add.disabled=false;})().catch(e=>status.textContent=e.message||String(e));\n}\n\nObject.entries(gwDetailButtons).forEach(([key,button]) =>\n  button.addEventListener(\"click\",()=>gwOpenDetailAction(key)));\ngwQuickCamera.addEventListener(\"click\",()=>gwOpenDetailAction(\"before\"));\n\nconst gwDetailReturn = document.createElement(\"button\");\ngwDetailReturn.type = \"button\";\ngwDetailReturn.textContent = \"\u2190 Job Details\";\ngwDetailReturn.style.cssText = \"width:auto;padding:7px 12px;margin-bottom:12px;\";\ndashboard.insertBefore(gwDetailReturn,dashboard.firstChild);\nconst gwDashboardReturn = document.createElement(\"button\");\ngwDashboardReturn.type = \"button\";\ngwDashboardReturn.textContent = \"Back to Dashboard\";\ngwDashboardReturn.classList.add(\"gw-re173-back\");\nfunction gwRE173BackLabels(){const label=gwSW()[3];gwDetailBack.textContent=label;gwDashboardReturn.textContent=label;}\nwindow.addEventListener(\"gw-language-changed\",gwRE173BackLabels);\ngwDashboardReturn.addEventListener(\"click\", gwRE173Dashboard);\ngwDetailReturn.hidden=true;\ngwDetailReturn.insertAdjacentElement(\"afterend\", gwDashboardReturn);\nconst gwNavRow = document.createElement(\"div\");\ngwNavRow.className = \"gw-action-row gw-re174-old-nav\";\ndashboard.prepend(gwNavRow); gwNavRow.append(gwDetailReturn,gwDashboardReturn);\ngwDetailReturn.addEventListener(\"click\",()=>{\n  gwRestoreActionSections();\n  dashboard.hidden = true;\n  gwShowDashboardBranch(false);\n  jobSearch.style.display = \"none\";\n  gwDetailView.hidden = false;\n  gw107Preview(gwDetailSelectedJobId);\n  void gwRefreshDetailIndicators(gwDetailSelectedJobId);\n  gwDetailView.scrollIntoView({block:\"start\",behavior:\"smooth\"});\n});\nlet monthlyJobCount = null;\nlet monthlyJobLoadSeq = 0;\nconst monthlyJobWords = {\n  en:[\"In Process\",\"Recently Completed\",\"Loading jobs...\",\"Unable to load jobs.\",\"No jobs\",\"Address not entered\"],\n  zh:[\"\u9032\u884c\u4e2d\",\"\u6700\u8fd1\u5b8c\u6210\",\"\u8f09\u5165\u5de5\u7a0b\u4e2d...\",\"\u7121\u6cd5\u8f09\u5165\u5de5\u7a0b\u3002\",\"\u6c92\u6709\u5de5\u7a0b\",\"\u5c1a\u672a\u8f38\u5165\u5730\u5740\"],\n  es:[\"En proceso\",\"Completados recientemente\",\"Cargando trabajos...\",\"No se pudieron cargar los trabajos.\",\"Sin trabajos\",\"Direcci\u00f3n pendiente\"]\n};\nfunction monthlyWords(){return monthlyJobWords[getGwPortalLanguage()] || monthlyJobWords.en;}\nfunction updateMonthlyJobTitle(){ \/* board headings are rebuilt with translated text *\/ }\nfunction setMonthlyJobExpanded(open){monthlyJobList.hidden = !open;}\nfunction gwBoardSection(title, rows, words){\n  const section = document.createElement(\"section\");\n  const heading = document.createElement(\"h3\");\n  heading.className = \"gw-board-heading\";\n  heading.textContent = title + \" (\" + rows.length + \")\";\n  const grid = document.createElement(\"div\");\n  grid.className = \"gw-board-grid\";\n  if (!rows.length) grid.textContent = words[4];\n  const toggle=document.createElement(\"button\");toggle.type=\"button\";toggle.textContent=heading.textContent;toggle.style.cssText=\"width:100%;text-align:left;background:transparent;color:inherit;border:0;padding:4px;\";toggle.setAttribute(\"aria-expanded\",\"true\");heading.replaceChildren(toggle);toggle.onclick=()=>{grid.hidden=!grid.hidden;grid.style.display=grid.hidden?\"none\":\"\";toggle.setAttribute(\"aria-expanded\",String(!grid.hidden));};\n  section.append(heading,grid);\n  const kind=title===words[0]?'active':title===words[1]?'completed':title==='Fabricated \u2013 Ready to Install'?'ready':title==='On Hold'?'hold':title.startsWith('Monthly Jobs')?'monthly':'issues';\n  section.dataset.gwBoardKind=kind;\n  if(kind==='completed'||(kind==='issues'&&!rows.length)){grid.hidden=true;grid.style.display='none';toggle.setAttribute('aria-expanded','false');}\n  return {section,grid};\n}\nfunction gwBoardCard(row, flags, words){\n  const btn = document.createElement(\"div\");\n  btn.className = \"gw-job-icon\";\n  btn.dataset.gwNoteJob=row.job_id;\n  if(row.job_status===\"Completed\"||row.completed_at)btn.style.background=\"#e0f2e4\";\n  else if(row.gw8?.on_hold){btn.style.background=\"#fce3cf\";btn.style.borderBottom=\"3px solid \"+(row.gw8.fabricated?\"#d4a52b\":\"#8795a1\");btn.title=row.gw8.fabricated?\"Fabricated \u00b7 On Hold\":\"In Process \u00b7 On Hold\";}\n  else if(row.gw8?.fabricated)btn.style.background=\"#fff0cd\";\n  const code = document.createElement(\"button\");\n  code.type = \"button\";\n  code.className = \"gw-job-code\";\n  code.textContent = row.job_id;\n  if(row.gw8?.on_hold&&!row.completed_at&&row.job_status!==\"Completed\"){const tag=document.createElement(\"small\");tag.textContent=row.gw8.fabricated?\" \u00b7 F\":\" \u00b7 IP\";tag.title=row.gw8.fabricated?\"Fabricated\":\"In Process\";code.append(tag);}\n  const stars = document.createElement(\"span\");\n  stars.className = \"gw-job-stars\";\n  const indicatorLabels = {\n    en: [\"Final Measurement\", \"Before Photos\", \"After Photos\", \"Available\", \"Missing\"],\n    zh: [\"\u6700\u7d42\u91cf\u5ea6\", \"\u65bd\u5de5\u524d\u7167\u7247\", \"\u65bd\u5de5\u5f8c\u7167\u7247\", \"\u5df2\u6709\", \"\u672a\u6709\"],\n    es: [\"Medici\u00f3n final\", \"Fotos antes\", \"Fotos despu\u00e9s\", \"Disponible\", \"Falta\"]\n  }[getGwPortalLanguage()] || [\"Final Measurement\", \"Before Photos\", \"After Photos\", \"Available\", \"Missing\"];\n  const indicatorPaths = [\n    '<path d=\"M3 16 16 3l5 5L8 21Z\"\/><path d=\"m6 13 3 3m1-7 3 3m1-7 3 3\"\/>',\n    '<path d=\"M4 6h4l2-3h4l2 3h4a2 2 0 0 1 2 2v11a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2Z\"\/><circle cx=\"12\" cy=\"13\" r=\"4\"\/>',\n    '<rect x=\"3\" y=\"3\" width=\"18\" height=\"18\" rx=\"2\"\/><circle cx=\"8.5\" cy=\"8.5\" r=\"1.5\"\/><path d=\"m21 15-5-5L5 21\"\/>'\n  ];\n  [\"measure\", \"before\", \"after\"].forEach(function(key, i){\n    const indicator = document.createElement(\"span\");\n    indicator.style.cssText = \"display:inline-flex;align-items:center;justify-content:center;width:20px;height:20px;color:\" + (flags[key] ? \"#e3a500\" : \"#aeb7c1\");\n    const label = indicatorLabels[i] + \": \" + indicatorLabels[flags[key] ? 3 : 4];\n    indicator.title = label;\n    indicator.setAttribute(\"role\", \"img\");\n    indicator.setAttribute(\"aria-label\", label);\n    indicator.innerHTML = '<svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"20\" height=\"20\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\" focusable=\"false\">' + indicatorPaths[i] + '<\/svg>';\n    stars.appendChild(indicator);\n  });\n  const address = document.createElement(\"span\");\n  address.className = \"gw-job-address\";\n  address.textContent = String(row.job_address || \"\").trim().split(\",\")[0] || words[5];\n  btn.title = row.job_id + \"\\n\" + (String(row.job_address || \"\").trim() || words[5]) + \"\\n\" + (row.job_status || \"\");\n  code.setAttribute(\"aria-label\",\"Open job \" + row.job_id + \", \" + address.textContent);\n  btn.append(code,stars,address);\n  if(flags.problem){\n    const alert = document.createElement(\"span\");\n    alert.className = \"gw-job-alert\";\n    alert.textContent = \"!\";\n    alert.title = \"Unresolved job problem\";\n    btn.appendChild(alert);\n  }\n  code.addEventListener(\"click\",function(){\n    if(findJob.disabled) return;\n    jobIdInput.value = row.job_id;\n    findJob.click();\n  });\n  return btn;\n}\nasync function gwBoardAll(table, fields, orderField, ascending, noteSource){\n  let all = [];\n  for(let page=0;page<30;page++){\n    let query = client.from(table).select(fields);\n    if(noteSource) query=query.eq(\"note_source\",noteSource);\n    const {data,error} = await query.order(orderField,{ascending:ascending}).range(page*500,page*500+499);\n    if(error) throw error;\n    all.push(...(data||[]));\n    if(!data || data.length<500) break;\n    if(page===29) throw new Error(\"Too many records to display safely.\");\n  }\n  return all;\n}\nasync function loadMonthlyJobIds(){\n  if(!client || logout.hidden) return;\n  const seq=++monthlyJobLoadSeq;\n  const words=monthlyWords();\n  monthlyJobList.textContent=words[2];\n  try{\n    \/\/ The existing RLS policies still control which records employees can read.\n    \/\/ Do not require optional columns to render the main job list.\n    let jobs;\n    try {\n      jobs=await gwBoardAll(\"Jobs\",\"job_id,job_address,job_status,completed_at\",\"job_id\",false);\n    } catch (firstError) {\n      console.warn(\"GW board: extended job fields unavailable; using basic job fields\",firstError);\n      jobs=await gwBoardAll(\"Jobs\",\"job_id,job_address,job_status\",\"job_id\",false);\n    }\n    if(logout.hidden || seq!==monthlyJobLoadSeq) return;\n    const active=jobs.filter(j=>j.job_status!==\"Completed\" && !j.completed_at);\n    const completed=jobs.filter(j=>j.job_status===\"Completed\" || !!j.completed_at)\n      .sort((a,b)=>String(b.completed_at||\"\").localeCompare(String(a.completed_at||\"\")) ||\n         String(b.job_id).localeCompare(String(a.job_id))).slice(0,10);\n    const workflows=await gwBoardAll(\"gw_job_workflow\",\"job_id,fabricated,on_hold\",\"job_id\",true);\n    if(logout.hidden || seq!==monthlyJobLoadSeq) return;\n    const workflowMap=new Map(workflows.map(w=>[w.job_id,w]));\n    jobs.forEach(j=>j.gw8=workflowMap.get(j.job_id)||{});\n    const shown=jobs;\n    const ids=new Set(shown.map(j=>j.job_id));\n    const flags=new Map(shown.map(j=>[j.job_id,{measure:false,before:false,after:false,problem:false}]));\n    if(shown.length){\n      \/\/ A failed optional indicator query must never hide the job board.\n      const indicators=await Promise.allSettled([\n        Promise.allSettled([gwBoardAll(\"final_measurements\",\"job_id\",\"id\",false),gwBoardAll(\"gw_final_measurement_versions\",\"job_id,measurement_status\",\"version_id\",false)]).then(rs=>rs.flatMap((r,i)=>r.status===\"fulfilled\"?r.value.filter(x=>i===0||x.measurement_status===\"Completed\"):[])),\n        gwBoardAll(\"job_photo\",\"job_id,photo_type\",\"id\",false),\n        gwBoardAll(\"job_problems\",\"job_id,status\",\"id\",false)\n      ]);\n      const [measurements,photos,problems]=indicators.map((result,index)=>{\n        if(result.status===\"fulfilled\") return result.value;\n        console.warn(\"GW board: optional indicator unavailable\",index,result.reason);\n        return [];\n      });\n      if(logout.hidden || seq!==monthlyJobLoadSeq) return;\n      measurements.forEach(r=>{if(ids.has(r.job_id)) flags.get(r.job_id).measure=true;});\n      photos.forEach(r=>{\n        if(!ids.has(r.job_id))return;\n        if(r.photo_type===\"Before\")flags.get(r.job_id).before=true;\n        if(r.photo_type===\"After\")flags.get(r.job_id).after=true;\n      });\n      problems.forEach(r=>{if(ids.has(r.job_id) && r.status!==\"Resolved\")flags.get(r.job_id).problem=true;});\n    }\n    monthlyJobList.replaceChildren();\n    if(gwMonthMode){\n      const prefix=\"GW-\"+gwMonthPick.value.slice(2).replace(\"-\",\"\")+\"-\";\n      const monthJobs=jobs.filter(r=>String(r.job_id).startsWith(prefix));\n      const done=r=>r.job_status===\"Completed\"||!!r.completed_at;\n      const completedCount=monthJobs.filter(done).length;\n      gwMonthSummary.textContent=\"Total: \"+monthJobs.length+\" \u00b7 In Process: \"+(monthJobs.length-completedCount)+\" \u00b7 Completed: \"+completedCount;\n      const rows=monthJobs.filter(r=>gwMonthFilter.value===\"All\"||(gwMonthFilter.value===\"Completed\"?done(r):!done(r)));\n      const section=gwBoardSection(\"Monthly Jobs \u2014 \"+gwMonthPick.value,rows,words);\n      rows.forEach(r=>section.grid.appendChild(gwBoardCard(r,flags.get(r.job_id),words)));\n      monthlyJobList.append(section.section);gw107BoardNotes(seq);return;\n    }\n    const pending=active.filter(r=>!r.gw8.on_hold&&!r.gw8.fabricated);\n    const fabricated=active.filter(r=>!r.gw8.on_hold&&r.gw8.fabricated);\n    const held=active.filter(r=>r.gw8.on_hold);\n    const inProcess=gwBoardSection(words[0],pending,words);\n    const fab=gwBoardSection(\"Fabricated \u2013 Ready to Install\",fabricated,words);\n    const hold=gwBoardSection(\"On Hold\",held,words);\n    fabricated.forEach(r=>fab.grid.appendChild(gwBoardCard(r,flags.get(r.job_id),words)));\n    held.forEach(r=>hold.grid.appendChild(gwBoardCard(r,flags.get(r.job_id),words)));\n    const recently=gwBoardSection(words[1],completed,words);\n    pending.forEach(r=>inProcess.grid.appendChild(gwBoardCard(r,flags.get(r.job_id),words)));\n    completed.forEach(r=>recently.grid.appendChild(gwBoardCard(r,flags.get(r.job_id),words)));\n    const issueRows=jobs.filter(r=>flags.get(r.job_id).problem);\n    const issues=gwBoardSection(({zh:\"\u5de5\u7a0b\u554f\u984c\",es:\"Problemas de trabajo\"})[getGwPortalLanguage()] || \"Job Issues\",issueRows,words);\n    issueRows.forEach(r=>issues.grid.appendChild(gwBoardCard(r,flags.get(r.job_id),words)));\n    monthlyJobList.append(inProcess.section,fab.section,hold.section,recently.section,issues.section);\n    monthlyJobCount=active.length;\n    gw107BoardNotes(seq);\n  }catch(error){\n    if(!logout.hidden && seq===monthlyJobLoadSeq)\n      monthlyJobList.textContent=words[3]+\" \"+(error?.message || \"Please check job access.\");\n    console.error(\"GW job board:\",error);\n  }\n}\nwindow.addEventListener(\"gw-language-changed\",function(){\n  if(!logout.hidden && !monthlyJobPanel.hidden)void loadMonthlyJobIds();\n});\n\n\/\/ A measurement is editable only after its job's saved data has loaded.\nlet measurementLoadedJobId = null;\n\/\/ Role-scoped dashboard and editor state, reset on each job and logout.\nlet currentWorkRole = null;\nlet currentWorkJobId = null;\nlet measurementLoadOK = false;\nlet preparationLoadOK = false;\n\n\n\/\/ Press Enter in the Job ID field to run the same search as the Find Job button.\n\/\/ Prevent the surrounding WordPress form from submitting or navigating away.\njobIdInput.addEventListener(\"keydown\", function (event) {\n  if (event.key !== \"Enter\" || event.isComposing) return;\n  event.preventDefault();\n  if (!event.repeat && !findJob.disabled) findJob.click();\n});\n\nfindJob.addEventListener(\"click\", async function () {\n  const jobId = jobIdInput.value.trim();\n  resetAccounting();\n    resetCompletion();\n  resetOwnerAssignments();\n  resetWorkDashboards();\n  resetPhotoView();\n  if (!photoUploadBusy) clearPendingPhotos();\n  resetCustomerCodeView();\n  resetPhotoApprovalView();\n  resetDrawingView();\n  resetProblemView();\n  measurementLoadedJobId = null;\n  document.getElementById(\"gw-save-measurement\").disabled = true;\n  document.getElementById(\"gw-measurement-message\").textContent = \"\";\n  \/\/ Prevent measurements from a previous job appearing under this job.\n  document.querySelectorAll(\n    \"#gw-measurement-form input, #gw-measurement-form textarea, #gw-measurement-form select\"\n  ).forEach(function (field) {\n    if (field.type === \"checkbox\") field.checked = false;\n    else field.value = \"\";\n  });\n  \/\/ Clear the previous employee's review before every job search.\n  document.getElementById(\"gw-review-notes\").value = \"\";\n  document.getElementById(\"gw-review-confirmed\").checked = false;\n  document.getElementById(\"gw-review-ready\").checked = false;\n  document.getElementById(\"gw-save-review\").disabled = true;\n  document.getElementById(\"gw-review-message\").textContent = \"\";\n   allReviewsPanel.hidden = true;\n   allReviewsContent.replaceChildren();\ndocument\n  .querySelectorAll(\n    \"#gw-preparation-form input, #gw-preparation-form textarea, #gw-preparation-form select\"\n  )\n  .forEach(function (field) {\n    if (field.type === \"checkbox\") {\n      field.checked = false;\n    } else {\n      field.value = \"\";\n    }\n  });\n  if (!\/^GW-\\d{4}-\\d{3}$\/i.test(jobId) || !client) {\n    jobResult.textContent = \"Please enter a full Job ID (GW-2611-013).\";\n    return;\n  }\ndashboard.hidden = true;\ndocument.getElementById(\"gw-save-preparation\").disabled = true;\n  findJob.disabled = true;\n  jobResult.textContent = \"Searching...\";\n\n  try {\n    const { data: { user }, error: authError } =\n      await client.auth.getUser();\n\n     if (authError || !user) {\n       jobResult.textContent = \"Please log in again.\";\n       return;\n    }\n\n     \/\/ Immediately recheck on a new search: existing sessions can be disabled.\n     const { data: isActive, error: accessError } =\n       await client.rpc(\"gw_employee_is_active\");\n     if (accessError) {\n       jobResult.textContent = \"Unable to verify Portal access. Please try again.\";\n       return;\n     }\n     if (isActive !== true) {\n       try { await client.auth.signOut(); } catch (_error) { \/* deny UI access *\/ }\n       showSignedOut();\n       message.textContent = \"This account's Portal access is disabled. Contact the office.\";\n       return;\n     }\n\n     const { data, error } = await client\n      .from(\"Jobs\")\n      .select(\"job_id, customer_name, customer_phone, job_address, job_status, completed_at\")\n      .eq(\"job_id\", jobId)\n      .maybeSingle();\n\n    if (error) {\n      jobResult.textContent = \"Search error: \" + error.message;\n    } else if (!data) {\n      jobResult.textContent = \"Job not found.\";\n    } else {\n      jobResult.textContent =\n        \"Job ID: \" + data.job_id + \"\\n\" +\n        \"Customer: \" + (data.customer_name || \"\") + \"\\n\" +\n        \"Phone: \" + (data.customer_phone || \"\") + \"\\n\" +\n        \"Address: \" + (data.job_address || \"\") + \"\\n\" +\n        \"Status: \" + (data.job_status || \"\");\n      jobResult.style.whiteSpace = \"pre-line\";\ndashboard.hidden = false;\ngwOpenFocusedDetail(data);\nawait gw10Load(data.job_id);\nconst { data: savedPreparation, error: loadError } =\n  await client\n    .from(\"site_preparation\")\n    .select(\"*\")\n    .eq(\"job_id\", data.job_id)\n    .order(\"id\", { ascending: false })\n    .limit(1)\n    .maybeSingle();\n\nif (loadError) {\n  jobResult.textContent +=\n    \"\\nUnable to load Site Preparation: \" + loadError.message;\n    preparationDashboardContent.textContent = \"Unable to load Site Preparation.\";\n\n} else if (savedPreparation) {\n    preparationLoadOK = true;\n  renderWorkSummary(preparationDashboardContent, savedPreparation, preparationDashboardGroups,\n    \"No Site Preparation recorded yet.\");\nconst preparationFields = {\n  \"gw-water-condition\": \"water_shutoff_condition\",\n  \"gw-water-replace\": \"water_shutoff_replace\",\n  \"gw-faucet-condition\": \"faucet_condition\",\n  \"gw-plumbing-modification\": \"plumbing_modification\",\n  \"gw-plumbing-notes\": \"plumbing_notes\",\n  \"gw-electrical-modification\": \"electrical_modification\",\n  \"gw-outlet-issue\": \"outlet_issue\",\n  \"gw-mirror-removal\": \"mirror_removal\",\n  \"gw-wall-condition\": \"wall_condition\",\n  \"gw-wall-work-required\": \"wall_work_required\",\n  \"gw-floor-type\": \"floor_type\",\n  \"gw-floor-protection-required\": \"floor_protection_required\",\n  \"gw-floor-protection-type\": \"floor_protection_type\",\n  \"gw-protection-notes\": \"protection_notes\",\n  \"gw-access-condition\": \"access_condition\",\n  \"gw-stairs-required\": \"stairs_required\",\n  \"gw-special-access-notes\": \"special_access_notes\",\n  \"gw-special-tools-required\": \"special_tools_required\",\n  \"gw-special-tools-list\": \"special_tools_list\",\n  \"gw-special-parts-required\": \"special_parts_required\",\n  \"gw-special-parts-list\": \"special_parts_list\",\n  \"gw-installer-notes\": \"installer_notes\",\n  \"gw-prepared-by\": \"prepared_by\",\n  \"gw-preparation-complete\": \"preparation_complete\",\n  \"gw-installer-reviewed\": \"installer_reviewed\",\n  \"gw-installer-reviewed-by\": \"installer_reviewed_by\",\n  \"gw-ready-for-install\": \"ready_for_install\"\n};\n\nObject.entries(preparationFields).forEach(function ([elementId, column]) {\n  const field = document.getElementById(elementId);\n  if (!field) return;\n\n  if (field.type === \"checkbox\") {\n    field.checked = savedPreparation[column] === true;\n  } else {\n    field.value = savedPreparation[column] ?? \"\";\n  }\n});  \ndocument.getElementById(\"gw-electrical-notes\").value =\n    savedPreparation.electrical_notes || \"\";\n} else {\n   preparationLoadOK = true;\n   renderWorkSummary(preparationDashboardContent, null, preparationDashboardGroups,\n     \"No Site Preparation recorded yet.\");\n}\n\n \/\/ Load only the signed-in employee's review for the selected job.\nconst { data: savedReview, error: reviewLoadError } = await client\n  .from(\"installer_reviews\")\n  .select(\"installer_notes, installer_reviewed, ready_for_install\")\n  .eq(\"job_id\", data.job_id)\n  .eq(\"user_id\", user.id)\n  .order(\"id\", { ascending: false })\n  .limit(1)\n  .maybeSingle();\n\nif (reviewLoadError) {\n  jobResult.textContent +=\n    \"\\nUnable to load Installer Review: \" + reviewLoadError.message;\n  \/\/ Leave Save disabled when the existing record cannot be checked.\n} else {\n  document.getElementById(\"gw-review-notes\").value =\n    savedReview?.installer_notes ?? \"\";\n  document.getElementById(\"gw-review-confirmed\").checked =\n    savedReview?.installer_reviewed === true;\n  document.getElementById(\"gw-review-ready\").checked =\n    savedReview?.ready_for_install === true;\n  document.getElementById(\"gw-save-review\").disabled = false;\n}\n\/\/ Only owners get the overview. RLS must independently enforce this access.\nconst { data: profile, error: profileError } = await client\n  .from(\"employee_profiles\")\n  .select(\"role\")\n  .eq(\"user_id\", user.id)\n  .maybeSingle();\nif (profileError) {\n  \/\/ Do not let an optional role lookup failure break the read-only work dashboards.\n  \/\/ No edit privilege is granted because role remains null.\n  configureWorkDashboards(null, data.job_id);\n  jobResult.textContent += \"\\nUnable to check employee role; work details are read-only.\";\n   } else {\n   configureWorkDashboards(profile?.role || null, data.job_id);\n   gw8Role(data.job_id,profile?.role || null);\n   configureDrawingView(data.job_id, profile?.role || null);\n   configureProblemView(data.job_id, profile?.role || null);\n   \n   configureCustomerCodeView(data.job_id, profile?.role || null, user.id);\n   configurePhotoApprovalView(data.job_id, profile?.role || null, user.id);\n   if (profile?.role === \"owner\") {\n     configureOwnerAssignments(data.job_id);\n     allReviewsPanel.hidden = true;\n     await refreshOwnerReviews(data.job_id, user.id);\n   }\n   if ([\"owner\", \"office\", \"project_manager\"].includes(profile?.role)) {\n     configureCompletion(data.job_id, data.job_status, data.completed_at);\n\n   }\n   if (profile?.role === \"owner\" || profile?.role === \"office\") {\n     \/\/ Office button is intentionally not shown in the Field Portal.\n     accountingToggle.hidden = true;\n   }\n }\n    }\n  } catch (error) {\n    jobResult.textContent = \"Connection error. Please try again.\";\n  } finally {\n    findJob.disabled = false;\n    if (!gwSchedulePanel.hidden && gwScheduleJobPending) { gwScheduleJobPending = false; gwScheduleStatus.textContent = jobResult.textContent; }\n  }\n});\n \/\/ OFFICE \/ OWNER \u2014 REGISTER AN ALREADY APPROVED JOB.\n \/\/ This UI is NOT an authorization boundary. \"Jobs\" INSERT RLS must independently\n \/\/ limit inserts to active owner\/office employees. A DB UNIQUE constraint on job_id\n \/\/ is also required to stop simultaneous submissions from creating duplicate IDs.\n \/\/ A verified Jobs AFTER INSERT trigger creates the invoice; this UI never adds payments.\n const createJobToggle = document.createElement(\"button\");\n createJobToggle.id = \"gw-create-job-toggle\";\n createJobToggle.type = \"button\";\n createJobToggle.textContent = \"Register Approved Job\"; createJobToggle.classList.add(\"gw-warm-register\");\n createJobToggle.hidden = true;\n createJobToggle.setAttribute(\"aria-expanded\", \"false\");\n createJobToggle.style.cssText = \"width:auto!important;min-height:36px!important;padding:7px 14px!important;margin:10px 0!important;display:inline-block;\";\n\n const createJobPanel = document.createElement(\"section\");\n createJobPanel.id = \"gw-create-job-panel\";\n createJobPanel.hidden = true;\n createJobPanel.style.cssText =\n   \"width:100%;max-width:100%;box-sizing:border-box;padding:16px;margin:8px 0 20px;\" +\n   \"border:1px solid #cbd5e1;border-radius:8px;background:#fff;\";\n const createJobHeading = document.createElement(\"h3\");\n createJobHeading.textContent = \"Register Approved Job\";\n const createJobHelp = document.createElement(\"p\");\n createJobHelp.textContent =\n  \"Only approved jobs receive a Job ID. Enter the approved job's assigned ID \" +\n  \"in GW-0000-000 format (example: GW-2609-018). \" +\n  \"An invoice is automatically created by the database after the job is registered.\";\n createJobPanel.append(createJobHeading, createJobHelp);\n\n function createJobField(id, labelText, type, maxLength, required) {\n   const label = document.createElement(\"label\");\n   label.setAttribute(\"for\", id);\n   label.textContent = labelText;\n   const input = document.createElement(\"input\");\n   input.id = id;\n   input.type = type;\n   input.maxLength = maxLength;\n   input.required = required;\n   input.autocomplete = \"off\";\n   input.style.cssText =\n     \"display:block;width:100%;max-width:100%;box-sizing:border-box;font-size:16px;\";\n   createJobPanel.append(label, input);\n   return input;\n }\n const createJobId = createJobField(\"gw-new-job-id\", \"Job ID * (GW-0000-000)\", \"text\", 11, true);\n createJobId.placeholder = \"GW-2609-018\";\n createJobId.pattern = \"GW-[0-9]{4}-[0-9]{3}\";\n const createCustomerName = createJobField(\n   \"gw-new-customer-name\", \"Customer Name *\", \"text\", 120, true\n );\n const createCustomerPhone = createJobField(\n   \"gw-new-customer-phone\", \"Customer Phone (optional)\", \"tel\", 50, false\n );\n const createJobAddress = createJobField(\n   \"gw-new-job-address\", \"Job Address *\", \"text\", 300, true\n );\n \/\/ Manual approval attestation: this UI records approved work, but cannot\n\/\/ independently verify approval from an external approval system.\nconst createJobApprovalLabel = document.createElement(\"label\");\ncreateJobApprovalLabel.id = \"gw-create-job-approval-label\";\ncreateJobApprovalLabel.style.cssText =\n  \"display:flex;align-items:flex-start;gap:10px;margin:18px 0;cursor:pointer;\";\nconst createJobApproved = document.createElement(\"input\");\ncreateJobApproved.id = \"gw-create-job-approved\";\ncreateJobApproved.type = \"checkbox\";\ncreateJobApproved.required = true;\ncreateJobApproved.style.cssText =\n  \"flex:0 0 22px;width:22px;height:22px;min-width:22px;margin:2px 0 0;\";\nconst createJobApprovalText = document.createElement(\"span\");\ncreateJobApprovalText.textContent =\n  \"I confirm this job has already been approved and its Job ID assigned.\";\ncreateJobApprovalLabel.append(createJobApproved, createJobApprovalText);\ncreateJobPanel.appendChild(createJobApprovalLabel);\nconst createJobSave = document.createElement(\"button\");\n createJobSave.id = \"gw-create-job-save\";\n createJobSave.type = \"button\";\n createJobSave.textContent = \"Register Approved Job\";\n createJobSave.style.width = \"100%\";\n const createJobCancel = document.createElement(\"button\");\n createJobCancel.id = \"gw-create-job-cancel\";\n createJobCancel.type = \"button\";\n createJobCancel.textContent = \"Close\";\n createJobCancel.style.width = \"100%\";\n const createJobMessage = document.createElement(\"p\");\n createJobMessage.id = \"gw-create-job-message\";\n createJobMessage.setAttribute(\"role\", \"status\");\n createJobMessage.style.cssText = \"white-space:pre-line;overflow-wrap:anywhere;\";\n createJobPanel.append(createJobSave, createJobCancel, createJobMessage);\n \/\/ V3: Register Job and Bulletin Board share one compact action row.\n const jobActionRow = document.createElement(\"div\");\n jobActionRow.id = \"gw-job-action-row\";\n jobActionRow.style.cssText = \"display:flex;gap:8px;align-items:stretch;margin:10px 0;\";\n const firstSearchLabel = jobSearch.querySelector('label[for=\"gw-job-id\"]');\n if (firstSearchLabel) {\n   firstSearchLabel.insertAdjacentElement(\"beforebegin\", jobActionRow);\n } else {\n   jobSearch.insertBefore(jobActionRow, jobSearch.firstChild);\n }\n jobActionRow.append(createJobToggle, bulletinEntry);\n for (const actionButton of [createJobToggle, bulletinEntry]) {\n   actionButton.style.setProperty(\"flex\", \"1 1 0\", \"important\");\n   actionButton.style.setProperty(\"width\", \"0\", \"important\");\n   actionButton.style.setProperty(\"min-width\", \"0\", \"important\");\n   actionButton.style.setProperty(\"min-height\", \"36px\", \"important\");\n   actionButton.style.setProperty(\"padding\", \"7px 8px\", \"important\");\n   actionButton.style.setProperty(\"margin\", \"0\", \"important\");\n   actionButton.style.setProperty(\"font-size\", \"12px\", \"important\");\n   actionButton.style.setProperty(\"text-align\", \"center\", \"important\");\n }\n jobActionRow.insertAdjacentElement(\"afterend\", createJobPanel);\n\n\/\/ Revision 9 \u2014 employee-facing published weekly schedule (read-only).\nconst gwScheduleEntry = document.createElement('button');\ngwScheduleEntry.type='button'; gwScheduleEntry.id='gw-weekly-schedule-entry';\ngwScheduleEntry.style.cssText='margin:0 0 10px;min-height:48px;';\njobActionRow.insertAdjacentElement('beforebegin',gwScheduleEntry);\nconst gwSchedulePanel=document.createElement('section');\ngwSchedulePanel.id='gw-employee-weekly-schedule'; gwSchedulePanel.hidden=true;\ngwSchedulePanel.style.cssText='padding:14px;border:1px solid #cbd5e1;border-radius:10px;background:white;margin:12px 0;';\nmonthlyJobPanel.insertAdjacentElement('afterend',gwSchedulePanel);\nconst gwScheduleWords={\n en:['Weekly Schedule','This Week','Next Week','Back to Dashboard','No Job','job','jobs','Not published yet','Loading schedule\u2026','Unable to load schedule.','Refresh','Published','Job ID not assigned','Opening job\u2026'],\n zh:['\u6bcf\u9031\u5de5\u4f5c\u5b89\u6392','\u672c\u9031','\u4e0b\u9031','\u8fd4\u56de\u4e3b\u9801','\u6c92\u6709\u5de5\u7a0b','\u9805\u5de5\u7a0b','\u9805\u5de5\u7a0b','\u5c1a\u672a\u767c\u4f48','\u8f09\u5165\u5b89\u6392\u4e2d\u2026','\u7121\u6cd5\u8f09\u5165\u5b89\u6392\u3002','\u91cd\u65b0\u6574\u7406','\u767c\u4f48\u6642\u9593','\u5c1a\u672a\u5206\u914d\u5de5\u7a0b\u7de8\u865f','\u6b63\u5728\u958b\u555f\u5de5\u7a0b\u2026'],\n es:['Horario semanal','Esta semana','Pr\u00f3xima semana','Volver al panel','Sin trabajos','trabajo','trabajos','A\u00fan no publicado','Cargando horario\u2026','No se pudo cargar el horario.','Actualizar','Publicado','Sin ID de trabajo','Abriendo trabajo\u2026']};\nconst gwSW=()=>gwScheduleWords[getGwPortalLanguage()]||gwScheduleWords.en;\nconst gwSE=(tag,parent)=>{const e=document.createElement(tag);parent.append(e);return e;};\nconst gwSB=(parent,fn)=>{const b=gwSE('button',parent);b.type='button';b.onclick=fn;return b;};\nconst gwScheduleBack=gwSB(gwSchedulePanel,()=>gwScheduleDashboard());\nconst gwScheduleHeading=gwSE('h2',gwSchedulePanel);\nconst gwScheduleTabs=gwSE('div',gwSchedulePanel);gwScheduleTabs.style.cssText='display:grid;grid-template-columns:1fr 1fr;gap:8px;';\nconst gwScheduleWeekButtons=[0,1].map(i=>gwSB(gwScheduleTabs,()=>{gwScheduleOffset=i;void gwScheduleLoad();}));\nconst gwScheduleRange=gwSE('p',gwSchedulePanel);gwScheduleRange.style.cssText='text-align:center;font-weight:700;margin:12px 0 4px;';\nconst gwScheduleRefresh=gwSB(gwSchedulePanel,()=>void gwScheduleLoad());gwScheduleRefresh.style.cssText='margin:4px 0;min-height:36px;width:auto;padding:5px 14px;';\nconst gwScheduleStatus=gwSE('p',gwSchedulePanel);gwScheduleStatus.setAttribute('role','status');gwScheduleStatus.style.cssText='font-size:12px;margin:4px 0 10px;color:#526579;';\nconst gwScheduleDays=gwSE('div',gwSchedulePanel);\nlet gwScheduleOffset=0,gwScheduleSeq=0,gwScheduleSaved=null,gwScheduleReturn=false,gwScheduleJobPending=false;\nfunction gwScheduleLabels(){const w=gwSW();gwScheduleEntry.textContent=w[0];gwScheduleHeading.textContent=w[0];gwScheduleBack.textContent=w[3];gwScheduleRefresh.textContent=w[10];gwScheduleWeekButtons.forEach((b,i)=>{b.textContent=w[i+1];b.setAttribute('aria-pressed',String(i===gwScheduleOffset));b.style.background=i===gwScheduleOffset?'#1769aa':'#526579';});}\nfunction gwScheduleReset(){gwScheduleClose();gwScheduleReturn=false;gwScheduleOffset=0;}\nfunction gwScheduleClose(){gwScheduleSeq++;gwSchedulePanel.hidden=true;gwScheduleDays.replaceChildren();gwScheduleStatus.textContent='';gwScheduleJobPending=false;if(gwScheduleSaved){for(const [el,value] of gwScheduleSaved)el.style.display=value;gwScheduleSaved=null;}}\n\/\/ Revision 9.1 \u2014 restore the actual dashboard, not the previous detail view.\nfunction gwScheduleDashboard(){\n  if(logout.hidden||recoveringPassword)return;\n  if(findJob.disabled){gwScheduleStatus.textContent=gwSW()[13];return;}\n  gwScheduleClose();\n  gwScheduleReturn=false;\n  gwMonthMode=false;\n  gwMonthNav.hidden=false;\n  gwMonthControls.hidden=true;\n  gwRestoreActionSections();\n  gwShowDashboardBranch(false);\n  gwDetailOpen=false;\n  gwDetailView.hidden=true;\n  dashboard.hidden=true;\n  jobResult.textContent='';\n  jobSearch.hidden=false;\n  jobSearch.style.display='';\n  monthlyJobPanel.hidden=false;\n  monthlyJobPanel.style.display='';\n  void loadMonthlyJobIds();\n  jobSearch.scrollIntoView({block:'start',behavior:'smooth'});\n}\nfunction gwScheduleOpen(reset=true){if(logout.hidden||recoveringPassword||!client||findJob.disabled&&reset)return;if(!gwSchedulePanel.hidden)return;if(reset)gwScheduleOffset=0;gwScheduleSaved=new Map([[jobSearch,jobSearch.style.display],[monthlyJobPanel,monthlyJobPanel.style.display],[gwDetailView,gwDetailView.style.display],[qPanel,qPanel.style.display],[employeeDirectoryPanel,employeeDirectoryPanel.style.display],[employeeDirectoryToggle,employeeDirectoryToggle.style.display],[annualProblemToggle,annualProblemToggle.style.display],[annualProblemPanel,annualProblemPanel.style.display]]);for(const [el] of gwScheduleSaved)el.style.display='none';gwSchedulePanel.hidden=false;void gwScheduleLoad();gwSchedulePanel.scrollIntoView({block:'start',behavior:'smooth'});}\nfunction gwScheduleDate(offset){const parts=new Intl.DateTimeFormat('en-US',{timeZone:'America\/Chicago',year:'numeric',month:'numeric',day:'numeric'}).formatToParts(new Date());const n=t=>Number(parts.find(p=>p.type===t).value);const d=new Date(Date.UTC(n('year'),n('month')-1,n('day')));d.setUTCDate(d.getUTCDate()-((d.getUTCDay()+6)%7)+offset*7);return d;}\nfunction gwScheduleISO(d){return d.toISOString().slice(0,10);}\nasync function gwScheduleLoad(){if(gwSchedulePanel.hidden||logout.hidden)return;const seq=++gwScheduleSeq,w=gwSW(),start=gwScheduleDate(gwScheduleOffset),end=new Date(start);end.setUTCDate(end.getUTCDate()+6);gwScheduleLabels();gwScheduleRange.textContent=gwScheduleISO(start)+' \u2013 '+gwScheduleISO(end);gwScheduleDays.replaceChildren();gwScheduleStatus.textContent=w[8];try{const {data,error}=await client.rpc('gw_get_published_schedule',{p_week_start:gwScheduleISO(start)});if(seq!==gwScheduleSeq||gwSchedulePanel.hidden||logout.hidden)return;if(error)throw error;if(data!==null&&(!Array.isArray(data.jobs)||data.week_start!==gwScheduleISO(start)))throw Error('Invalid schedule response');const locale=({zh:'zh-TW',es:'es-US'})[getGwPortalLanguage()]||'en-US';gwScheduleStatus.textContent=data?w[11]+': '+new Date(data.published_at).toLocaleString(locale,{timeZone:'America\/Chicago'})+' CT':w[7];for(let i=0;i<7;i++){const day=new Date(start);day.setUTCDate(day.getUTCDate()+i);const iso=gwScheduleISO(day),jobs=(data?.jobs||[]).filter(j=>j.work_date===iso);const detail=gwSE('div',gwScheduleDays);detail.className='gw-warm-day'+(jobs.length?'':' gw-warm-empty');detail.style.cssText='display:grid;grid-template-columns:52px minmax(0,1fr);gap:10px;align-items:center;border-bottom:1px solid #d9d2c4;padding:8px 0;';const dateBox=gwSE('div',detail);dateBox.className='gw-warm-date';dateBox.style.cssText='text-align:center;border-right:1px solid #d9d2c4;padding-right:6px;color:#174a80;';const weekday=gwSE('div',dateBox);weekday.textContent=day.toLocaleDateString(locale,{weekday:'short',timeZone:'UTC'});weekday.style.cssText='font-size:12px;font-weight:700;';const dayNum=gwSE('div',dateBox);dayNum.textContent=String(day.getUTCDate());dayNum.style.cssText='font-size:23px;font-weight:700;line-height:1.15;';const content=gwSE('div',detail);content.style.minWidth='0';if(!jobs.length){const empty=gwSE('span',content);empty.textContent=data?w[4]:'\u2014';empty.style.cssText='color:#64748b;font-size:13px;';}for(const j of jobs){const row=gwSE('div',content);row.style.cssText='padding:3px 0;overflow-wrap:anywhere;';if(content.children.length>1)row.style.borderTop='1px solid #d9d2c4';;const line=gwSE('div',row);line.style.cssText='display:flex;align-items:baseline;gap:8px;flex-wrap:wrap;';const id=String(j.job_id||'');if(\/^GW-\\d{4}-\\d{3}$\/.test(id)){const b=gwSB(line,()=>{if(findJob.disabled||logout.hidden)return;gwScheduleJobPending=true;gwScheduleStatus.textContent=gwSW()[13];jobIdInput.value=id;findJob.click();});b.textContent=id;b.classList.add(\"gw-re17-id\");b.style.cssText='width:auto;min-height:40px;margin:0;padding:4px 8px;font-size:14px;';}else{gwSE('strong',line).textContent=id||w[12];}const addr=gwSE('span',line);addr.className='gw-warm-schedule-address';addr.textContent=j.job_address||'';addr.style.cssText='flex:1 1 150px;font-size:14px;min-width:0;';if(typeof j.sink_source==='string'&&j.sink_source.trim()){const sink=gwSE('div',row);sink.textContent=({zh:'\u6c34\u69fd\u4f86\u6e90',es:'Origen del fregadero'})[getGwPortalLanguage()]||'Sink source';sink.textContent+=': '+j.sink_source;sink.style.cssText='font-size:13px;margin-top:2px;';}if(j.notes){const note=gwSE('div',row);note.className='gw-warm-schedule-note';note.textContent=j.notes;note.style.cssText='white-space:pre-wrap;overflow-wrap:anywhere;margin-top:3px;color:#334155;font-size:13px;';}}}}catch(e){if(seq===gwScheduleSeq&&!gwSchedulePanel.hidden&&!logout.hidden)gwScheduleStatus.textContent=w[9]+' '+(e.message||'');}}\ngwScheduleEntry.onclick=()=>{if(!gwSchedulePanel.hidden)return;if(photoUploadBusy||qBusy)return;if(!qPanel.hidden)qClose();if(gwDetailOpen){gwRestoreActionSections();gwDetailOpen=false;gwDetailView.hidden=true;dashboard.hidden=true;gwShowDashboardBranch(false);jobSearch.style.display=\"\";monthlyJobPanel.style.display=\"\";}gwScheduleOpen();};gwScheduleLabels();\nwindow.addEventListener('gw-language-changed',()=>{gwScheduleLabels();if(!gwSchedulePanel.hidden)void gwScheduleLoad();});\n\n\n\n\/\/ Revision 6B \u2014 Temporary Quotation (private storage, existing official jobs only).\nconst qNav=document.createElement('button'); qNav.type='button';qNav.classList.add('gw-warm-quote');qNav.textContent='Temporary Quotation';qNav.style.cssText=createJobToggle.style.cssText;jobActionRow.insertBefore(qNav,bulletinEntry);\nconst qPanel=document.createElement('section');qPanel.id='gw-re17-quotations';qPanel.hidden=true;qPanel.style.cssText='padding:16px;border:1px solid #cbd5e1;border-radius:12px;background:white;';monthlyJobPanel.insertAdjacentElement('afterend',qPanel);\nlet qBusy=false,qSavedView=null;\nfunction qEl(tag,text,parent){const e=document.createElement(tag);if(text)e.textContent=text;if(parent)parent.append(e);return e;}\nfunction qBtn(parent,text,fn){const b=qEl('button',text,parent);b.type='button';b.onclick=async()=>{if(qBusy)return;qBusy=true;try{await fn();}catch(e){alert(e.message||String(e));}finally{qBusy=false;}};return b;}\nfunction qField(parent,label,value='',multi=false){qEl('label',label,parent);const e=qEl(multi?'textarea':'input','',parent);e.value=value;e.style.width='100%';return e;}\nfunction qCheck(r){if(r.error)throw r.error;return r.data;}\nasync function qUser(){return qCheck(await client.auth.getUser()).user;}\nasync function qRole(){const u=await qUser();return qCheck(await client.from('employee_profiles').select('role,is_active').eq('user_id',u.id).single());}\nfunction qClose(){qPanel.hidden=true;qPanel.replaceChildren();if(qSavedView){for(const [e,v] of qSavedView)e.style.display=v;qSavedView=null;}void loadMonthlyJobIds();}\nfunction qBase(title){qPanel.replaceChildren();qBtn(qPanel,'\u2190 Dashboard',qClose);qEl('h2',title,qPanel);}\nfunction qRow(parent){const r=qEl('div','',parent);r.style.cssText='display:flex;gap:8px;align-items:center;flex-wrap:wrap;margin:8px 0';return r;}\nfunction qCompact(parent,text,fn){const b=qBtn(parent,text,fn);b.style.cssText='width:auto;min-height:36px;margin:0;padding:8px 12px;flex:1 1 auto';return b;}\nasync function qList(){qBase('Temporary Quotation');qCompact(qRow(qPanel),'+ New Quotation',qForm);const rows=await gwBoardAll('gw_quotations','*','created_at',false);const photos=await gwBoardAll('gw_quotation_photos','id,quote_id','id',true);const counts=new Map();for(const p of photos)counts.set(p.quote_id,(counts.get(p.quote_id)||0)+1);const pdfCounts=new Map();let pdfCountsOK=true;try{for(const d of await gwBoardAll('gw_quotation_drawings','drawing_id,quote_id,mime_type','drawing_id',true)){if(d.mime_type==='application\/pdf')pdfCounts.set(d.quote_id,(pdfCounts.get(d.quote_id)||0)+1);}}catch(e){pdfCountsOK=false;console.warn('Quotation PDF counts unavailable',e);}if(qPanel.hidden||logout.hidden)return;const pending=qEl('section','',qPanel);qEl('h3','Pending Quotations',pending);const closed=qEl('details','',qPanel);qEl('summary','Closed Quotations',closed);const grids=[pending,closed].map(parent=>{const g=qEl('div','',parent);g.className='gw-board-grid gw-re174-q-grid';return g;});for(const q of rows){const card=qEl('div','',grids[q.status==='Pending'?0:1]);card.className='gw-job-icon gw-re174-q-card';card.dataset.status=q.status;if(q.status==='Converted')card.style.background='#e0f2e4';else if(q.status==='N')card.style.background='#e7e6e6';card.title=q.customer_name+' \u2014 '+q.job_address+' \u2014 '+q.status;const code=qBtn(card,q.quote_id,()=>qDetail(q.quote_id));code.className='gw-job-code';const stars=qEl('span','',card);stars.className='gw-job-stars';for(const [name,has,path] of [['Photos',(counts.get(q.quote_id)||0)>0,'<path d=\"M4 6h4l2-3h4l2 3h4a2 2 0 0 1 2 2v11a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2Z\"\/><circle cx=\"12\" cy=\"13\" r=\"4\"\/>'],['PDF',pdfCountsOK?(pdfCounts.get(q.quote_id)||0)>0:null,'<path d=\"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8Z\"\/><path d=\"M14 2v6h6M8 13h8M8 17h8\"\/>']]){const indicator=qEl('span','',stars);indicator.style.cssText='display:inline-flex;align-items:center;justify-content:center;width:20px;height:20px;color:'+(has?'#e3a500':'#aeb7c1');indicator.title=name+': '+(has===null?'Unavailable':has?'Available':'Missing');indicator.setAttribute('role','img');indicator.setAttribute('aria-label',indicator.title);indicator.innerHTML='<svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"20\" height=\"20\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\">'+path+'<\/svg>';}const address=qEl('span',String(q.job_address||'').trim().split(',')[0]||'Address not entered',card);address.className='gw-job-address';}}\n\nqNav.onclick=async()=>{if(qBusy||logout.hidden)return;qBusy=true;try{qSavedView=new Map([[jobSearch,jobSearch.style.display],[monthlyJobPanel,monthlyJobPanel.style.display]]);jobSearch.style.display='none';monthlyJobPanel.style.display='none';qPanel.hidden=false;await qList();}catch(e){qClose();alert(e.message);}finally{qBusy=false;}};\nlogout.addEventListener('click',()=>{if(!qPanel.hidden)qClose();});\nfunction qPicker(parent){const files=[];const list=qEl('div','',parent);const redraw=()=>{list.replaceChildren();files.forEach((f,i)=>{const row=qEl('div',f.name,list);qBtn(row,'Remove',()=>{files.splice(i,1);redraw();});});};const controls=qRow(parent);for(const camera of [true,false]){const input=qEl('input','',parent);input.type='file';input.accept='image\/*';input.multiple=!camera;if(camera)input.setAttribute('capture','environment');input.hidden=true;qCompact(controls,camera?'Take Photo':'Photo Library',()=>input.click());input.onchange=()=>{files.push(...input.files);input.value='';redraw();};}return files;}\nasync function qUpload(id,files,description=''){const u=await qUser();while(files.length){const f=files[0];const ext=({ 'image\/jpeg':'jpg','image\/png':'png','image\/webp':'webp','image\/heic':'heic','image\/heif':'heif','image\/gif':'gif'})[f.type];if(!ext||f.size>20971520)throw Error('Unsupported image or exceeds 20 MB: '+f.name);const path=u.id+'\/'+id+'\/'+crypto.randomUUID()+'.'+ext;qCheck(await client.storage.from('gw-quotation-photos').upload(path,f,{upsert:false,contentType:f.type}));qCheck(await client.from('gw_quotation_photos').insert({quote_id:id,photo_url:path,description}));files.shift();}}\nfunction qTechnicalPayload(d,areas){\n const clean=o=>Object.fromEntries(Object.entries(o||{}).filter(([,v])=>v!==null&&v!==undefined&&(typeof v!==\"string\"||v.trim()!==\"\")).map(([k,v])=>[k,typeof v===\"string\"?v.trim():v]));\n return {p_default_specs:clean(d),p_project_areas:areas.map(clean)};\n}\nfunction qTechnicalEditor(parent,source={}){\n const d=JSON.parse(JSON.stringify(source.default_specs||{})),areas=JSON.parse(JSON.stringify(source.project_areas||[]));\n const root=qEl('section','',parent);root.style.cssText='border:1px solid #cbd5e1;border-radius:9px;padding:10px;margin:12px 0;';\n gw11TechnicalFields(root,d,areas,true);\n return {root,payload:()=>qTechnicalPayload(d,areas)};\n}\nfunction qTechnicalDetail(q,editable){\n const section=qEl('details','',qPanel);section.style.cssText='border:1px solid #cbd5e1;border-radius:9px;padding:12px;margin:12px 0;';\n qEl('summary','Technical Specifications',section);\n const content=qEl('div','',section);\n const data=qTechnicalPayload(q.default_specs||{},q.project_areas||[]);\n const addLines=(parent,obj)=>{for(const [key,value] of Object.entries(obj)){if(key==='area_type'||key==='area_name')continue;const line=qEl('div','',parent);line.style.cssText='margin:5px 0;white-space:pre-wrap;overflow-wrap:anywhere;';qEl('strong',(gw10Labels[key]||key)+': ',line);qEl('span',String(value),line);}};\n if(Object.keys(data.p_default_specs).length){qEl('h4','Shared specifications',content);addLines(content,data.p_default_specs);}\n for(const area of data.p_project_areas){qEl('h4',area.area_type+(area.area_name?' \u2014 '+area.area_name:''),content);addLines(content,area);}\n if(!Object.keys(data.p_default_specs).length&&!data.p_project_areas.length)qEl('p','No technical specifications entered.',content);\n if(editable)qBtn(content,'Edit Technical Specifications',()=>{\n  content.replaceChildren();const editor=qTechnicalEditor(content,q);const actions=qRow(content);\n  qCompact(actions,'Save Specifications',async()=>{const payload=editor.payload();const controls=[...content.querySelectorAll('button,input,select,textarea')];controls.forEach(e=>e.disabled=true);try{qCheck(await client.rpc('gw_save_quotation_specs',{p_quote_id:q.quote_id,...payload}));await qDetail(q.quote_id);}finally{controls.forEach(e=>e.disabled=false);}});\n  qCompact(actions,'Cancel',()=>qDetail(q.quote_id));\n });\n}\nfunction qForm(){\n qBase('New Quotation');const name=qField(qPanel,'Customer Name *'),address=qField(qPanel,'Job Address *'),phone=qField(qPanel,'Phone (Optional)');\n qEl('h3','Technical Specifications (Optional)',qPanel);const editor=qTechnicalEditor(qPanel);\n const notesSection=qEl('details','',qPanel);qEl('summary','Quotation Notes (Optional)',notesSection);const notes=qField(notesSection,'Notes','',true);\n qEl('h3','Photos (Optional)',qPanel);const files=qPicker(qPanel);let id=null,lastSpecs=null,lastInfo=null;\n const actions=qRow(qPanel);qCompact(actions,'Save Quotation',async()=>{\n  if(!name.value.trim()||!address.value.trim())throw Error('Customer name and address required.');\n  const payload=editor.payload(),signature=JSON.stringify(payload),info={customer_name:name.value.trim(),job_address:address.value.trim(),phone:phone.value,notes:notes.value};\n  const controls=[...qPanel.querySelectorAll('button,input,select,textarea')];controls.forEach(e=>e.disabled=true);\n  try{\n   if(!id){id=qCheck(await client.rpc('gw_create_quotation',{p_customer_name:info.customer_name,p_job_address:info.job_address,p_phone:info.phone,p_notes:info.notes}));lastInfo=JSON.stringify(info);}\n   else if(lastInfo!==JSON.stringify(info)){qCheck(await client.from('gw_quotations').update(info).eq('quote_id',id));lastInfo=JSON.stringify(info);}\n   if(signature!==lastSpecs&&(lastSpecs!==null||Object.keys(payload.p_default_specs).length||payload.p_project_areas.length)){qCheck(await client.rpc('gw_save_quotation_specs',{p_quote_id:id,...payload}));lastSpecs=signature;}\n   await qUpload(id,files);await qDetail(id);\n  }catch(e){if(id)throw Error('Quotation '+id+' was created. Retry Save to finish remaining updates: '+(e.message||String(e)));throw e;}finally{controls.forEach(e=>e.disabled=false);}\n });qCompact(actions,'Cancel',()=>id?qDetail(id):qList());\n}\nasync function qPDFSection(q,role){\n  const host=qEl('section','',qPanel);host.style.cssText='border:1px solid #cbd5e1;border-radius:9px;padding:12px;margin:12px 0';\n  qEl('h3','Quotation PDF \/ Reference Drawings',host);qEl('p','Optional reference only \u2014 not a final cutting plan.',host);\n  const msg=qEl('p','Loading documents\u2026',host);msg.setAttribute('role','status');\n  const current=()=>host.isConnected&&!qPanel.hidden&&!logout.hidden;\n  let docs;try{docs=qCheck(await client.from('gw_quotation_drawings').select('drawing_id,storage_path,file_name,mime_type,created_at').eq('quote_id',q.quote_id).order('created_at',{ascending:false}));}catch(e){if(current())msg.textContent='Unable to load documents: '+e.message;return null;}\n  if(!current())return null;msg.textContent=docs.length?docs.length+' document(s)':'No documents uploaded.';\n  for(const d of docs){const row=qEl('div','',host);row.style.cssText='border-top:1px solid #dbe3ea;padding:8px 0;overflow-wrap:anywhere';qEl('strong',d.file_name,row);const controls=qRow(row);for(const download of [false,true]){const b=qCompact(controls,download?'Download':d.mime_type==='application\/pdf'?'View PDF':'View Drawing',async()=>{\n      if(!current())return;const signed=qCheck(await client.storage.from('gw-quotation-drawings').createSignedUrl(d.storage_path,300,download?{download:d.file_name}:{}));if(!current())return;const a=document.createElement('a');a.href=signed.signedUrl;a.target='_blank';a.rel='noopener noreferrer';a.textContent=download?'Open download':'Open document';controls.querySelector('a')?.remove();controls.append(a);a.click();\n    });}}\n  if(q.status==='Pending'&&role.is_active&&['owner','office','project_manager'].includes(role.role)){\n    const input=qEl('input','',host);input.type='file';input.accept='application\/pdf,.pdf';input.setAttribute('aria-label','Select PDF');let stored=null;\n    input.onchange=()=>{if(stored){input.value='';msg.textContent='A file awaits registration. Retry registration before selecting another.';}};\n    qCompact(qRow(host),'Upload PDF',async()=>{if(!current())return;const f=input.files?.[0];if(!stored&&(!f||!f.size||f.size>20971520||!(\/\\.pdf$\/i.test(f.name))||(f.type&&f.type!=='application\/pdf')))throw Error('Choose a PDF up to 20 MB.');if(!stored){if(!confirm('Upload '+f.name+' to '+q.quote_id+'?'))return;const u=await qUser();if(!current())return;const path=u.id+'\/'+q.quote_id+'\/'+crypto.randomUUID()+'.pdf';msg.textContent='Uploading PDF\u2026';qCheck(await client.storage.from('gw-quotation-drawings').upload(path,f,{upsert:false,contentType:'application\/pdf'}));stored={p_quote_id:q.quote_id,p_storage_path:path,p_file_name:f.name,p_mime_type:'application\/pdf',p_description:null};}try{qCheck(await client.rpc('gw_register_quotation_drawing',stored));}catch(e){msg.textContent='PDF stored but registration not confirmed. Retry Upload PDF to register the same file. '+stored.p_storage_path;throw e;}stored=null;if(current())await qDetail(q.quote_id);});\n  }\n  return docs;\n}\nasync function qDetail(id){\nconst q=qCheck(await client.from('gw_quotations').select('*').eq('quote_id',id).single());const photos=qCheck(await client.from('gw_quotation_photos').select('*').eq('quote_id',id));const role=await qRole();const editable=q.status!=='Converted';\nqPanel.replaceChildren();const nav=qRow(qPanel);qCompact(nav,'\u2190 Dashboard',qClose);qCompact(nav,'\u2190 Quotations',qList);\nconst head=qRow(qPanel);qEl('h2',id,head).className='gw-re17-id';if(editable){const status=qEl('select','',head);status.style.cssText='width:auto;margin:0';for(const v of ['Pending','N'])status.add(new Option(v,v));status.value=q.status;status.onchange=async()=>{if(qBusy){status.value=q.status;return;}qBusy=true;try{qCheck(await client.from('gw_quotations').update({status:status.value}).eq('quote_id',id));await qDetail(id);}catch(e){status.value=q.status;alert(e.message);}finally{qBusy=false;}};}else qEl('span','Converted',head);\nconst info=qEl('section','',qPanel);info.style.cssText='background:#f8fafc;border:1px solid #cbd5e1;border-radius:9px;padding:12px';const ih=qRow(info);qEl('strong','Customer Information',ih);const body=qEl('div','',info);for(const [label,value] of [['Customer Name',q.customer_name],['Job Address',q.job_address],['Phone',q.phone],['Notes',q.notes]]){const line=qEl('div','',body);line.style.cssText='margin:6px 0;overflow-wrap:anywhere';qEl('strong',label+': ',line);qEl('span',value||'\u2014',line);}if(!editable)qEl('p','Converted to '+q.converted_job_id,body);\nif(editable)qCompact(ih,'Edit',()=>{body.replaceChildren();ih.querySelector('button').hidden=true;const name=qField(body,'Customer Name',q.customer_name),address=qField(body,'Job Address',q.job_address),phone=qField(body,'Phone',q.phone),notes=qField(body,'Notes',q.notes,true);const actions=qRow(body);qCompact(actions,'Save Changes',async()=>{if(!name.value.trim()||!address.value.trim())throw Error('Customer name and address required.');qCheck(await client.from('gw_quotations').update({customer_name:name.value.trim(),job_address:address.value.trim(),phone:phone.value,notes:notes.value}).eq('quote_id',id));await qDetail(id);});qCompact(actions,'Cancel',()=>qDetail(id));});\nqTechnicalDetail(q,editable);\nconst ph=qRow(qPanel);qEl('h3','Photos ('+photos.length+')',ph);const grid=qEl('div','',qPanel);grid.style.cssText='display:grid;grid-template-columns:repeat(auto-fill,minmax(100px,100px));gap:8px';for(const p of photos){const r=await client.storage.from('gw-quotation-photos').createSignedUrl(p.photo_url,300);if(r.error){qEl('p','Photo unavailable',grid);continue;}const b=qEl('button','',grid);b.type='button';b.style.cssText='padding:0;margin:0;width:100px;background:transparent;border:0';const img=qEl('img','',b);img.src=r.data.signedUrl;img.style.cssText='width:100%;height:100px;object-fit:cover;border-radius:6px';b.onclick=()=>openPhotoZoom(r.data.signedUrl,p.description||'Quotation photo',b);}\nif(editable){const upload=qEl('section','',qPanel);upload.hidden=true;const add=qCompact(ph,'+ Add Photo',()=>{upload.hidden=false;add.hidden=true;});const files=qPicker(upload),desc=qField(upload,'Description (Optional)');const actions=qRow(upload);qCompact(actions,'Upload All Photos',async()=>{if(!files.length)throw Error('Select photos first.');await qUpload(id,files,desc.value);await qDetail(id);});qCompact(actions,'Cancel',()=>qDetail(id));}\nconst documents=await qPDFSection(q,role);if(qPanel.hidden||logout.hidden)return;const footer=qRow(qPanel);if(editable)qCompact(footer,'Convert to GW Job',()=>{if(documents===null||documents.length)throw Error('Quotation drawing transfer is not installed yet. Use Office only after the transfer update.');return qConvert(q);});if(editable&&role.is_active&&['owner','office'].includes(role.role)){const del=qCompact(footer,'Delete Quotation',async()=>{if(documents===null||documents.length)throw Error('Quotation documents exist or could not be checked. Preserve this quotation in history.');if(!confirm('Permanently delete '+id+' and its original photos? Official job photos are preserved.'))return;for(const p of photos)qCheck(await client.storage.from('gw-quotation-photos').remove([p.photo_url]));qCheck(await client.rpc('gw_delete_quotation',{p_quote_id:id}));await qList();});del.style.background='#b42318';del.style.color='white';}\n}\n\nfunction qConvert(q){qBase('Convert '+q.quote_id);qBtn(qPanel,'Cancel',()=>qDetail(q.quote_id));const input=qField(qPanel,'Existing GW Job ID');const result=qEl('div','',qPanel);qBtn(qPanel,'Load Job',async()=>{result.replaceChildren();const id=input.value.trim().toUpperCase();const j=qCheck(await client.from('Jobs').select('job_id,customer_name,job_address').eq('job_id',id).single());const photos=qCheck(await client.from('gw_quotation_photos').select('*').eq('quote_id',q.quote_id));const count=await client.from('job_photo').select('id',{count:'exact',head:true}).eq('job_id',id).eq('photo_type','Before');qCheck(count);qEl('p','Quotation: '+q.customer_name+' \u2014 '+q.job_address,result);qEl('p','Official job: '+j.job_id+' \u2014 '+j.customer_name+' \u2014 '+j.job_address,result);qEl('p','Existing Before Photos: '+count.count+'; incoming: '+photos.length,result);qBtn(result,'Confirm & Convert',async()=>{if(!confirm('Convert to '+id+'? This appends quotation photos and notes and preserves quotation technical specifications in quotation history. Existing completed measurements are preserved.'))return;const u=await qUser();for(const p of photos){const ext=p.photo_url.split('.').pop().toLowerCase();const dest=u.id+'\/'+id+'\/quote-'+p.id+'.'+ext;const blob=qCheck(await client.storage.from('gw-quotation-photos').download(p.photo_url));const bucket=client.storage.from('job-photos');const up=await bucket.upload(dest,blob,{upsert:false,contentType:blob.type});if(up.error){const old=await bucket.download(dest);if(old.error||old.data.size!==blob.size)throw up.error;const a=new Uint8Array(await old.data.arrayBuffer()),b=new Uint8Array(await blob.arrayBuffer());if(!a.every((v,i)=>v===b[i]))throw Error('Existing copy differs.');}}qCheck(await client.rpc('gw_convert_quotation',{p_quote_id:q.quote_id,p_job_id:id}));await qDetail(q.quote_id);});});}\n\n let createJobRequestId = 0;\n let createJobUserId = null;\n let createJobBusy = false;\n function resetCreateJob() {\n   createJobRequestId++;\n   createJobUserId = null;\n   createJobBusy = false;\n   createJobToggle.hidden = true;\n   createJobToggle.setAttribute(\"aria-expanded\", \"false\");\n   createJobPanel.hidden = true;\n   createJobId.value = \"\";\n   createCustomerName.value = \"\";\n   createCustomerPhone.value = \"\";\n  createJobAddress.value = \"\";\n  createJobApproved.checked = false;\n  createJobMessage.textContent = \"\";\n   createJobSave.disabled = false;\n   createJobCancel.disabled = false;\n }\n async function verifyCreateJobRole() {\n   if (!client || logout.hidden || jobSearch.hidden) return null;\n   const { data: auth, error: authError } = await client.auth.getUser();\n   if (authError || !auth.user) return null;\n   const { data: active, error: activeError } =\n     await client.rpc(\"gw_employee_is_active\");\n   if (activeError || active !== true) return null;\n   const { data: profile, error: profileError } = await client\n     .from(\"employee_profiles\")\n     .select(\"role\")\n     .eq(\"user_id\", auth.user.id)\n     .maybeSingle();\n   if (profileError || !profile ||\n       ![\"owner\", \"office\"].includes(profile.role)) return null;\n   return auth.user.id;\n }\n async function checkCreateJobAccess() {\n   const requestId = ++createJobRequestId;\n   createJobToggle.hidden = true;\n   createJobPanel.hidden = true;\n   createJobUserId = null;\n   try {\n     const userId = await verifyCreateJobRole();\n     if (requestId !== createJobRequestId || !userId || logout.hidden ||\n         jobSearch.hidden) return;\n     createJobUserId = userId;\n     createJobToggle.hidden = false;\n   } catch (_error) {\n     \/\/ Fail closed; existing search and login continue to operate.\n   }\n }\n createJobToggle.addEventListener(\"click\", function () {\n   if (createJobToggle.hidden || logout.hidden || jobSearch.hidden ||\n       !createJobUserId || createJobBusy) return;\n   createJobPanel.hidden = !createJobPanel.hidden;\n   createJobToggle.setAttribute(\"aria-expanded\", String(!createJobPanel.hidden));\n   if (!createJobPanel.hidden) createJobId.focus();\n });\n createJobCancel.addEventListener(\"click\", function () {\n   if (createJobBusy) return;\n   createJobPanel.hidden = true;\n   createJobToggle.setAttribute(\"aria-expanded\", \"false\");\n });\n createJobSave.addEventListener(\"click\", async function () {\n   if (!client || createJobBusy || createJobPanel.hidden ||\n       createJobToggle.hidden || jobSearch.hidden || logout.hidden ||\n       !createJobUserId) return;\n   const jobId = createJobId.value.trim();\n   const customerName = createCustomerName.value.trim();\n   const customerPhone = createCustomerPhone.value.trim();\n   const jobAddress = createJobAddress.value.trim();\n  \/\/ Exact company ID convention; do not automatically generate sequential job numbers.\n  if (!\/^GW-[0-9]{4}-[0-9]{3}$\/.test(jobId)) {\n    createJobMessage.textContent =\n      \"Job ID must use GW-0000-000 (example: GW-2609-018).\";\n     return;\n   }\n  if (!customerName || customerName.length > 120 ||\n       customerPhone.length > 50 || !jobAddress || jobAddress.length > 300) {\n    createJobMessage.textContent = \"Enter a customer name and job address.\";\n    return;\n  }\n  if (!createJobApproved.checked) {\n    createJobMessage.textContent =\n      \"Confirm the job has already been approved before registering its Job ID.\";\n    return;\n  }\n   const requestId = ++createJobRequestId;\n   createJobBusy = true;\n   createJobSave.disabled = true;\n   createJobCancel.disabled = true;\n   createJobMessage.textContent = \"Checking Job ID and employee access...\";\n   try {\n     const userId = await verifyCreateJobRole();\n     if (!userId || userId !== createJobUserId)\n       throw new Error(\"Office \/ Owner access could not be verified. Log in again.\");\n     const { data: existing, error: existingError } = await client\n       .from(\"Jobs\").select(\"job_id\").eq(\"job_id\", jobId)\n       .limit(1).maybeSingle();\n     if (existingError) throw existingError;\n     if (existing) {\n       createJobMessage.textContent =\n         \"This Job ID already exists. Choose a different ID; no job was created.\";\n       return;\n     }\n     if (requestId !== createJobRequestId || logout.hidden ||\n         createJobPanel.hidden) return;\n     if (!window.confirm(\n       \"Register this ALREADY APPROVED job?\\n\\n\" +\n       \"Job ID: \" + jobId + \"\\nCustomer: \" + customerName +\n       \"\\nPhone: \" + (customerPhone || \"(none)\") +\n       \"\\nAddress: \" + jobAddress +\n       \"\\nStatus: Approved\" +\n       \"\\n\\nThis creates a Job record and its automatic $0 invoice. No payment is recorded.\"\n     )) {\n       createJobMessage.textContent = \"Cancelled. No job was created.\";\n       return;\n     }\n    \/\/ Recheck after confirmation; client-side attestation cannot prove\n    \/\/ external approval, and database RLS must enforce active owner\/office access.\n    if (!createJobApproved.checked)\n      throw new Error(\"Approval confirmation is required. No create request sent.\");\n     const confirmedUserId = await verifyCreateJobRole();\n     if (!confirmedUserId || confirmedUserId !== userId ||\n         requestId !== createJobRequestId || logout.hidden ||\n         createJobPanel.hidden)\n       throw new Error(\"Session or employee access changed. No create request sent.\");\n     createJobMessage.textContent = \"Creating job...\";\n     const { data: saved, error: saveError } = await client\n       .from(\"Jobs\")\n       .insert({\n         job_id: jobId,\n         customer_name: customerName,\n         customer_phone: customerPhone || null,\n         job_address: jobAddress,\n         job_status: \"Approved\"\n       })\n       .select(\"job_id, job_status\")\n       .maybeSingle();\n     if (saveError) {\n       if (saveError.code === \"23505\") {\n         createJobMessage.textContent =\n           \"This Job ID already exists. No duplicate job was created.\";\n         return;\n       }\n       throw saveError;\n     }\n     if (!saved || saved.job_id !== jobId) {\n       throw new Error(\n         \"Create result could not be verified. Search this Job ID before retrying.\"\n       );\n     }\n     \/\/ Save is complete. The Jobs insert trigger should create a $0 invoice.\n     \/\/ Don't permit a new Create submission of this same record.\n     createJobSave.disabled = true;\n     jobIdInput.value = saved.job_id;\n     createJobMessage.textContent =\n       \"Approved job registered: \" + saved.job_id + \".\\n\" +\n       \"Opening job details...\" +\n       (saved.job_status === \"Approved\" ? \"\\nStatus: Approved\" :\n         \"\\nWarning: Saved job status was not Approved. Check the job record.\");\n     try {\n       const { data: invoice, error: invoiceError } = await client\n         .from(\"job_invoices\")\n         .select(\"job_id\")\n         .eq(\"job_id\", saved.job_id)\n         .maybeSingle();\n       if (invoiceError) {\n         createJobMessage.textContent +=\n           \"\\nInvoice status could not be verified; check Office Accounting.\";\n       } else if (!invoice) {\n         createJobMessage.textContent +=\n           \"\\nWarning: Automatic invoice was not found. Check the job trigger \" +\n           \"and Office Accounting before recording payments.\";\n       }\n     } catch (_error) {\n       createJobMessage.textContent +=\n         \"\\nInvoice status could not be verified; check Office Accounting.\";\n     }\n     createJobPanel.hidden = true;\n     createJobToggle.setAttribute(\"aria-expanded\", \"false\");\n     void loadMonthlyJobIds();\n     if (!findJob.disabled) findJob.click();\n   } catch (error) {\n     if (requestId === createJobRequestId && !logout.hidden &&\n         !createJobPanel.hidden) {\n       createJobMessage.textContent =\n         \"Create failed or could not be confirmed: \" + error.message +\n         \"\\nSearch this Job ID before trying again.\";\n     }\n   } finally {\n     if (requestId === createJobRequestId && !logout.hidden &&\n         !createJobPanel.hidden) {\n       createJobBusy = false;\n       createJobCancel.disabled = false;\n       \/\/ Success leaves Save disabled until a new Job ID is entered.\n       if (!createJobMessage.textContent.startsWith(\"Approved job registered:\"))\n         createJobSave.disabled = false;\n     }\n   }\n });\n createJobId.addEventListener(\"input\", function () {\n   if (!createJobBusy && createJobMessage.textContent.startsWith(\"Approved job registered:\")) {\n     createJobSave.disabled = false;\n     createJobMessage.textContent = \"\";\n   }\n });\n\n\/\/ OWNER \/ OFFICE \u2014 MANUALLY SET OR RESET A CUSTOMER'S PRIVATE LOOKUP CODE.\n\/\/ This creates UI only; the SECURITY DEFINER database RPC enforces active\n\/\/ owner\/office membership. No code is generated, stored in browser storage,\n\/\/ fetched from the database, or included in a customer-facing URL.\nconst customerCodeToggle = document.createElement(\"button\");\ncustomerCodeToggle.id = \"gw-customer-code-toggle\";\ncustomerCodeToggle.type = \"button\";\ncustomerCodeToggle.textContent = \"Customer Lookup Code (Owner \/ Office)\";\ncustomerCodeToggle.hidden = true;\ncustomerCodeToggle.setAttribute(\"aria-expanded\", \"false\");\ncustomerCodeToggle.style.cssText = \"width:100%;margin:12px 0 8px;\";\n\nconst customerCodePanel = document.createElement(\"section\");\ncustomerCodePanel.id = \"gw-customer-code-panel\";\ncustomerCodePanel.hidden = true;\ncustomerCodePanel.style.cssText =\n  \"padding:16px;margin:8px 0 20px;border:1px solid #cbd5e1;border-radius:8px;\";\nconst customerCodeHeading = document.createElement(\"h3\");\ncustomerCodeHeading.textContent = \"Set \/ Reset Customer Lookup Code\";\nconst customerCodeJobLabel = document.createElement(\"p\");\ncustomerCodeJobLabel.id = \"gw-customer-code-job\";\nconst customerCodeHelp = document.createElement(\"p\");\ncustomerCodeHelp.textContent =\n  \"Enter a random 8-character code using English letters and numbers (at least one of each). \" +\n  \"Use a random, hard-to-guess code, not a phone number or address. \" +\n  \"Saving again replaces the old code immediately. The code cannot be read back \" +\n  \"from this Portal; share it privately with this job's customer.\";\n\nfunction customerCodeField(id, title) {\n  const label = document.createElement(\"label\");\n  label.htmlFor = id;\n  label.textContent = title;\n  label.style.cssText = \"display:block;margin:12px 0 4px;\";\n  const input = document.createElement(\"input\");\n  input.id = id;\n  input.type = \"password\";\n  input.autocomplete = \"off\";\n  input.spellcheck = false;\n  input.maxLength = 8;\n  input.style.cssText = \"display:block;width:100%;max-width:440px;\";\n  customerCodePanel.append(label, input);\n  return input;\n}\ncustomerCodePanel.append(customerCodeHeading, customerCodeJobLabel, customerCodeHelp);\nconst customerCodeInput = customerCodeField(\"gw-customer-code-value\", \"Private lookup code\");\nconst customerCodeConfirmInput = customerCodeField(\n  \"gw-customer-code-confirm\", \"Confirm private lookup code\"\n);\n\/\/ Optional local visibility control; defaults to hidden on every opening.\n\/\/ Never persist the checkbox state or either code field.\nconst customerCodeShowLabel = document.createElement(\"label\");\ncustomerCodeShowLabel.style.cssText =\n  \"display:flex;align-items:center;gap:8px;margin:12px 0;cursor:pointer;\";\nconst customerCodeShowCheckbox = document.createElement(\"input\");\ncustomerCodeShowCheckbox.type = \"checkbox\";\ncustomerCodeShowCheckbox.id = \"gw-customer-code-show\";\ncustomerCodeShowCheckbox.autocomplete = \"off\";\nconst customerCodeShowText = document.createElement(\"span\");\ncustomerCodeShowText.textContent = \"Show letters while typing (both fields)\";\ncustomerCodeShowLabel.append(customerCodeShowCheckbox, customerCodeShowText);\ncustomerCodePanel.append(customerCodeShowLabel);\nfunction hideCustomerCodeLetters() {\n  customerCodeShowCheckbox.checked = false;\n  customerCodeInput.type = \"password\";\n  customerCodeConfirmInput.type = \"password\";\n}\ncustomerCodeShowCheckbox.addEventListener(\"change\", function () {\n  const type = customerCodeShowCheckbox.checked ? \"text\" : \"password\";\n  customerCodeInput.type = type;\n  customerCodeConfirmInput.type = type;\n});\nconst customerCodeSave = document.createElement(\"button\");\ncustomerCodeSave.type = \"button\";\ncustomerCodeSave.id = \"gw-customer-code-save\";\ncustomerCodeSave.textContent = \"Save \/ Reset Code\";\ncustomerCodeSave.style.cssText = \"width:100%;margin-top:12px;\";\nconst customerCodeClose = document.createElement(\"button\");\ncustomerCodeClose.type = \"button\";\ncustomerCodeClose.textContent = \"Close\";\ncustomerCodeClose.style.cssText = \"width:100%;margin-top:6px;\";\nconst customerCodeMessage = document.createElement(\"p\");\ncustomerCodeMessage.id = \"gw-customer-code-message\";\ncustomerCodeMessage.setAttribute(\"role\", \"status\");\ncustomerCodePanel.append(customerCodeSave, customerCodeClose, customerCodeMessage);\ndashboard.append(customerCodeToggle, customerCodePanel);\n\nlet customerCodeJobId = null;\nlet customerCodeUserId = null;\nlet customerCodeGeneration = 0;\nlet customerCodeBusy = false;\nfunction resetCustomerCodeView() {\n  customerCodeGeneration++;\n  customerCodeJobId = null;\n  customerCodeUserId = null;\n  customerCodeBusy = false;\n  customerCodeToggle.hidden = true;\n  customerCodeToggle.setAttribute(\"aria-expanded\", \"false\");\n  customerCodePanel.hidden = true;\n  customerCodeJobLabel.textContent = \"\";\n  hideCustomerCodeLetters();\n  customerCodeInput.value = \"\";\n  customerCodeConfirmInput.value = \"\";\n  customerCodeMessage.textContent = \"\";\n  customerCodeInput.disabled = false;\n  customerCodeConfirmInput.disabled = false;\n  customerCodeSave.disabled = false;\n  customerCodeClose.disabled = false;\n}\nfunction customerCodeIsCurrent(jobId, generation, userId) {\n  return !!client && !logout.hidden && !jobSearch.hidden && !dashboard.hidden &&\n    !customerCodeToggle.hidden && !customerCodePanel.hidden &&\n    customerCodeJobId === jobId && customerCodeUserId === userId &&\n    jobIdInput.value.trim() === jobId && generation === customerCodeGeneration;\n}\nfunction configureCustomerCodeView(jobId, role, userId) {\n  resetCustomerCodeView();\n  if (![\"owner\", \"office\"].includes(role) ||\n      !\/^GW-[0-9]{4}-[0-9]{3}$\/.test(jobId || \"\") ||\n      !userId || logout.hidden || jobSearch.hidden || dashboard.hidden ||\n      jobIdInput.value.trim() !== jobId) return;\n  customerCodeJobId = jobId;\n  customerCodeUserId = userId;\n  customerCodeJobLabel.textContent = \"Selected Job ID: \" + jobId;\n  customerCodeToggle.hidden = false;\n}\ncustomerCodeToggle.addEventListener(\"click\", function () {\n  if (!client || customerCodeToggle.hidden || dashboard.hidden || logout.hidden ||\n      !customerCodeJobId || !customerCodeUserId || customerCodeBusy ||\n      jobIdInput.value.trim() !== customerCodeJobId) return;\n  customerCodePanel.hidden = !customerCodePanel.hidden;\n  customerCodeToggle.setAttribute(\"aria-expanded\", String(!customerCodePanel.hidden));\n  if (customerCodePanel.hidden) {\n    hideCustomerCodeLetters();\n    customerCodeInput.value = \"\";\n    customerCodeConfirmInput.value = \"\";\n    customerCodeMessage.textContent = \"\";\n  } else {\n    customerCodeInput.focus();\n  }\n});\ncustomerCodeClose.addEventListener(\"click\", function () {\n  if (customerCodeBusy) return;\n  customerCodePanel.hidden = true;\n  customerCodeToggle.setAttribute(\"aria-expanded\", \"false\");\n  hideCustomerCodeLetters();\n  customerCodeInput.value = \"\";\n  customerCodeConfirmInput.value = \"\";\n  customerCodeMessage.textContent = \"\";\n});\ncustomerCodeSave.addEventListener(\"click\", async function () {\n  const jobId = customerCodeJobId;\n  const userId = customerCodeUserId;\n  const generation = customerCodeGeneration;\n  if (!customerCodeIsCurrent(jobId, generation, userId) || customerCodeBusy) return;\n  const code = customerCodeInput.value;\n  const confirmation = customerCodeConfirmInput.value;\n  if (!\/^(?=.{8}$)(?=.*[A-Za-z])(?=.*[0-9])[A-Za-z0-9]{8}$\/.test(code)) {\n    customerCodeMessage.textContent =\n      \"Use exactly 8 characters: English letters and numbers, at least one of each. No symbols.\";\n    return;\n  }\n  if (code !== confirmation) {\n    customerCodeMessage.textContent = \"The two codes do not match.\";\n    return;\n  }\n  if (!window.confirm(\n    \"Set or RESET the private lookup code for \" + jobId + \"?\\n\\n\" +\n    \"Any existing customer code will stop working immediately. \" +\n    \"The new code will NOT be shown again after saving.\"\n  )) return;\n\n  customerCodeBusy = true;\n  customerCodeSave.disabled = true;\n  customerCodeClose.disabled = true;\n  customerCodeInput.disabled = true;\n  customerCodeConfirmInput.disabled = true;\n  customerCodeMessage.textContent = \"Verifying Owner \/ Office access...\";\n  try {\n    const verifiedUserId = await verifyCreateJobRole();\n    if (!customerCodeIsCurrent(jobId, generation, userId) ||\n        !verifiedUserId || verifiedUserId !== userId) {\n      throw new Error(\"Session or employee access changed.\");\n    }\n    customerCodeMessage.textContent = \"Saving private code...\";\n    const { data: saved, error: saveError } = await client.rpc(\n      \"gw_set_customer_portal_code\", { p_job_id: jobId, p_code: code }\n    );\n    if (saveError || saved !== true) throw new Error(\"Code was not confirmed as saved.\");\n    if (customerCodeIsCurrent(jobId, generation, userId)) {\n      customerCodeMessage.textContent =\n        \"Private lookup code saved for \" + jobId + \". \" +\n        \"Share the new code privately with the correct customer; \" +\n        \"never include it in a URL or public message.\";\n    }\n  } catch (_error) {\n    if (customerCodeIsCurrent(jobId, generation, userId)) {\n      customerCodeMessage.textContent =\n        \"Unable to confirm whether the code was saved. \" +\n        \"Check your connection and reset with a NEW code if needed.\";\n    }\n  } finally {\n    \/\/ Wipe both fields even after an error; never echo, cache, or log the code.\n    if (customerCodeGeneration === generation) {\n      hideCustomerCodeLetters();\n      customerCodeInput.value = \"\";\n      customerCodeConfirmInput.value = \"\";\n      customerCodeBusy = false;\n      customerCodeSave.disabled = false;\n      customerCodeClose.disabled = false;\n      customerCodeInput.disabled = false;\n      customerCodeConfirmInput.disabled = false;\n    }\n  }\n});\n\n\/\/ OFFICE PAGE: separate in-Portal workspace for Owner \/ Office.\n\/\/ Visibility is only a UI convenience. Supabase RLS remains the security boundary.\nconst accountingToggle = document.createElement(\"button\");\naccountingToggle.id = \"gw-accounting-toggle\";\naccountingToggle.type = \"button\";\naccountingToggle.textContent = \"Office\";\naccountingToggle.hidden = true;\n\/\/ Field Portal: Office navigation button intentionally disabled.\naccountingToggle.setAttribute(\"aria-expanded\", \"false\");\naccountingToggle.style.cssText =\n  \"width:100%;margin:12px 0;padding:15px 16px;text-align:left;font-size:18px;font-weight:700;\" +\n  \"border:1px solid #b9c7d6;border-radius:10px;background:#fff;cursor:pointer;\";\naccountingToggle.style.setProperty(\"color\", \"#0b4f8a\", \"important\");\naccountingToggle.style.setProperty(\"-webkit-text-fill-color\", \"#0b4f8a\", \"important\");\n\nconst accountingPanel = document.createElement(\"section\");\naccountingPanel.id = \"gw-accounting-panel\";\naccountingPanel.hidden = true;\naccountingPanel.style.cssText =\n  \"box-sizing:border-box;width:100%;margin:14px 0 20px;padding:16px;\" +\n  \"border:1px solid #cbd5e1;border-radius:10px;background:#fff;\";\n\nconst accountingTop = document.createElement(\"div\");\naccountingTop.style.cssText =\n  \"display:flex;align-items:center;justify-content:space-between;gap:12px;\" +\n  \"flex-wrap:wrap;margin-bottom:14px;\";\n\nconst accountingBack = document.createElement(\"button\");\naccountingBack.type = \"button\";\naccountingBack.textContent = \"\u2190 Back to Portal\";\naccountingBack.style.cssText = \"margin:0;padding:8px 10px;font-size:14px;\";\n\nconst accountingTitle = document.createElement(\"h2\");\naccountingTitle.textContent = \"Office\";\naccountingTitle.style.cssText = \"margin:0;font-size:26px;line-height:1.2;\";\n\naccountingTop.append(accountingBack, accountingTitle);\naccountingPanel.appendChild(accountingTop);\ndashboard.append(accountingToggle, accountingPanel);\n\nlet accountingPortalState = null;\n\nfunction openAccountingView() {\n  if (!accountingRoleAllowed || accountingToggle.hidden || logout.hidden) return;\n\n  accountingPortalState = {\n    jobSearchHidden: jobSearch.hidden,\n    dashboardHidden: dashboard.hidden\n  };\n\n  \/\/ Office is its own page inside the Portal.\n  jobSearch.hidden = true;\n  dashboard.hidden = true;\n  bulletinEntry.hidden = true;\n  bulletinBoard.hidden = true;\n  employeeDirectoryToggle.hidden = true;\n  employeeDirectoryPanel.hidden = true;\n  createJobToggle.hidden = true;\n  createJobPanel.hidden = true;\n  annualProblemToggle.hidden = true;\n  annualProblemPanel.hidden = true;\n\n  accountingToggle.hidden = true;\n  accountingPanel.hidden = false;\n  accountingToggle.setAttribute(\"aria-expanded\", \"true\");\n  accountingTitle.scrollIntoView({ behavior: \"smooth\", block: \"start\" });\n}\n\nfunction closeAccountingView() {\n  if (accountingPanel.hidden) return;\n\n  accountingPanel.hidden = true;\n  accountingToggle.hidden = !accountingRoleAllowed;\n  accountingToggle.setAttribute(\"aria-expanded\", \"false\");\n\n  jobSearch.hidden = false;\n  dashboard.hidden = true;\n  bulletinBoard.hidden = true;\n  bulletinEntry.hidden = false;\n\n  employeeDirectoryPanel.hidden = true;\n  void checkEmployeeDirectoryAccess();\n\n  createJobPanel.hidden = true;\n  void checkCreateJobAccess();\n\n  annualProblemPanel.hidden = true;\n  annualProblemToggle.hidden = !annualProblemAllowed;\n  annualProblemToggle.setAttribute(\"aria-expanded\", \"false\");\n\n  accountingPortalState = null;\n  accountingToggle.scrollIntoView({ behavior: \"smooth\", block: \"center\" });\n}\n\naccountingToggle.addEventListener(\"click\", openAccountingView);\naccountingBack.addEventListener(\"click\", closeAccountingView);\n\nfunction accountingElement(tag, parent, text) {\n  const el = document.createElement(tag);\n  if (text !== undefined) el.textContent = text;\n  parent.appendChild(el);\n  return el;\n}\nfunction accountingField(parent, labelText, type) {\n  const wrap = accountingElement(\"div\", parent);\n  wrap.style.marginBottom = \"10px\";\n  const label = accountingElement(\"label\", wrap, labelText);\n  label.style.display = \"block\";\n  const input = accountingElement(\"input\", wrap);\n  input.type = type;\n  input.style.width = \"100%\";\n  input.style.maxWidth = \"400px\";\n  if (type === \"number\") {\n    input.min = \"0\";\n    input.step = \"0.01\";\n  }\n  return input;\n}\nfunction accountingButton(parent, text) {\n  const button = accountingElement(\"button\", parent, text);\n  button.type = \"button\";\n  button.style.margin = \"4px 8px 4px 0\";\n  return button;\n}\nfunction moneyCents(value) {\n  return Math.round(Number(value || 0) * 100);\n}\nfunction moneyText(cents) {\n  return new Intl.NumberFormat(\"en-US\", {\n    style: \"currency\", currency: \"USD\"\n  }).format(cents \/ 100);\n}\nfunction parseDollars(value, allowZero) {\n  const text = String(value).trim();\n  if (!\/^\\d+(?:\\.\\d{1,2})?$\/.test(text)) return null;\n  const cents = moneyCents(text);\n  if (!Number.isSafeInteger(cents) || cents > 999999999999 ||\n      (!allowZero && cents <= 0)) return null;\n  return cents;\n}\nfunction todayLocal() {\n  const d = new Date();\n  const pad = (v) => String(v).padStart(2, \"0\");\n  return d.getFullYear() + \"-\" + pad(d.getMonth() + 1) + \"-\" + pad(d.getDate());\n}\n\n\/\/ ------------------------------------------------------------\n\/\/ OFFICE \u2014 independent Job ID selector\n\/\/ Office Accounting\/Labor\/Material do NOT depend on the main Portal Job Search.\n\/\/ ------------------------------------------------------------\nconst officeJobBox = accountingElement(\"section\", accountingPanel);\nofficeJobBox.style.cssText =\n  \"margin:8px 0 16px;padding:14px;border:1px solid #dbe3ea;border-radius:8px;background:#f8fafc;\";\n\nconst officeJobHeading = accountingElement(\"h3\", officeJobBox, \"Job\");\nofficeJobHeading.style.cssText = \"margin:0 0 10px;font-size:20px;\";\n\nconst officeJobLabel = accountingElement(\"label\", officeJobBox, \"Job ID\");\nofficeJobLabel.style.cssText = \"display:block;font-weight:600;margin-bottom:5px;\";\n\nconst officeJobIdInput = accountingElement(\"input\", officeJobBox);\nofficeJobIdInput.type = \"text\";\nofficeJobIdInput.maxLength = 20;\nofficeJobIdInput.placeholder = \"GW-2610-001\";\nofficeJobIdInput.autocomplete = \"off\";\nofficeJobIdInput.style.cssText =\n  \"box-sizing:border-box;width:100%;max-width:400px;font-size:17px;padding:9px;margin-bottom:8px;\";\n\nconst officeLoadJobButton = accountingButton(officeJobBox, \"Load Job\");\nconst officeClearJobButton = accountingButton(officeJobBox, \"Clear\");\nconst officeJobMessage = accountingElement(\"p\", officeJobBox);\nofficeJobMessage.setAttribute(\"role\", \"status\");\nofficeJobMessage.setAttribute(\"aria-live\", \"polite\");\nofficeJobMessage.style.cssText = \"margin:8px 0 0;font-size:14px;\";\n\n\/\/ Office modules. Labor + Material are now first-class Office sections;\n\/\/ their Supabase write forms are added in the next step without changing navigation again.\nconst officeModuleNav = accountingElement(\"div\", accountingPanel);\nofficeModuleNav.style.cssText =\n  \"display:flex;gap:8px;flex-wrap:wrap;margin:10px 0 16px;padding-bottom:12px;border-bottom:1px solid #dbe3ea;\";\n\nconst officeAccountingButton = accountingButton(officeModuleNav, \"Invoice \/ Payments\");\nconst officeLaborButton = accountingButton(officeModuleNav, \"Labor\");\nconst officeMaterialButton = accountingButton(officeModuleNav, \"Material\");\n\nconst officeAccountingSection = accountingElement(\"section\", accountingPanel);\nconst officeLaborSection = accountingElement(\"section\", accountingPanel);\nconst officeMaterialSection = accountingElement(\"section\", accountingPanel);\n\nofficeLaborSection.hidden = true;\nofficeMaterialSection.hidden = true;\nofficeLaborSection.style.cssText =\n  \"padding:14px;border:1px solid #dbe3ea;border-radius:8px;background:#fff;\";\nofficeMaterialSection.style.cssText =\n  \"padding:14px;border:1px solid #dbe3ea;border-radius:8px;background:#fff;\";\n\nconst officeLaborHeading = accountingElement(\"h3\", officeLaborSection, \"Labor\");\nconst officeLaborStatus = accountingElement(\n  \"p\",\n  officeLaborSection,\n  \"Select and load a Job ID above. Labor entry will use this same Job ID.\"\n);\nofficeLaborStatus.style.margin = \"6px 0\";\n\/\/ ============================================================\n\/\/ OFFICE LABOR \u2014 INSTALLER FORM UI\n\/\/ Step 2A: UI only. Supabase save will be connected next.\n\/\/ ============================================================\n\nconst installerLaborBox = accountingElement(\"section\", officeLaborSection);\ninstallerLaborBox.style.cssText =\n  \"margin-top:16px;padding:16px;border:1px solid #dbe3ea;\" +\n  \"border-radius:8px;background:#f8fafc;\";\n\nconst installerLaborTitle = accountingElement(\n  \"h4\",\n  installerLaborBox,\n  \"Installer Labor\"\n);\ninstallerLaborTitle.style.cssText = \"margin:0 0 14px;font-size:19px;\";\n\nconst installerWorkDate =\n  accountingField(installerLaborBox, \"Work Date\", \"date\");\ninstallerWorkDate.value = todayLocal();\n\nconst installerWorkType =\n  accountingField(installerLaborBox, \"Work Type\", \"text\");\ninstallerWorkType.value = \"Installation\";\n\nconst installerSF =\n  accountingField(installerLaborBox, \"SF\", \"number\");\ninstallerSF.step = \"0.01\";\n\nconst installerKitchenSink =\n  accountingField(installerLaborBox, \"Kitchen Sink Qty\", \"number\");\ninstallerKitchenSink.step = \"1\";\n\nconst installerBathSink =\n  accountingField(installerLaborBox, \"Bath Sink Qty\", \"number\");\ninstallerBathSink.step = \"1\";\n\nconst installerCooktop =\n  accountingField(installerLaborBox, \"Cooktop Qty\", \"number\");\ninstallerCooktop.step = \"1\";\n\nconst installerMiter =\n  accountingField(installerLaborBox, \"Miter LF\", \"number\");\ninstallerMiter.step = \"0.01\";\n\nconst installerSeam =\n  accountingField(installerLaborBox, \"Seam Qty\", \"number\");\ninstallerSeam.step = \"1\";\n\nfunction installerCheckbox(labelText) {\n  const label = accountingElement(\"label\", installerLaborBox);\n  label.style.cssText =\n    \"display:flex;align-items:center;gap:8px;margin:10px 0;font-weight:600;\";\n\n  const input = accountingElement(\"input\", label);\n  input.type = \"checkbox\";\n\n  accountingElement(\"span\", label, labelText);\n\n  return input;\n}\n\nconst installerDemolition =\n  installerCheckbox(\"Demolition\");\n\nconst installerBacksplash =\n  installerCheckbox(\"Backsplash\");\n\nconst installerRepair =\n  installerCheckbox(\"Repair\");\n\nconst installerOtherWork =\n  accountingField(installerLaborBox, \"Other Work\", \"text\");\n\nconst installerNotesWrap =\n  accountingElement(\"div\", installerLaborBox);\n\ninstallerNotesWrap.style.marginBottom = \"10px\";\n\nconst installerNotesLabel =\n  accountingElement(\"label\", installerNotesWrap, \"Notes\");\n\ninstallerNotesLabel.style.display = \"block\";\n\nconst installerNotes =\n  accountingElement(\"textarea\", installerNotesWrap);\n\ninstallerNotes.rows = 3;\ninstallerNotes.style.cssText =\n  \"box-sizing:border-box;width:100%;max-width:500px;\" +\n  \"font-size:16px;padding:8px;\";\n\nconst saveInstallerLaborButton =\n  accountingButton(installerLaborBox, \"Save Installer Labor\");\n\n\/\/ Disabled until Step 2B connects Supabase.\nsaveInstallerLaborButton.disabled = true;\n\nconst installerLaborMessage =\n  accountingElement(\n    \"p\",\n    installerLaborBox,\n    \"Labor form ready. Database save will be connected next.\"\n  );\n\ninstallerLaborMessage.style.cssText =\n  \"margin:10px 0 0;font-size:14px;\";\n\/\/ Step 2B save temporarily removed so Portal login stays stable.\n\nconst officeMaterialHeading = accountingElement(\"h3\", officeMaterialSection, \"Material\");\nconst officeMaterialStatus = accountingElement(\n  \"p\",\n  officeMaterialSection,\n  \"Select and load a Job ID above. Material entry will use this same Job ID.\"\n);\nofficeMaterialStatus.style.margin = \"6px 0\";\n\nfunction showOfficeModule(moduleName) {\n  officeAccountingSection.hidden = moduleName !== \"accounting\";\n  officeLaborSection.hidden = moduleName !== \"labor\";\n  officeMaterialSection.hidden = moduleName !== \"material\";\n}\n\nofficeAccountingButton.addEventListener(\"click\", function () {\n  showOfficeModule(\"accounting\");\n});\nofficeLaborButton.addEventListener(\"click\", function () {\n  showOfficeModule(\"labor\");\n});\nofficeMaterialButton.addEventListener(\"click\", function () {\n  showOfficeModule(\"material\");\n});\n\nconst invoiceHeading = accountingElement(\"h4\", officeAccountingSection, \"Invoice\");\nconst accountingSummary = accountingElement(\"p\", officeAccountingSection, \"Enter a Job ID above to load its invoice.\");\naccountingSummary.style.whiteSpace = \"pre-line\";\nconst invoiceSubtotal = accountingField(officeAccountingSection, \"Subtotal before tax ($)\", \"number\");\nconst invoiceTax = accountingField(officeAccountingSection, \"Sales Tax ($) \u2014 manual entry\", \"number\");\nconst saveInvoiceButton = accountingButton(officeAccountingSection, \"Save Invoice Amounts\");\nconst invoiceMessage = accountingElement(\"p\", officeAccountingSection);\ninvoiceMessage.setAttribute(\"role\", \"status\");\n\naccountingElement(\"h4\", officeAccountingSection, \"Payments (unlimited)\");\nconst paymentList = accountingElement(\"div\", officeAccountingSection);\naccountingElement(\"h4\", officeAccountingSection, \"Add \/ Edit Payment\");\nconst paymentAmount = accountingField(officeAccountingSection, \"Payment amount ($)\", \"number\");\npaymentAmount.min = \"0.01\";\nconst paymentDate = accountingField(officeAccountingSection, \"Payment date\", \"date\");\nconst paymentMethodWrap = accountingElement(\"div\", officeAccountingSection);\naccountingElement(\"label\", paymentMethodWrap, \"Payment method\").style.display = \"block\";\nconst paymentMethod = accountingElement(\"select\", paymentMethodWrap);\nfor (const method of [\"Zelle\", \"Check\", \"Cash\", \"Credit Card\", \"ACH\", \"Wire\", \"Other\"]) {\n  const option = accountingElement(\"option\", paymentMethod, method);\n  option.value = method;\n}\npaymentMethodWrap.style.marginBottom = \"10px\";\nconst paymentReference = accountingField(officeAccountingSection, \"Reference number (optional)\", \"text\");\nconst paymentNotesWrap = accountingElement(\"div\", officeAccountingSection);\naccountingElement(\"label\", paymentNotesWrap, \"Payment notes (optional)\").style.display = \"block\";\nconst paymentNotes = accountingElement(\"textarea\", paymentNotesWrap);\npaymentNotes.rows = 2;\npaymentNotes.style.width = \"100%\";\npaymentNotes.style.maxWidth = \"400px\";\nconst savePaymentButton = accountingButton(officeAccountingSection, \"Add Payment\");\nconst cancelPaymentButton = accountingButton(officeAccountingSection, \"Cancel Edit\");\nconst paymentMessage = accountingElement(\"p\", officeAccountingSection);\npaymentMessage.setAttribute(\"role\", \"status\");\n\nlet accountingRequestId = 0;\nlet accountingLoadedJobId = null;\nlet accountingInvoice = null;\nlet accountingPayments = [];\nlet editingPaymentId = null;\n\/\/ Remember whether the signed-in employee is allowed to see Office Accounting.\n\/\/ resetAccounting() clears job data, but must not hide the Portal-level entry\n\/\/ from an Owner \/ Office employee.\nlet accountingRoleAllowed = false;\n\nfunction resetPaymentEditor() {\n  editingPaymentId = null;\n  paymentAmount.value = \"\";\n  paymentDate.value = todayLocal();\n  paymentMethod.value = \"Zelle\";\n  paymentReference.value = \"\";\n  paymentNotes.value = \"\";\n  savePaymentButton.textContent = \"Add Payment\";\n  cancelPaymentButton.hidden = true;\n}\nfunction resetAccounting() {\n  accountingRequestId++;\n  accountingLoadedJobId = null;\n  accountingInvoice = null;\n  accountingPayments = [];\n  accountingToggle.hidden = !accountingRoleAllowed;\n  accountingToggle.setAttribute(\"aria-expanded\", \"false\");\n  accountingPanel.hidden = true;\n  accountingPortalState = null;\n  officeJobIdInput.value = \"\";\n  officeJobMessage.textContent = \"\";\n  officeLaborStatus.textContent =\n    \"Select and load a Job ID above. Labor entry will use this same Job ID.\";\n  officeMaterialStatus.textContent =\n    \"Select and load a Job ID above. Material entry will use this same Job ID.\";\n  showOfficeModule(\"accounting\");\n  accountingSummary.textContent = \"Enter a Job ID above to load its invoice.\";\n  invoiceSubtotal.value = \"\";\n  invoiceTax.value = \"\";\n  invoiceMessage.textContent = \"\";\n  paymentMessage.textContent = \"\";\n  paymentList.replaceChildren();\n  saveInvoiceButton.disabled = true;\n  savePaymentButton.disabled = true;\n  resetPaymentEditor();\n}\nfunction accountingIsCurrent(jobId) {\n  return client && accountingRoleAllowed && !logout.hidden && !accountingPanel.hidden &&\n    accountingLoadedJobId === jobId &&\n    officeJobIdInput.value.trim().toUpperCase() === jobId;\n}\nfunction drawAccounting() {\n  const subtotal = moneyCents(accountingInvoice.subtotal);\n  const tax = moneyCents(accountingInvoice.sales_tax);\n  const total = subtotal + tax;\n  const received = accountingPayments.reduce((sum, p) => sum + moneyCents(p.amount), 0);\n  const balance = total - received;\n  accountingSummary.textContent =\n    \"Invoice \/ Job ID: \" + accountingInvoice.job_id + \"\\n\" +\n    \"Subtotal: \" + moneyText(subtotal) + \"\\n\" +\n    \"Sales Tax: \" + moneyText(tax) + \"\\n\" +\n    \"Invoice Total: \" + moneyText(total) + \"\\n\" +\n    \"Total Received: \" + moneyText(received) + \"\\n\" +\n    \"Balance Due: \" + moneyText(Math.max(0, balance)) +\n    (balance < 0 ? \"\\nCredit \/ overpayment: \" + moneyText(-balance) : \"\") + \"\\n\" +\n    \"Due Date: \" + (accountingInvoice.due_date || \"Not set \u2014 awaits job completion workflow\");\n  invoiceSubtotal.value = (subtotal \/ 100).toFixed(2);\n  invoiceTax.value = (tax \/ 100).toFixed(2);\n  paymentList.replaceChildren();\n  if (!accountingPayments.length) {\n    accountingElement(\"p\", paymentList, \"No payments recorded.\");\n  }\n  for (const payment of accountingPayments) {\n    const entry = accountingElement(\"div\", paymentList);\n    entry.style.cssText = \"padding:10px 0;border-bottom:1px solid #e3e8ed;\";\n    const description = accountingElement(\"p\", entry);\n    description.style.whiteSpace = \"pre-wrap\";\n    description.textContent =\n      \"Payment #\" + payment.id + \" \u2014 \" + moneyText(moneyCents(payment.amount)) +\n      \" | \" + payment.payment_date + \" | \" + payment.payment_method +\n      (payment.reference_number ? \"\\nReference: \" + payment.reference_number : \"\") +\n      (payment.notes ? \"\\nNotes: \" + payment.notes : \"\");\n    const edit = accountingButton(entry, \"Edit Payment #\" + payment.id);\n    edit.addEventListener(\"click\", function () {\n      if (!accountingIsCurrent(payment.job_id)) return;\n      editingPaymentId = payment.id;\n      paymentAmount.value = (moneyCents(payment.amount) \/ 100).toFixed(2);\n      paymentDate.value = payment.payment_date;\n      if (![...paymentMethod.options].some((o) => o.value === payment.payment_method)) {\n        const option = accountingElement(\"option\", paymentMethod, payment.payment_method);\n        option.value = payment.payment_method;\n      }\n      paymentMethod.value = payment.payment_method;\n      paymentReference.value = payment.reference_number || \"\";\n      paymentNotes.value = payment.notes || \"\";\n      savePaymentButton.textContent = \"Save Payment Changes\";\n      cancelPaymentButton.hidden = false;\n      paymentMessage.textContent = \"Editing payment #\" + payment.id + \".\";\n      paymentAmount.focus();\n    });\n    const remove = accountingButton(entry, \"Delete Payment #\" + payment.id);\n    remove.addEventListener(\"click\", async function () {\n      const jobId = accountingLoadedJobId;\n      if (!accountingIsCurrent(jobId) || jobId !== payment.job_id) return;\n      if (!window.confirm(\"Delete payment #\" + payment.id + \" for \" +\n          moneyText(moneyCents(payment.amount)) + \"? This removes the payment row. An audit record remains.\")) return;\n      remove.disabled = true;\n      paymentMessage.textContent = \"Deleting payment...\";\n      try {\n        const { data, error } = await client.from(\"invoice_payments\")\n          .delete().eq(\"id\", payment.id).eq(\"job_id\", jobId)\n          .select(\"id\").maybeSingle();\n        if (error) throw error;\n        if (!data) throw new Error(\"Payment was not deleted. Please refresh and check permissions.\");\n        if (accountingIsCurrent(jobId)) {\n          const refreshed = await loadAccounting(jobId);\n          paymentMessage.textContent = refreshed\n            ? \"Payment deleted. Audit Log retains the record.\"\n            : \"Payment deleted, but the accounting view could not refresh.\";\n        }\n      } catch (error) {\n        if (accountingIsCurrent(jobId)) paymentMessage.textContent = \"Delete failed: \" + error.message;\n      } finally {\n        remove.disabled = false;\n      }\n    });\n  }\n}\nasync function loadAccounting(jobId) {\n  const requestId = accountingRequestId;\n  \/\/ Refresh data without forcing the Accounting section open.\n  accountingSummary.textContent = \"Loading invoice and payments...\";\n  saveInvoiceButton.disabled = true;\n  savePaymentButton.disabled = true;\n  invoiceMessage.textContent = \"\";\n  paymentList.replaceChildren();\n  try {\n    const { data: invoice, error: invoiceError } = await client\n      .from(\"job_invoices\")\n      .select(\"job_id, subtotal, sales_tax, due_date\")\n      .eq(\"job_id\", jobId).maybeSingle();\n    if (invoiceError) throw invoiceError;\n    if (!invoice) throw new Error(\"Invoice not found. Check the job invoice record.\");\n    const { data: payments, error: paymentsError } = await client\n      .from(\"invoice_payments\")\n      .select(\"id, job_id, amount, payment_date, payment_method, reference_number, notes\")\n      .eq(\"job_id\", jobId)\n      .order(\"payment_date\", { ascending: false })\n      .order(\"id\", { ascending: false });\n    if (paymentsError) throw paymentsError;\n    if (requestId !== accountingRequestId || accountingPanel.hidden ||\n        officeJobIdInput.value.trim().toUpperCase() !== jobId) return;\n    accountingLoadedJobId = jobId;\n    accountingInvoice = invoice;\n    accountingPayments = payments || [];\n    resetPaymentEditor();\n    drawAccounting();\n    saveInvoiceButton.disabled = false;\n    savePaymentButton.disabled = false;\n    return true;\n  } catch (error) {\n    if (requestId !== accountingRequestId || accountingPanel.hidden ||\n        officeJobIdInput.value.trim().toUpperCase() !== jobId) return;\n    accountingSummary.textContent = \"Unable to load accounting: \" + error.message;\n    accountingLoadedJobId = null;\n    return false;\n  }\n}\nsaveInvoiceButton.addEventListener(\"click\", async function () {\n  const jobId = accountingLoadedJobId;\n  if (!accountingIsCurrent(jobId)) return;\n  const subtotal = parseDollars(invoiceSubtotal.value, true);\n  const tax = parseDollars(invoiceTax.value, true);\n  if (subtotal === null || tax === null || subtotal + tax > 999999999999) {\n    invoiceMessage.textContent = \"Enter valid non-negative dollar amounts (max 2 decimal places).\";\n    return;\n  }\n  saveInvoiceButton.disabled = true;\n  invoiceMessage.textContent = \"Saving invoice amounts...\";\n  try {\n    const { data, error } = await client.from(\"job_invoices\")\n      .update({ subtotal: (subtotal \/ 100).toFixed(2), sales_tax: (tax \/ 100).toFixed(2) })\n      .eq(\"job_id\", jobId).select(\"job_id\").maybeSingle();\n    if (error) throw error;\n    if (!data) throw new Error(\"Invoice not updated. Please check permissions.\");\n    if (accountingIsCurrent(jobId)) {\n      const refreshed = await loadAccounting(jobId);\n      invoiceMessage.textContent = refreshed\n        ? \"Invoice amounts saved successfully!\"\n        : \"Invoice saved, but the accounting view could not refresh.\";\n    }\n  } catch (error) {\n    if (accountingIsCurrent(jobId)) invoiceMessage.textContent = \"Save failed: \" + error.message;\n  } finally {\n    if (accountingIsCurrent(jobId)) saveInvoiceButton.disabled = false;\n  }\n});\ncancelPaymentButton.addEventListener(\"click\", function () {\n  resetPaymentEditor();\n  paymentMessage.textContent = \"Edit cancelled.\";\n});\nsavePaymentButton.addEventListener(\"click\", async function () {\n  const jobId = accountingLoadedJobId;\n  if (!accountingIsCurrent(jobId)) return;\n  const cents = parseDollars(paymentAmount.value, false);\n  if (cents === null || !\/^\\d{4}-\\d{2}-\\d{2}$\/.test(paymentDate.value) ||\n      !paymentMethod.value) {\n    paymentMessage.textContent = \"Enter a positive payment amount, date and method.\";\n    return;\n  }\n  const record = {\n    job_id: jobId,\n    amount: (cents \/ 100).toFixed(2),\n    payment_date: paymentDate.value,\n    payment_method: paymentMethod.value,\n    reference_number: paymentReference.value.trim() || null,\n    notes: paymentNotes.value.trim() || null\n  };\n  const editedId = editingPaymentId;\n  savePaymentButton.disabled = true;\n  paymentMessage.textContent = editedId === null ? \"Adding payment...\" : \"Updating payment...\";\n  try {\n    const query = editedId === null\n      ? client.from(\"invoice_payments\").insert(record)\n      : client.from(\"invoice_payments\").update(record)\n          .eq(\"id\", editedId).eq(\"job_id\", jobId);\n    const { data, error } = await query.select(\"id\").maybeSingle();\n    if (error) throw error;\n    if (!data) throw new Error(\"Payment not saved. Please check permissions.\");\n    if (accountingIsCurrent(jobId)) {\n      const refreshed = await loadAccounting(jobId);\n      paymentMessage.textContent = !refreshed\n        ? \"Payment saved, but the accounting view could not refresh.\"\n        : (editedId === null ? \"Payment added successfully!\" : \"Payment updated successfully!\");\n    }\n  } catch (error) {\n    if (accountingIsCurrent(jobId)) paymentMessage.textContent = \"Save failed: \" + error.message;\n  } finally {\n    if (accountingIsCurrent(jobId)) savePaymentButton.disabled = false;\n  }\n});\nresetAccounting();\n\nofficeLoadJobButton.addEventListener(\"click\", async function () {\n  if (!client || !accountingRoleAllowed || logout.hidden || accountingPanel.hidden ||\n      officeLoadJobButton.disabled) return;\n\n  const jobId = officeJobIdInput.value.trim().toUpperCase();\n  officeJobIdInput.value = jobId;\n\n  if (!\/^GW-\\d{4}-\\d{3}$\/.test(jobId)) {\n    officeJobMessage.textContent = \"Enter a valid Job ID, for example GW-2610-001.\";\n    return;\n  }\n\n  accountingRequestId++;\n  accountingLoadedJobId = null;\n  accountingInvoice = null;\n  accountingPayments = [];\n  saveInvoiceButton.disabled = true;\n  savePaymentButton.disabled = true;\n  officeLoadJobButton.disabled = true;\n  officeClearJobButton.disabled = true;\n  officeJobMessage.textContent = \"Checking Job ID...\";\n  accountingSummary.textContent = \"Loading...\";\n  paymentList.replaceChildren();\n  resetPaymentEditor();\n\n  try {\n    const { data: job, error: jobError } = await client\n      .from(\"Jobs\")\n      .select(\"job_id\")\n      .eq(\"job_id\", jobId)\n      .maybeSingle();\n\n    if (jobError) throw jobError;\n    if (!job) throw new Error(\"Job ID not found.\");\n\n    officeJobMessage.textContent = \"Loaded \" + jobId + \".\";\n    officeLaborStatus.textContent =\n      \"Current Job ID: \" + jobId + \" \u2014 ready for Labor entry.\";\n    officeMaterialStatus.textContent =\n      \"Current Job ID: \" + jobId + \" \u2014 ready for Material entry.\";\n\n    const loaded = await loadAccounting(jobId);\n    if (!loaded && !accountingSummary.textContent.startsWith(\"Unable\")) {\n      accountingSummary.textContent = \"Invoice data is not available for this Job ID.\";\n    }\n  } catch (error) {\n    accountingLoadedJobId = null;\n    accountingInvoice = null;\n    accountingPayments = [];\n    accountingSummary.textContent = \"No Office accounting loaded.\";\n    officeLaborStatus.textContent =\n      \"Select and load a valid Job ID above before entering Labor.\";\n    officeMaterialStatus.textContent =\n      \"Select and load a valid Job ID above before entering Material.\";\n    officeJobMessage.textContent = error.message || \"Unable to load Job ID.\";\n  } finally {\n    officeLoadJobButton.disabled = false;\n    officeClearJobButton.disabled = false;\n  }\n});\n\nofficeJobIdInput.addEventListener(\"keydown\", function (event) {\n  if (event.key !== \"Enter\" || event.isComposing) return;\n  event.preventDefault();\n  if (!event.repeat && !officeLoadJobButton.disabled) officeLoadJobButton.click();\n});\n\nofficeClearJobButton.addEventListener(\"click\", function () {\n  accountingRequestId++;\n  accountingLoadedJobId = null;\n  accountingInvoice = null;\n  accountingPayments = [];\n  officeJobIdInput.value = \"\";\n  officeJobMessage.textContent = \"\";\n  accountingSummary.textContent = \"Enter a Job ID above to load its invoice.\";\n  invoiceSubtotal.value = \"\";\n  invoiceTax.value = \"\";\n  invoiceMessage.textContent = \"\";\n  paymentMessage.textContent = \"\";\n  paymentList.replaceChildren();\n  saveInvoiceButton.disabled = true;\n  savePaymentButton.disabled = true;\n  resetPaymentEditor();\n  officeLaborStatus.textContent =\n    \"Select and load a Job ID above. Labor entry will use this same Job ID.\";\n  officeMaterialStatus.textContent =\n    \"Select and load a Job ID above. Material entry will use this same Job ID.\";\n  officeJobIdInput.focus();\n});\n\nconst measurementButton =\n  document.getElementById(\"gw-final-measurement\");\n\nconst measurementForm =\n  document.getElementById(\"gw-measurement-form\");\n\n\nmeasurementButton.addEventListener(\"click\", function () {\n  if (dashboard.hidden || !currentWorkJobId) return;\n  measurementDashboard.hidden = !measurementDashboard.hidden;\n  if (measurementDashboard.hidden) measurementForm.hidden = true;\n});\nconst saveMeasurement =\n  document.getElementById(\"gw-save-measurement\");\n\nconst measurementMessage =\n  document.getElementById(\"gw-measurement-message\");\n\nconst preparationButton =\n  document.getElementById(\"gw-site-preparation\");\n\nconst preparationForm =\n  document.getElementById(\"gw-preparation-form\");\n\npreparationButton.addEventListener(\"click\", function () {\n  if (dashboard.hidden || !currentWorkJobId) return;\n  preparationDashboard.hidden = !preparationDashboard.hidden;\n  if (preparationDashboard.hidden) preparationForm.hidden = true;\n});\nconst savePreparation =\n  document.getElementById(\"gw-save-preparation\");\n\nconst preparationMessage =\n  document.getElementById(\"gw-preparation-message\");\n\n\/\/ READ-ONLY DASHBOARDS: show persisted data; do not confuse form visibility\n\/\/ with database authorization. Existing edit forms stay hidden until explicitly opened.\nconst measurementDashboard = document.createElement(\"section\");\nmeasurementDashboard.id = \"gw-measurement-dashboard\";\nmeasurementDashboard.hidden = true;\nmeasurementDashboard.style.cssText =\n  \"padding:16px;margin:12px 0 20px;border:1px solid #cbd5e1;border-radius:8px;\";\nconst measurementDashboardTitle = document.createElement(\"h3\");\nmeasurementDashboardTitle.textContent = \"Job Details\";\nconst measurementDashboardContent = document.createElement(\"div\");\nconst editMeasurementButton = measurementButton.cloneNode(false);\neditMeasurementButton.id = \"gw-edit-measurement\";\neditMeasurementButton.type = \"button\";\neditMeasurementButton.textContent = \"Edit Final Measurement\";\neditMeasurementButton.hidden = true;\neditMeasurementButton.style.cssText = \"\";\nconst measurementPhotoButton=document.createElement(\"button\");\nmeasurementPhotoButton.type=\"button\"; gwRE3Label(measurementPhotoButton,\"Measurement Photos\");\nmeasurementPhotoButton.addEventListener(\"click\",()=>gwOpenDetailAction(\"measurementPhoto\"));\nconst measurementActions=document.createElement(\"div\"); measurementActions.className=\"gw-re12-measure-links\";\nmeasurementActions.append(editMeasurementButton);\nconst measurementHeader=document.createElement(\"div\");measurementHeader.className=\"gw-re14-measure-header\";measurementHeader.append(measurementDashboardTitle,measurementActions);measurementDashboard.append(measurementHeader, measurementDashboardContent);\n\n\/\/ V3: append-only measurement editor; original form retained but no longer writes.\nlet gw10State=null;\nconst gw10Editor=document.createElement(\"section\");gw10Editor.hidden=true;\nconst gwRE173MeasureDrop=document.createElement(\"details\");gwRE173MeasureDrop.className=\"gw-re173-measure-drop\";\nconst gwRE173MeasureLabel=document.createElement(\"summary\");gwRE3Label(gwRE173MeasureLabel,\"Final Measurement\");\nconst gwRE173ReadOnly=document.createElement(\"div\");\ngwRE173MeasureDrop.append(gwRE173MeasureLabel,gwRE173ReadOnly,gw10Editor);measurementDashboard.append(gwRE173MeasureDrop);\n\/\/ RE17.4: opening the measurement dropdown is read-only; the explicit edit link opens the editor.\nconst gw10Edges=[\"Eased\",\"1\/4 Round\",\"Demi\",\"3\/8 Bevel\",\"Bullnose\",\"Ogee\"];\nconst gw10Labels={material:\"Material\",thickness:\"Thickness\",edge:\"Edge\",sink_type:\"Sink\",sink_source:\"Sink source\",faucet:\"Faucet\",stove_type:\"Stove\",cutout:\"Cutout size \/ Model number\",backsplash:\"Backsplash\",backsplash_other:\"Backsplash details\",demolish:\"Demolish\",remove_mirror:\"Remove Mirror\",plumbing:\"Plumbing\",seam:\"Seam\",reinforce:\"Reinforce\",notes:\"Notes\",area_name:\"Area name\"};\nfunction gw10Node(tag,text,parent){const e=document.createElement(tag);if(text)e.textContent=text;if(parent)parent.append(e);return e;}\nfunction gw10Btn(parent,text,fn){const b=gw10Node(\"button\",text,parent);b.type=\"button\";b.onclick=fn;return b;}\nfunction gw10Legacy(row){if(!row)return {default_specs:{},project_areas:[]};const d={material:row.material||\"\",edge:gw10Edges.includes(row.edge)?row.edge:\"\"};const text=(row.project_area||\"\").toLowerCase();const types=[];if(\/kitchen\/.test(text))types.push(\"Kitchen\");if(\/bath\/.test(text)&&!\/maybe\/.test(text))types.push(\"Bathroom\");if(\/bar\/.test(text))types.push(\"Bar\");if(\/patio|laundry\/.test(text)||!types.length)types.push(\"Other\");const areas=types.map(t=>({area_type:t}));if(areas.length===1){const a=areas[0];const bs=(row.backsplash||\"\").trim().toLowerCase();a.backsplash=bs===\"4 inch\"?\"4 inch\":bs.includes(\"full wall\")?\"Full Wall\":bs.includes(\"keep tiles\")?\"Keep Tiles\":bs===\"no bs\"?\"None\":bs?\"Other\":\"\";if(a.backsplash===\"Other\")a.backsplash_other=row.backsplash;const stove=(row.stove_type||\"\").trim().toLowerCase();if(a.area_type===\"Kitchen\"&&[\"range\",\"cooktop\"].includes(stove))a.stove_type=stove===\"range\"?\"Range\":\"Cooktop\";if(row.sink_type===\"None\")a.sink_type=\"None\";if(a.area_type===\"Bathroom\"&&\/^(1 hole|one hole|single)$\/i.test((row.faucet||\"\").trim()))a.faucet=\"Single Hole\";if(row.seam_required===true)a.seam=\"Yes\";}return {default_specs:d,project_areas:areas};}\nasync function gw10Load(id){const [old,latest,completed]=await Promise.all([client.from(\"final_measurements\").select(\"*\").eq(\"job_id\",id).order(\"id\",{ascending:false}).limit(1).maybeSingle(),client.from(\"gw_final_measurement_versions\").select(\"*\").eq(\"job_id\",id).order(\"revision_number\",{ascending:false}).limit(1).maybeSingle(),client.from(\"gw_final_measurement_versions\").select(\"*\").eq(\"job_id\",id).eq(\"measurement_status\",\"Completed\").order(\"revision_number\",{ascending:false}).limit(1).maybeSingle()]);if(jobIdInput.value.trim()!==id||logout.hidden)return;if(old.error||latest.error||completed.error){measurementLoadOK=false;measurementDashboardContent.textContent=\"Unable to load measurement. Editing disabled.\";return;}gw10State={id,legacy:old.data,latest:latest.data,completed:completed.data};measurementLoadedJobId=id;measurementLoadOK=true;gw10Render();}\nfunction gw10Render(){const st=gw10State;if(!st)return;const c=measurementDashboardContent;c.replaceChildren();const row=st.completed;const legacy=st.legacy;const summary=gw10Node(\"details\",\"\",c);summary.className=\"gw-warm-measure-summary\";gw10Node(\"summary\",({zh:\"\u5df2\u5132\u5b58\u91cf\u5ea6\u6458\u8981\",es:\"Resumen de medici\u00f3n guardada\"})[getGwPortalLanguage()]||\"Saved Measurement Summary\",summary);const body=gw10Node(\"div\",\"\",summary);const show=(parent,k,v)=>{if(v===null||v===undefined||v===\"\")return;const line=gw10Node(\"div\",\"\",parent);line.style.cssText=\"white-space:pre-wrap;overflow-wrap:anywhere;margin:5px 0;\";gw10Node(\"strong\",(gw10Labels[k]||k)+\": \",line);const chunks=String(v).split(\/(https?:\\\/\\\/[^\\s<>]+)\/gi);for(const chunk of chunks){if(\/^https?:\\\/\\\/\/i.test(chunk)){const a=gw10Node(\"a\",({zh:\"\u958b\u555f\u9023\u7d50\",es:\"Abrir enlace\"})[getGwPortalLanguage()]||\"Open link\",line);a.href=chunk;a.target=\"_blank\";a.rel=\"noopener noreferrer\";}else line.append(document.createTextNode(chunk));}};if(row){show(body,\"Measured by\",row.measured_by_name);show(body,\"Measurement date\",row.measurement_date);show(body,\"Revision\",row.revision_number);gw10Node(\"h4\",\"Shared specifications\",body);for(const k of [\"material\",\"thickness\",\"edge\"])show(body,k,row.default_specs[k]);for(const a of row.project_areas){gw10Node(\"h4\",a.area_type+(a.area_name?\" \u2014 \"+a.area_name:\"\"),body);for(const k of Object.keys(gw10Labels))if(k!==\"area_name\"&&(!a.sinks?.length||!['sink_type','sink_source'].includes(k)))show(body,k,a[k]);if(Array.isArray(a.sinks))a.sinks.forEach((sink,i)=>{gw10Node(\"h5\",\"Sink \"+(i+1),body);for(const [k,label] of Object.entries({type:\"Sink type\",source:\"Sink source\",brand:\"Brand\",model:\"Model\",length:\"Length (in)\",width:\"Width (in)\",depth:\"Depth (in)\",mounting_type:\"Mounting type\",quantity:\"Quantity\",notes:\"Sink notes\"}))show(body,label,sink[k]);});}}else if(legacy){gw10Node(\"h4\",\"Original measurement\",body);for(const [k,v] of Object.entries(legacy))if(![\"id\",\"job_id\",\"created_at\",\"measurement_status\"].includes(k))show(body,k.replaceAll(\"_\",\" \"),v);}else {gw10Node(\"p\",\"No measurement recorded yet.\",body);const empty=gw10Node(\"p\",\"No measurement recorded yet.\",c);empty.style.cssText=\"color:#64748b;font-size:13px;margin:4px 8px;\";}if(st.latest?.measurement_status===\"Draft\")gw10Node(\"p\",\"A measurement draft is available.\",c);editMeasurementButton.textContent=st.latest?.measurement_status===\"Draft\"?\"Continue Final Measurement\":row||legacy?\"Edit Final Measurement\":\"Add Final Measurement\";gwRE173ReadOnly.replaceChildren(...Array.from(body.childNodes,n=>n.cloneNode(true)));}\n\/\/ V12: detailed sink records, stored inside each area in the existing versioned JSON.\nfunction gw12SinkSummary(a){\n  if(!Array.isArray(a.sinks)||!a.sinks.length)return;\n  a.sink_type=a.sinks[0].type||\"\";\n  a.sink_source=a.sinks[0].source||\"\";\n}\nfunction gw121Group(parent,title){\n  const box=gw10Node(\"details\",\"\",parent);box.style.cssText=\"border:1px solid #d8e2eb;border-radius:7px;margin:7px 0;padding:8px;background:#fff;\";\n  const summary=gw10Node(\"summary\",title,box);summary.style.cssText=\"font-weight:600;cursor:pointer;padding:6px 2px;color:#174a80;\";return box;\n}\nfunction gw121Grid(parent,min=115){const box=gw10Node(\"div\",\"\",parent);box.style.cssText=`display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,${min}px),1fr));gap:0 8px;`;return box;}\nfunction gw121SmallButton(parent,label,fn){const b=gw10Btn(parent,label,fn);b.style.cssText=\"width:auto;min-width:0;max-width:100%;margin:4px 4px 4px 0;padding:7px 10px;min-height:36px;border:1px solid #b8cadb;border-radius:6px;background:#fff;color:#174a80;font-size:13px;white-space:normal;\";return b;}\nfunction gw12SinkEditor(parent,a,field){\n  const section=gw121Group(parent,\"Sink Information\");const summary=section.firstElementChild;\n  if(!Array.isArray(a.sinks)){\n    if((a.sink_type||a.sink_source)&&a.sink_type!==\"None\")a.sinks=[{type:a.sink_type||\"\",source:a.sink_source||\"\"}];else a.sinks=[];\n  }\n  const list=gw10Node(\"div\",\"\",section);\n  const types=a.area_type===\"Bathroom\"?[\"Rectangle\",\"Oval\",\"Other\"]:[\"Single\",\"Double\",\"Other\"];\n  const refresh=()=>{summary.textContent=\"Sink Information \u2014 \"+(a.sinks.length?a.sinks.map(x=>[x.type,x.source,x.model].filter(Boolean).join(\" \/ \")||\"Details pending\").join(\"; \"):a.sink_type===\"None\"?\"No Sink\":\"Not specified\");};\n  const sync=()=>{if(a.sinks.length)gw12SinkSummary(a);else{a.sink_type=\"None\";a.sink_source=\"\";}refresh();};\n  const draw=()=>{\n    list.replaceChildren();refresh();\n    if(!a.sinks.length)gw10Node(\"p\",\"No sink details entered.\",list);\n    a.sinks.forEach((sink,i)=>{\n      const card=gw10Node(\"div\",\"\",list);card.style.cssText=\"border-bottom:1px solid #dbe3eb;padding:6px 0;margin:4px 0;\";\n      gw10Node(\"strong\",\"Sink \"+(i+1),card);\n      const basic=gw121Grid(card);const type=field(basic,sink,\"type\",types,\"Sink Type\");const source=field(basic,sink,\"source\",[\"GW\",\"Template\",\"Customer\"],\"Source\");\n      for(const el of [type,source]){const old=el.oninput;el.oninput=()=>{old();sync();};}\n      const models=gw121Grid(card);field(models,sink,\"brand\",null,\"Brand\");const model=field(models,sink,\"model\",null,\"Model\");const old=model.oninput;model.oninput=()=>{old();refresh();};\n      gw10Node(\"div\",\"Overall dimensions (inches)\",card);const sizes=gw10Node(\"div\",\"\",card);sizes.style.cssText=\"display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:5px;\";\n      for(const k of [\"length\",\"width\",\"depth\"])field(sizes,sink,k,null,k[0].toUpperCase()+k.slice(1));\n      const extra=gw121Grid(card);field(extra,sink,\"mounting_type\",[\"Undermount\",\"Drop-in\",\"Farmhouse\",\"Other\"],\"Mounting Type\");const qty=field(extra,sink,\"quantity\",null,\"Quantity\");qty.inputMode=\"numeric\";\n      field(card,sink,\"notes\",null,\"Sink Notes\");gw121SmallButton(card,\"Remove Sink\",()=>{if(confirm(\"Remove this sink from the new revision?\")){a.sinks.splice(i,1);sync();draw();}});\n    });\n  };\n  gw121SmallButton(section,\"+ Add Sink\",()=>{a.sinks.push({type:\"\",source:\"\",quantity:1});sync();draw();});\n  gw121SmallButton(section,\"No Sink\",()=>{if(!a.sinks.length||confirm(\"Mark this area as having no sink in the new revision?\")){a.sinks=[];sync();draw();}});draw();\n}\nfunction gw12ValidateSinks(areas){\n  for(const a of areas){for(const sink of (Array.isArray(a.sinks)?a.sinks:[])){\n    const q=String(sink.quantity??\"\").trim();\n    if(q&&!\/^[1-9][0-9]*$\/.test(q))return \"Sink quantity must be a positive whole number or blank.\";\n    if(q&&!Number.isSafeInteger(Number(q)))return \"Sink quantity is too large.\";\n  }}return \"\";\n}\n\/\/ Shared technical field renderer: Final Measurement and Temporary Quotation.\nfunction gw11TechnicalFields(root,d,areas,compact=false){\nconst areaList=gw10Node(\"div\",\"\",root),addRow=gw10Node(\"div\",\"\",areaList),areaBody=gw10Node(\"div\",\"\",areaList);\nconst shared=gw10Node(compact?\"details\":\"div\",\"\",root);\nif(compact){gw10Node(\"summary\",\"Shared specifications (optional)\",shared);shared.style.cssText=\"border:1px solid #cbd5e1;padding:10px;margin:10px 0;border-radius:8px;\";}\nfunction field(parent,obj,key,options,label){const l=gw10Node(\"label\",label||gw10Labels[key]||key,parent);l.style.cssText=\"display:block;margin:9px 0;font-weight:600;\";const el=gw10Node(options?\"select\":key===\"notes\"?\"textarea\":\"input\",\"\",l);el.style.cssText=\"display:block;width:100%;box-sizing:border-box;min-width:0;padding:8px;margin-top:4px;\";if(options){el.add(new Option(\"\u2014 Select \u2014\",\"\"));for(const v of options)el.add(new Option(v,v));if(obj[key]&&!options.includes(obj[key]))el.add(new Option(obj[key],obj[key]));}el.value=obj[key]||\"\";el.oninput=()=>{obj[key]=el.value;};return el;}\naddRow.style.cssText=\"display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:4px;margin:8px 0;\";for(const t of [\"Kitchen\",\"Bathroom\",\"Bar\",\"Other\"]){const b=gw10Btn(addRow,\"+ \"+t,()=>{areas.push({area_type:t});draw(areas.length-1);});b.style.cssText=\"width:100%;min-width:0;max-width:100%;box-sizing:border-box;margin:0;padding:8px 2px;min-height:44px;font-size:clamp(10px,2.5vw,14px);white-space:nowrap;\";}if(!compact)gw10Node(\"h4\",\"Shared specifications\",shared);field(shared,d,\"material\");field(shared,d,\"thickness\",[\"2 cm\",\"3 cm\",\"Other\"]);field(shared,d,\"edge\",gw10Edges);\nfunction draw(openIndex=-1){areaBody.replaceChildren();areas.forEach((a,i)=>{const p=gw10Node(\"details\",\"\",areaBody);p.open=!compact||i===openIndex;p.style.cssText=\"border:1px solid #cbd5e1;padding:10px;margin:10px 0;border-radius:8px;\";gw10Node(\"summary\",a.area_type+\" \"+(i+1),p);field(p,a,\"area_name\");gw10Btn(p,\"Remove area\",()=>{if(confirm(\"Remove this area from the new revision?\")){areas.splice(i,1);draw();}});field(p,a,\"material\",null,\"Material override (optional)\");field(p,a,\"thickness\",[\"2 cm\",\"3 cm\",\"Other\"],\"Thickness override\");field(p,a,\"edge\",gw10Edges,\"Edge override\");if(compact){field(p,a,\"sink_type\",a.area_type===\"Bathroom\"?[\"Rectangle\",\"Oval\",\"Other\",\"None\"]:[\"Single\",\"Double\",\"Other\",\"None\"]);field(p,a,\"sink_source\",[\"GW\",\"Template\",\"Customer\"]);}else{gw12SinkEditor(p,a,field);}field(p,a,\"faucet\",a.area_type===\"Bathroom\"?[\"Single Hole\",\"4 inch Centerset\",\"8 inch Widespread\"]:[\"1 hole\",\"2 holes\",\"3 holes\",\"4 holes\",\"Other\"],a.area_type===\"Bathroom\"?\"Faucet \/ \u6c34\u9f8d\u982d\":\"Faucet holes\");if(a.area_type===\"Kitchen\"){const stove=field(p,a,\"stove_type\",[\"Range\",\"Cooktop\",\"None\"]);const cut=field(p,a,\"cutout\");cut.parentElement.hidden=a.stove_type!==\"Cooktop\";stove.oninput=()=>{a.stove_type=stove.value;cut.parentElement.hidden=stove.value!==\"Cooktop\";if(cut.parentElement.hidden){a.cutout=\"\";cut.value=\"\";}};}const bs=field(p,a,\"backsplash\",[\"None\",\"4 inch\",\"Full Wall\",\"Tile\",\"Keep Tiles\",\"Other\"]);const other=field(p,a,\"backsplash_other\");other.parentElement.hidden=a.backsplash!==\"Other\";bs.oninput=()=>{a.backsplash=bs.value;other.parentElement.hidden=bs.value!==\"Other\";if(other.parentElement.hidden){a.backsplash_other=\"\";other.value=\"\";}};field(p,a,\"demolish\",[\"Yes\",\"No\"]);if(a.area_type===\"Bathroom\")field(p,a,\"remove_mirror\",[\"Yes\",\"No\"]);for(const k of [\"plumbing\",\"seam\",\"reinforce\"])field(p,a,k,[\"Yes\",\"No\"]);field(p,a,\"notes\");});}draw();\n}\n\/\/ Final Measurement only: grouped editor, separate from quotation.\nfunction gw121MeasurementFields(root,d,areas){\n function field(parent,obj,key,options,label){const l=gw10Node(\"label\",label||gw10Labels[key]||key,parent);l.style.cssText=\"display:block;min-width:0;margin:5px 0;font-weight:600;font-size:13px;\";const el=gw10Node(options?\"select\":key===\"notes\"?\"textarea\":\"input\",\"\",l);el.style.cssText=\"display:block;width:100%;box-sizing:border-box;min-width:0;padding:7px;margin-top:3px;font-size:16px;\";if(options){el.add(new Option(\"\u2014 Select \u2014\",\"\"));for(const v of options)el.add(new Option(v,v));if(obj[key]&&!options.includes(obj[key]))el.add(new Option(obj[key],obj[key]));}el.value=obj[key]??\"\";el.oninput=()=>{obj[key]=el.value;};return el;}\n const shared=gw121Group(root,\"Shared Specifications\");const sharedTitle=shared.firstElementChild;\n const refreshShared=()=>{sharedTitle.textContent=\"Shared Specifications\"+([d.material,d.thickness,d.edge].filter(Boolean).length?\" \u2014 \"+[d.material,d.thickness,d.edge].filter(Boolean).join(\" \/ \"):\" (optional)\");};\n const sh=gw121Grid(shared);for(const el of [field(sh,d,\"material\"),field(sh,d,\"thickness\",[\"2 cm\",\"3 cm\",\"Other\"]),field(sh,d,\"edge\",gw10Edges)]){const old=el.oninput;el.oninput=()=>{old();refreshShared();};}refreshShared();\n const areaBody=gw10Node(\"div\",\"\",root);const add=gw121Group(root,\"+ Add Location\");for(const t of [\"Kitchen\",\"Bathroom\",\"Bar\",\"Other\"])gw121SmallButton(add,\"+ \"+t,()=>{areas.push({area_type:t});draw(areas.length-1);add.open=false;});\n function draw(openIndex=-1){areaBody.replaceChildren();areas.forEach((a,i)=>{\n  const p=gw121Group(areaBody,\"\");p.style.background=\"#f0eadf\";p.open=i===openIndex;const heading=p.firstElementChild;const title=()=>{heading.textContent=\"Location \"+(i+1)+\" \u2014 \"+(a.area_name||a.area_type);};title();const name=field(p,a,\"area_name\",null,\"Location name\");const old=name.oninput;name.oninput=()=>{old();title();};\n  const counter=gw121Group(p,\"Countertop\");const cg=gw121Grid(counter);field(cg,a,\"material\",null,\"Material override\");field(cg,a,\"thickness\",[\"2 cm\",\"3 cm\",\"Other\"],\"Thickness override\");field(cg,a,\"edge\",gw10Edges,\"Edge override\");\n  gw12SinkEditor(p,a,field);\n  const bsGroup=gw121Group(p,\"Backsplash & Stove\");const bg=gw121Grid(bsGroup);const bs=field(bg,a,\"backsplash\",[\"None\",\"4 inch\",\"Full Wall\",\"Tile\",\"Keep Tiles\",\"Other\"]);const other=field(bg,a,\"backsplash_other\");other.parentElement.hidden=a.backsplash!==\"Other\";bs.oninput=()=>{a.backsplash=bs.value;other.parentElement.hidden=bs.value!==\"Other\";if(other.parentElement.hidden){a.backsplash_other=\"\";other.value=\"\";}};\n  if(a.area_type===\"Kitchen\"){const stove=field(bg,a,\"stove_type\",[\"Range\",\"Cooktop\",\"None\"]);const cut=field(bg,a,\"cutout\");cut.parentElement.hidden=a.stove_type!==\"Cooktop\";stove.oninput=()=>{a.stove_type=stove.value;cut.parentElement.hidden=stove.value!==\"Cooktop\";if(cut.parentElement.hidden){a.cutout=\"\";cut.value=\"\";}};}\n  const install=gw121Group(p,\"Installation Details\");const ig=gw121Grid(install);field(ig,a,\"faucet\",a.area_type===\"Bathroom\"?[\"Single Hole\",\"4 inch Centerset\",\"8 inch Widespread\"]:[\"1 hole\",\"2 holes\",\"3 holes\",\"4 holes\",\"Other\"],a.area_type===\"Bathroom\"?\"Faucet\":\"Faucet holes\");field(ig,a,\"demolish\",[\"Yes\",\"No\"]);if(a.area_type===\"Bathroom\")field(ig,a,\"remove_mirror\",[\"Yes\",\"No\"]);for(const k of [\"plumbing\",\"seam\",\"reinforce\"])field(ig,a,k,[\"Yes\",\"No\"]);\n  const notes=gw121Group(p,\"Location Notes\");field(notes,a,\"notes\");gw121SmallButton(p,\"Remove Location\",()=>{if(confirm(\"Remove this area from the new revision?\")){areas.splice(i,1);draw();}});\n });}draw();\n}\nfunction gw10OpenEditor(){\n const st=gw10State;if(!st||!canEditMeasurement(st.id)||!measurementLoadOK)return;\n gwRE173MeasureDrop.open=true;\n gwRE173ReadOnly.hidden=true;\n if(!gw10Editor.hidden){gw10Editor.scrollIntoView({block:\"start\",behavior:\"smooth\"});return;}\n let source=st.latest||gw10Legacy(st.legacy);\n if(st.latest?.measurement_status==='Draft'&&st.latest.source_quotation_id&&(st.completed||st.legacy)){\n  if(!confirm('Use the imported quotation specifications? OK uses quotation; Cancel keeps the existing measurement.'))source=st.completed||gw10Legacy(st.legacy);\n }\n const clone=x=>JSON.parse(JSON.stringify(x));let d=clone(source.default_specs||{}),areas=clone(source.project_areas||[]),expected=st.latest?.version_id??null,busy=false;\n const root=gw10Editor;root.hidden=false;root.replaceChildren();gw10Node('h3','Final Measurement',root);\n const msg=gw10Node('p','',root);msg.setAttribute('role','status');\n function field(parent,obj,key,options,label){const l=gw10Node('label',label||gw10Labels[key]||key,parent);l.style.cssText='display:block;min-width:0;margin:5px 0;font-size:13px;font-weight:600;';const el=gw10Node(options?'select':key==='notes'?'textarea':'input','',l);el.style.cssText='display:block;width:100%;box-sizing:border-box;min-width:0;padding:7px;margin-top:3px;font-size:16px;';if(options){el.add(new Option('\u2014 Select \u2014',''));for(const v of options)el.add(new Option(v,v));if(obj[key]&&!options.includes(obj[key]))el.add(new Option(obj[key],obj[key]));}el.value=obj[key]??'';el.oninput=()=>obj[key]=el.value;return el;}\n async function persist(nd,na,local,done){if(busy||gw10State?.id!==st.id||!canEditMeasurement(st.id)||root.hidden)return;const err=gw12ValidateSinks(na);if(err){local.textContent=err;return;}busy=true;const controls=[...root.querySelectorAll('button,input,select,textarea')].filter(e=>!e.disabled);controls.forEach(e=>e.disabled=true);local.textContent='Saving\u2026';try{\n const check=await client.from('gw_final_measurement_versions').select('version_id').eq('job_id',st.id).order('revision_number',{ascending:false}).limit(1).maybeSingle();if(check.error)throw check.error;if(String(check.data?.version_id??'')!==String(expected??''))throw Error('Measurement changed elsewhere. Reopen the job before saving.');\n const r=await client.rpc('gw_save_final_measurement_v3',{p_job_id:st.id,p_status:na.length?'Completed':'Draft',p_default_specs:nd,p_project_areas:na});if(r.error)throw r.error;expected=r.data;d=nd;areas=na;if(gw10State?.id!==st.id||root.hidden)return;local.textContent='Saved';done();msg.textContent='Saved successfully.';await gw10Load(st.id);void gwRefreshDetailIndicators(st.id);\n }catch(e){local.textContent=e.message||'Save failed.';}finally{busy=false;controls.forEach(e=>e.disabled=false);}}\n const areaBody=gw10Node('div','',root);\n function section(parent,title,get,fields,commit){const box=gw121Group(parent,title);const content=gw10Node('div','',box);function view(){content.replaceChildren();const val=get();for(const [key,label] of fields.map(f=>[f[0],f[2]||gw10Labels[f[0]]||f[0]])){if(val[key]!==undefined&&val[key]!==null&&val[key]!=='')gw10Node('div',label+': '+val[key],content);}gw121SmallButton(content,'Edit',edit);}function edit(){content.replaceChildren();box.open=true;const val=clone(get());const grid=gw121Grid(content);for(const [key,options,label] of fields)field(grid,val,key,options,label);const status=gw10Node('div','',content);gw121SmallButton(content,'Save',()=>commit(val,status,()=>{view();box.open=false;}));}view();return box;}\n const shared=section(root,'Shared Specifications',()=>d,[['material'],['thickness',['2 cm','3 cm','Other']],['edge',gw10Edges]],(val,s,done)=>persist(val,clone(areas),s,done));root.insertBefore(shared,areaBody);\n function drawArea(i){const a=areas[i];const p=gw121Group(areaBody,'Location '+(i+1)+' \u2014 '+(a.area_name||a.area_type));p.style.background='#f0eadf';\n function group(title,fields){return section(p,title,()=>areas[i],fields,(val,s,done)=>{const next=clone(areas);for(const [key] of fields)next[i][key]=val[key]??'';persist(clone(d),next,s,()=>{p.firstElementChild.textContent='Location '+(i+1)+' \u2014 '+(areas[i].area_name||areas[i].area_type);done();});});}\n group('Countertop \/ Location',[['area_name',null,'Location name'],['material',null,'Material override'],['thickness',['2 cm','3 cm','Other']],['edge',gw10Edges]]);\n const sinkBox=gw121Group(p,'Sink Information');const list=gw10Node('div','',sinkBox);\n const getSinks=()=>{const x=areas[i];return Array.isArray(x.sinks)?clone(x.sinks):x.sink_type==='None'||!(x.sink_type||x.sink_source)?[]:[{type:x.sink_type||'',source:x.sink_source||''}];};\n function sinkSave(arr,status,done,noSink=false){const next=clone(areas);next[i].sinks=arr;for(const sink of arr){const q=String(sink.quantity??'').trim();if(q&&\/^[1-9][0-9]*$\/.test(q)&&Number.isSafeInteger(Number(q)))sink.quantity=Number(q);}if(arr.length)gw12SinkSummary(next[i]);else if(noSink){next[i].sink_type='None';next[i].sink_source='';}persist(clone(d),next,status,done);}\n function drawSinks(){list.replaceChildren();const arr=getSinks();if(!arr.length)gw10Node('div',areas[i].sink_type==='None'?'No Sink':'Not specified',list);arr.forEach((sink,j)=>{const card=gw10Node('div','',list);card.style.cssText='border-bottom:1px solid #dbe3eb;padding:8px 0;';gw10Node('strong','Sink '+(j+1),card);gw10Node('div',[sink.type,sink.source,sink.brand,sink.model,[sink.length,sink.width,sink.depth].filter(Boolean).join(' \u00d7 '),sink.mounting_type,sink.quantity?'Qty '+sink.quantity:'',sink.notes].filter(Boolean).join(' \u00b7 ')||'Details not specified',card);gw121SmallButton(card,'Edit',()=>editSink(card,j,sink));});gw121SmallButton(list,'+ Add Sink',()=>{const card=gw10Node('div','',list);editSink(card,arr.length,{quantity:1});});if(!arr.length)gw121SmallButton(list,'No Sink',()=>{const s=gw10Node('div','',list);sinkSave([],s,drawSinks,true);});}\n function editSink(card,j,sink){if(list.querySelector('[data-sink-edit]'))return;card.replaceChildren();card.dataset.sinkEdit='1';gw10Node('strong','Sink '+(j+1),card);const val=clone(sink),g=gw121Grid(card);field(g,val,'type',areas[i].area_type==='Bathroom'?['Rectangle','Oval','Other']:['Single','Double','Other'],'Sink Type');field(g,val,'source',['GW','Template','Customer'],'Source');field(g,val,'brand',null,'Brand');field(g,val,'model',null,'Model');gw10Node('div','Dimensions (inches)',card);const sizes=gw121Grid(card,75);for(const k of ['length','width','depth'])field(sizes,val,k,null,k[0].toUpperCase()+k.slice(1));field(g,val,'mounting_type',['Undermount','Drop-in','Farmhouse','Other'],'Mounting Type');field(g,val,'quantity',null,'Quantity').inputMode='numeric';field(card,val,'notes',null,'Notes');const s=gw10Node('div','',card);gw121SmallButton(card,'Save',()=>{const arr=getSinks();arr[j]=val;sinkSave(arr,s,drawSinks);});}drawSinks();\n const bs=[['backsplash',['None','4 inch','Full Wall','Tile','Keep Tiles','Other']],['backsplash_other']];if(a.area_type==='Kitchen')bs.push(['stove_type',['Range','Cooktop','None']],['cutout']);group('Backsplash & Stove',bs);\n const install=[['faucet',a.area_type==='Bathroom'?['Single Hole','4 inch Centerset','8 inch Widespread']:['1 hole','2 holes','3 holes','4 holes','Other']],['demolish',['Yes','No']]];if(a.area_type==='Bathroom')install.push(['remove_mirror',['Yes','No']]);for(const k of ['plumbing','seam','reinforce'])install.push([k,['Yes','No']]);group('Installation Details',install);group('Location Notes',[['notes']]);return p;}\n areas.forEach((a,i)=>drawArea(i));const add=gw121Group(root,'+ Add Location');const addContent=gw10Node('div','',add);function addView(){addContent.replaceChildren();const v={area_type:'Kitchen',area_name:''};field(addContent,v,'area_type',['Kitchen','Bathroom','Bar','Other'],'Location Type');field(addContent,v,'area_name',null,'Location Name');const s=gw10Node('div','',addContent);gw121SmallButton(addContent,'Save',()=>{if(!v.area_type){s.textContent='Select a location type.';return;}const next=clone(areas);next.push(v);persist(clone(d),next,s,()=>{drawArea(areas.length-1).open=true;add.open=false;addView();});});}addView();\n if(st.legacy){const ref=gw10Node('details','',root);gw10Node('summary','Legacy Measurement Reference',ref);gw10Node('pre',Object.entries(st.legacy).filter(([k])=>!['id','job_id','created_at'].includes(k)).map(([k,v])=>k+': '+(v??'')).join('\\n'),ref).style.whiteSpace='pre-wrap';}\n root.scrollIntoView({block:'start'});\n}\n\n\/\/ Revision 9.2: independent notes inside Job Details, never cloned into action headers.\nconst gw92Notes = document.createElement(\"section\");\ngw92Notes.id = \"gw-job-details-notes\";\ngw92Notes.hidden = true;\nmeasurementDashboard.insertBefore(gw92Notes,gwRE173MeasureDrop);\nconst gwAdditionalDetails=document.createElement(\"details\");gwAdditionalDetails.className=\"gw-re174-additional-drop\";const gwAdditionalSummary=document.createElement(\"summary\");gwRE3Label(gwAdditionalSummary,\"Additional Work\");gwAdditionalDetails.append(gwAdditionalSummary,gwAdditionalSlot);measurementDashboard.append(gwAdditionalDetails);\nconst gwRE173PrivateNotes=document.createElement(\"div\");gwRE173PrivateNotes.hidden=true;measurementDashboard.append(gwRE173PrivateNotes);\nlet gw92Generation = 0;\nfunction gw92ClearNotes(){gw92Generation++;gw92Notes.hidden=true;gw92Notes.replaceChildren();gwRE173PrivateNotes.hidden=true;gwRE173PrivateNotes.replaceChildren();}\nfunction gw92OpenNotes(id){\n  gw92ClearNotes();\n  if (!id || logout.hidden || currentWorkJobId!==id) return;\n  const generation=gw92Generation;\n  const current=()=>generation===gw92Generation&&!logout.hidden&&currentWorkJobId===id&&gwDetailSelectedJobId===id;\n  gw92Notes.hidden=false;\n  const el=(tag,text,parent)=>{const x=document.createElement(tag);if(text)x.textContent=text;if(parent)parent.append(x);return x;};\n  const btn=(parent,text,fn)=>{const x=el(\"button\",text,parent);x.type=\"button\";x.onclick=fn;return x;};\n  const noteReloaders = {};\n  let transferBusy = false;\n  function section(title,table,rpc){\n    const host=table===\"gw_job_private_notes\"?gwRE173PrivateNotes:gw92Notes;host.hidden=false;const box=el(\"details\",\"\",host);box.open=false;box.style.cssText=\"box-sizing:border-box;width:100%;min-width:0;border:1px solid #cbd5e1;border-radius:9px;margin:12px 0;padding:12px;background:\"+(table===\"gw_job_private_notes\"?\"#fff4df\":\"#f0f7ff\")+\";\";\n    const heading=el(\"summary\",title,box);heading.style.cssText=\"font-weight:700;cursor:pointer;padding:8px 0;color:#174a80;\";\n    const input=el(\"textarea\",\"\",box);input.style.cssText=\"display:block;width:100%;box-sizing:border-box;min-height:90px;resize:vertical;\";input.rows=3;input.maxLength=10000;input.placeholder=\"Enter note\u2026\";input.setAttribute(\"aria-label\",title);\n    const msg=el(\"p\",\"\",box);msg.setAttribute(\"role\",\"status\");\n    let rows=[],busy=false,loaded=false,count=null;\n    const actions=el(\"div\",\"\",box);\n    const save=btn(actions,\"Add Note\",async()=>{if(!current()||busy||!input.value.trim())return;busy=true;save.disabled=true;input.disabled=true;msg.textContent=\"Saving\u2026\";try{const {error}=await client.rpc(rpc,{p_job_id:id,p_body:input.value.trim()});if(error)throw error;if(!current())return;input.value=\"\";msg.textContent=\"Note saved.\";await load(true);}catch(e){if(current())msg.textContent=e.message||\"Unable to save note.\";}finally{busy=false;save.disabled=false;input.disabled=false;}});\n    if(table===\"gw_job_private_notes\"){\n      const composer=el(\"div\",\"\",box);\n      actions.style.cssText=\"display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:6px;align-items:stretch;\";\n      const classify=btn(actions,\"Issue Classification\",async()=>{\n        if(!current()||busy)return;\n        classify.disabled=true;\n        try{\n          const note={open_note_id:null,private_note_id:null};\n          await gw93Editor(composer,null,[],note,current,()=>{msg.textContent=\"Private note and classification saved.\";void load(true).catch(e=>{if(current())msg.textContent=e.message||\"Unable to refresh notes.\";});},async(target)=>{\n            if(target.private_note_id!==null)return;\n            if(!current()||busy||!input.value.trim())throw new Error(\"Enter an Office \/ Owner note first.\");\n            busy=true;save.disabled=true;input.disabled=true;\n            try{\n              const data=await gw93Result(client.rpc(rpc,{p_job_id:id,p_body:input.value.trim()}));\n              target.private_note_id=data;\n              if(current()){input.value=\"\";msg.textContent=\"Private note saved. Saving classification\u2026\";await load(true).catch(()=>{});}\n            }finally{busy=false;save.disabled=false;input.disabled=false;}\n          });\n        }catch(e){if(current())msg.textContent=e.message||\"Unable to open classification.\";}\n        finally{classify.disabled=false;}\n      });\n      for(const action of [save,classify]) action.style.cssText=\"width:100%;min-width:0;max-width:100%;box-sizing:border-box;margin:0;padding:8px 4px;min-height:44px;font-size:clamp(11px,2.8vw,14px);white-space:normal;line-height:1.2;\";\n    }\n    const list=el(\"div\",\"\",box);list.style.cssText=\"display:block;width:100%;min-width:0;max-height:280px;overflow-y:auto;overflow-x:hidden;overscroll-behavior-y:contain;\";\n    const older=btn(box,\"Load Older Notes\",async()=>{if(busy||!current())return;busy=true;try{await load(false);}catch(e){if(current())msg.textContent=e.message||\"Unable to load notes.\";}finally{busy=false;}});older.hidden=true;\n    async function load(reset){const offset=reset?0:rows.length;let query=client.from(table).select(\"id,body,author_name,created_at\",{count:\"exact\"}).eq(\"job_id\",id);if(table===\"gw_job_notes\")query=query.eq(\"note_source\",\"manual\");const {data,error,count:total}=await query.order(\"created_at\",{ascending:false}).order(\"id\",{ascending:false}).range(offset,offset+49);if(error)throw error;if(!current())return;rows=reset?(data||[]):rows.concat((data||[]).filter(n=>!rows.some(r=>r.id===n.id)));count=total;loaded=true;list.replaceChildren();if(!rows.length)el(\"p\",\"No notes yet.\",list);for(const n of rows){const item=el(\"article\",\"\",list);item.style.cssText=\"padding:12px 0;border-top:1px solid #e0e8f2;\";el(\"small\",(n.author_name||\"\")+\" \u00b7 \"+new Date(n.created_at).toLocaleString([], {timeZone:\"America\/Chicago\"}),item);const body=el(\"div\",n.body,item);body.style.cssText=\"white-space:pre-wrap;overflow-wrap:anywhere;word-break:break-word;font-size:16px;line-height:1.6;margin-top:6px;color:#243447;\";if(table===\"gw_job_notes\")gwRE3Optional(body,n.body);if (table === \"gw_job_private_notes\" && [\"owner\",\"office\"].includes(currentWorkRole)) gw93NoteControl(item,n,table,current);if(table===\"gw_job_notes\" && [\"owner\",\"office\"].includes(currentWorkRole)){\n      const move=btn(item,\"Move to Private Notes\",async()=>{\n        if(!current()||busy||transferBusy||![\"owner\",\"office\"].includes(currentWorkRole))return;\n        if(!confirm(\"Move this note to Office \/ Owner Notes? Regular employees will no longer see it.\"))return;\n        transferBusy=true;move.disabled=true;\n        let transferred=false;\n        try{\n          const {error}=await client.rpc(\"gw_move_note_to_private\",{p_note_id:n.id});\n          if(error)throw error;\n          transferred=true;\n          if(!current())return;\n          item.remove();msg.textContent=\"Note moved to Office \/ Owner Notes.\";\n          gw107Preview(id);\n          void gw107BoardNotes(monthlyJobLoadSeq);\n          const results=await Promise.allSettled(Object.values(noteReloaders).map(refresh=>refresh()));\n          if(current()&&results.some(r=>r.status===\"rejected\"))msg.textContent=\"Note moved. Reopen Job Details to refresh the lists.\";\n        }catch(e){if(current())msg.textContent=transferred?\"Note moved. Reopen Job Details to refresh.\":(e.message||\"Unable to move note.\");}\n        finally{transferBusy=false;move.disabled=transferred;}\n      });\n      move.style.cssText=\"display:block;width:100%;margin-top:8px;padding:8px;min-height:40px;\";\n    }} older.hidden=rows.length>=(count??rows.length);}\n    noteReloaders[table]=()=>load(true);\n    const initialLoad=async()=>{if(!box.open||loaded||busy||!current())return;busy=true;save.disabled=true;try{await load(true);}catch(e){if(current())msg.textContent=e.message||\"Unable to load notes.\";}finally{busy=false;save.disabled=false;}};box.addEventListener(\"toggle\",initialLoad);void initialLoad();\n  }\n  section(\"Open Notes\",\"gw_job_notes\",\"gw_add_job_note\");\n  if ([\"owner\",\"office\"].includes(currentWorkRole)) section(\"Office \/ Owner Notes\",\"gw_job_private_notes\",\"gw_add_job_private_note\");\n}\n\n\nconst preparationDashboard = document.createElement(\"section\");\npreparationDashboard.id = \"gw-preparation-dashboard\";\npreparationDashboard.hidden = true;\npreparationDashboard.style.cssText =\n  \"padding:16px;margin:12px 0 20px;border:1px solid #cbd5e1;border-radius:8px;\";\nconst preparationDashboardTitle = document.createElement(\"h3\");\npreparationDashboardTitle.textContent = \"Site Preparation Dashboard\";\nconst preparationDashboardContent = document.createElement(\"div\");\nconst editPreparationButton = preparationButton.cloneNode(false);\neditPreparationButton.id = \"gw-edit-preparation\";\neditPreparationButton.type = \"button\";\neditPreparationButton.textContent = \"Edit Site Preparation\";\neditPreparationButton.hidden = true;\neditPreparationButton.style.cssText = \"width:100%;margin-top:12px;\";\npreparationDashboard.append(preparationDashboardTitle, preparationDashboardContent, editPreparationButton);\n\nconst measurementDashboardGroups = [\n  [\"Measurement & design\", [\n    [\"measured_by\", \"Measured by\"], [\"measurement_date\", \"Measurement date\"],\n    [\"project_area\", \"Project area\"], [\"material\", \"Material\"],\n    [\"edge\", \"Edge\"], [\"sink_type\", \"Sink type\"],\n    [\"sink_model\", \"Sink model\"], [\"stove_type\", \"Stove type\"],\n    [\"faucet\", \"Faucet\"], [\"backsplash\", \"Backsplash\"],\n    [\"seam_required\", \"Seam required\"]\n  ]],\n  [\"Field notes\", [[\"field_notes\", \"Notes\"]]]\n];\nconst preparationDashboardGroups = [\n  [\"Water & plumbing\", [\n    [\"water_shutoff_condition\", \"Water shutoff condition\"],\n    [\"water_shutoff_replace\", \"Replace water shutoff\"],\n    [\"faucet_condition\", \"Faucet condition\"],\n    [\"plumbing_modification\", \"Plumbing modification\"],\n    [\"plumbing_notes\", \"Plumbing notes\"]\n  ]],\n  [\"Electrical, mirrors & walls\", [\n    [\"electrical_modification\", \"Electrical modification\"],\n    [\"outlet_issue\", \"Outlet issue\"], [\"electrical_notes\", \"Electrical notes\"],\n    [\"mirror_removal\", \"Mirror removal\"], [\"wall_condition\", \"Wall condition\"],\n    [\"wall_work_required\", \"Wall work required\"]\n  ]],\n  [\"Floor & access\", [\n    [\"floor_type\", \"Floor type\"], [\"floor_protection_required\", \"Floor protection required\"],\n    [\"floor_protection_type\", \"Floor protection type\"],\n    [\"protection_notes\", \"Protection notes\"],\n    [\"access_condition\", \"Access condition\"], [\"stairs_required\", \"Stairs required\"],\n    [\"special_access_notes\", \"Special access notes\"]\n  ]],\n  [\"Tools & parts\", [\n    [\"special_tools_required\", \"Special tools required\"],\n    [\"special_tools_list\", \"Special tools list\"],\n    [\"special_parts_required\", \"Special parts required\"],\n    [\"special_parts_list\", \"Special parts list\"]\n  ]],\n  [\"Installer handoff\", [\n    [\"installer_notes\", \"Installer notes\"], [\"prepared_by\", \"Prepared by\"],\n    [\"preparation_complete\", \"Preparation complete\"],\n    [\"installer_reviewed\", \"Installer reviewed\"],\n    [\"installer_reviewed_by\", \"Installer reviewed by\"],\n    [\"ready_for_install\", \"Ready for installation\"]\n  ]]\n];\n\nfunction renderWorkSummary(container, savedRow, groups, emptyText) {\n  container.replaceChildren();\n  if (!savedRow) {\n    const p = document.createElement(\"p\");\n    p.textContent = emptyText;\n    container.appendChild(p);\n    return;\n  }\n  for (const [heading, fields] of groups) {\n    const section = document.createElement(\"section\");\n    const title = document.createElement(\"h4\");\n    title.textContent = heading;\n    section.appendChild(title);\n    const grid = document.createElement(\"div\");\n    grid.style.cssText =\n      \"display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,220px),1fr));gap:10px;margin-bottom:16px;\";\n    for (const [column, label] of fields) {\n      const cell = document.createElement(\"div\");\n      cell.style.cssText =\n        \"padding:10px;border:1px solid #e0e8f2;border-radius:6px;background:#f8fbff;min-width:0;\";\n      const name = document.createElement(\"strong\");\n      name.textContent = label;\n      name.style.display = \"block\";\n      const value = document.createElement(\"div\");\n      const raw = savedRow[column];\n      if (container === measurementDashboardContent && (raw == null || raw === \"\")) continue;\n      if (column === \"field_notes\") cell.style.gridColumn = \"1 \/ -1\";\n      value.textContent = typeof raw === \"boolean\" ? (raw ? \"Yes\" : \"No\") :\n        (raw === null || raw === undefined || raw === \"\" ? \"\u2014\" : String(raw));\n      value.style.cssText = \"white-space:pre-wrap;overflow-wrap:anywhere;margin-top:4px;\";\n\n      \/\/ Translate only the approved natural-language note fields.\n      \/\/ Names, addresses, Job IDs, materials, models, measurements, dates,\n      \/\/ money, filenames, and all other job data remain untouched.\n      if (GW_SAFE_WORK_NOTE_COLUMNS.has(column) &&\n          raw !== null && raw !== undefined && String(raw) !== \"\") {\n        value.dataset.gwSafeNoteSource = String(raw);\n        translateSafeWorkNoteElement(value);\n      }\n\n      cell.append(name, value);\n      grid.appendChild(cell);\n    }\n    if (grid.children.length) { section.appendChild(grid); container.appendChild(section); }\n  }\n}\nfunction canEditMeasurement(jobId) {\n  return !!jobId && currentWorkJobId === jobId &&\n    (currentWorkRole === \"owner\" || currentWorkRole === \"office\" || currentWorkRole === \"project_manager\");\n}\nfunction canEditPreparation(jobId) {\n  return !!jobId && currentWorkJobId === jobId &&\n    (currentWorkRole === \"owner\" || currentWorkRole === \"project_manager\");\n}\nfunction setWorkFormEditable(form, allowed) {\n  form.querySelectorAll(\"input, textarea, select, button\").forEach(function (control) {\n    control.disabled = !allowed;\n  });\n}\nfunction resetWorkDashboards() {\n  gw92ClearNotes();\n  currentWorkRole = null;\n  currentWorkJobId = null;\n  measurementLoadOK = false;\n  preparationLoadOK = false;\n  measurementButton.hidden = true;\n  preparationButton.hidden = true;\n  measurementDashboard.hidden = true;\n  preparationDashboard.hidden = true;\n  measurementForm.hidden = true;\n  preparationForm.hidden = true;\n  editMeasurementButton.hidden = true;\n  editPreparationButton.hidden = true;\n  gw10State=null; gw10Editor.hidden=true; gw10Editor.replaceChildren();gwRE173MeasureDrop.open=false;gwRE173ReadOnly.hidden=false;gwRE173ReadOnly.replaceChildren();\n  measurementDashboardContent.replaceChildren();\n  preparationDashboardContent.replaceChildren();\n  setWorkFormEditable(measurementForm, false);\n  setWorkFormEditable(preparationForm, false);\n  saveMeasurement.hidden = true;\n  savePreparation.hidden = true;\n  measurementMessage.textContent = \"\";\n  preparationMessage.textContent = \"\";\n}\nfunction configureWorkDashboards(role, jobId) {\n  currentWorkRole = role;\n  currentWorkJobId = jobId;\n\n  \/\/ VIEW and EDIT are deliberately separate permissions.\n  \/\/ All active Portal roles may view the saved read-only dashboards.\n  \/\/ Only Owner \/ Project Manager may edit or save.\n  const viewAllowed = !!jobId && [\n    \"owner\", \"office\", \"project_manager\", \"installer\", \"fabricator\"\n  ].includes(role);\n\n  const measurementEditAllowed =\n    canEditMeasurement(jobId) && measurementLoadOK;\n\n  const preparationEditAllowed =\n    canEditPreparation(jobId) && preparationLoadOK;\n\n  \/\/ Keep the main read-only entry buttons available to every approved role.\n  measurementButton.hidden = !viewAllowed;\n  preparationButton.hidden = !viewAllowed;\n\n  setWorkFormEditable(measurementForm, measurementEditAllowed);\n  setWorkFormEditable(preparationForm, preparationEditAllowed);\n\n  editMeasurementButton.hidden = !measurementEditAllowed;\n  editPreparationButton.hidden = !preparationEditAllowed;\n\n  saveMeasurement.hidden = !measurementEditAllowed;\n  savePreparation.hidden = !preparationEditAllowed;\n  saveMeasurement.disabled = !measurementEditAllowed;\n  savePreparation.disabled = !preparationEditAllowed;\n\n  \/\/ Forms stay closed by default. Read-only dashboards open from the main buttons.\n  measurementForm.hidden = true;\n  preparationForm.hidden = true;\n}\neditMeasurementButton.addEventListener(\"click\", function () {\n  if (dashboard.hidden || !canEditMeasurement(currentWorkJobId)) {\n    alert(\"Final Measurement editing is not available for this account and job.\");\n    return;\n  }\n  if (!measurementLoadOK || !gw10State || gw10State.id !== currentWorkJobId) {\n    alert(\"Final Measurement is not loaded. Please reopen this job and try again.\");\n    return;\n  }\n  gw10OpenEditor();\n});\neditPreparationButton.addEventListener(\"click\", function () {\n  if (!dashboard.hidden && canEditPreparation(currentWorkJobId) && preparationLoadOK)\n    preparationForm.hidden = !preparationForm.hidden;\n});\n\n\nsavePreparation.addEventListener(\"click\", async function () {\n  const jobId = jobIdInput.value.trim();\n\n     if (!client || dashboard.hidden || !jobId || !canEditPreparation(jobId) ||\n       !preparationLoadOK || preparationForm.hidden) {\n     preparationMessage.textContent =\n       \"Site Preparation editing is not available for this account and job.\";\n     return;\n  }\n\n   savePreparation.disabled = true;\n  preparationMessage.textContent = \"Saving...\";\n\n  try {\n    const { data: auth, error: authError } =\n      await client.auth.getUser();\n\n    if (authError || !auth.user) {\n      preparationMessage.textContent = \"Please log in again.\";\n      return;\n    }\nconst { data: existing, error: lookupError } = await client\n  .from(\"site_preparation\")\n  .select(\"id\")\n  .eq(\"job_id\", jobId)\n  .order(\"id\", { ascending: false })\n  .limit(1)\n  .maybeSingle();\n\nif (lookupError) throw lookupError;\n const preparationData = {\n        job_id: jobId,\n        water_shutoff_condition:\n          document.getElementById(\"gw-water-condition\").value.trim(),\n        water_shutoff_replace:\n          document.getElementById(\"gw-water-replace\").checked,\n        faucet_condition:\n          document.getElementById(\"gw-faucet-condition\").value.trim(),\n        plumbing_modification:\n          document.getElementById(\"gw-plumbing-modification\").checked,\n        plumbing_notes:\n  document.getElementById(\"gw-plumbing-notes\").value.trim(),\n\nelectrical_modification:\n  document.getElementById(\"gw-electrical-modification\").checked,\noutlet_issue:\n  document.getElementById(\"gw-outlet-issue\").checked,\nelectrical_notes:\n  document.getElementById(\"gw-electrical-notes\").value.trim(),\nmirror_removal:\n  document.getElementById(\"gw-mirror-removal\").value,\n\nwall_condition:\n  document.getElementById(\"gw-wall-condition\").value.trim(),\nwall_work_required:\n  document.getElementById(\"gw-wall-work-required\").checked,\n\nfloor_type:\n  document.getElementById(\"gw-floor-type\").value.trim(),\nfloor_protection_required:\n  document.getElementById(\"gw-floor-protection-required\").checked,\nfloor_protection_type:\n  document.getElementById(\"gw-floor-protection-type\").value.trim(),\n protection_notes:\n  document.getElementById(\"gw-protection-notes\").value.trim(),\n\naccess_condition:\n  document.getElementById(\"gw-access-condition\").value.trim(),\nstairs_required:\n  document.getElementById(\"gw-stairs-required\").checked,\nspecial_access_notes:\n  document.getElementById(\"gw-special-access-notes\").value.trim(),\n\nspecial_tools_required:\n  document.getElementById(\"gw-special-tools-required\").checked,\nspecial_tools_list:\n  document.getElementById(\"gw-special-tools-list\").value.trim(),\nspecial_parts_required:\n  document.getElementById(\"gw-special-parts-required\").checked,\nspecial_parts_list:\n  document.getElementById(\"gw-special-parts-list\").value.trim(),\n\ninstaller_notes:\n  document.getElementById(\"gw-installer-notes\").value.trim(),\nprepared_by:\n  document.getElementById(\"gw-prepared-by\").value.trim(),\npreparation_complete:\n  document.getElementById(\"gw-preparation-complete\").checked,\ninstaller_reviewed:\n  document.getElementById(\"gw-installer-reviewed\").checked,\ninstaller_reviewed_by:\n  document.getElementById(\"gw-installer-reviewed-by\").value.trim(),\nready_for_install:\n  document.getElementById(\"gw-ready-for-install\").checked\n};\n\nconst { data: savedRow, error } = existing\n   ? await client\n       .from(\"site_preparation\")\n       .update(preparationData)\n       .eq(\"id\", existing.id)\n       .eq(\"job_id\", jobId)\n       .select(\"*\").maybeSingle()\n   : await client\n       .from(\"site_preparation\")\n       .insert(preparationData)\n       .select(\"*\").maybeSingle();\n     if (error) throw error;\n     if (!savedRow) throw new Error(\"No preparation was saved. Check database permissions.\");\n     if (canEditPreparation(jobId)) {\n       renderWorkSummary(preparationDashboardContent, savedRow, preparationDashboardGroups,\n         \"No Site Preparation recorded yet.\");\n       preparationMessage.textContent = \"Site Preparation saved successfully!\";\n       preparationForm.hidden = true;\n     }\n     } catch (error) {\n     if (canEditPreparation(jobId))\n       preparationMessage.textContent = \"Save failed: \" + error.message;\n   } finally {\n     savePreparation.disabled = !canEditPreparation(jobId) || !preparationLoadOK;\n  }\n});\nconst reviewButton =\n  document.getElementById(\"gw-installer-review-button\");\n\/\/ Installer Review has been retired from the Portal UI.\n\/\/ Keep legacy elements\/data intact so this change cannot damage stored review records.\nreviewButton.hidden = true;\nreviewButton.style.display = \"none\";\n\/\/ Keep the Accounting button in the existing Portal flow.\nreviewButton.insertAdjacentElement(\"afterend\", accountingToggle);\naccountingToggle.insertAdjacentElement(\"afterend\", accountingPanel);\n\nconst reviewForm =\n  document.getElementById(\"gw-installer-review-form\");\nreviewForm.hidden = true;\nreviewForm.style.display = \"none\";\n\n\/\/ Legacy owner review overview is also retired from the Portal UI. Access to rows is enforced by Supabase RLS.\nconst allReviewsPanel = document.createElement(\"section\");\nallReviewsPanel.id = \"gw-all-installer-reviews\";\nallReviewsPanel.hidden = true;\nallReviewsPanel.style.marginTop = \"20px\";\nallReviewsPanel.style.padding = \"16px\";\nallReviewsPanel.style.border = \"1px solid #ccd6e0\";\nallReviewsPanel.style.borderRadius = \"8px\";\nconst allReviewsHeading = document.createElement(\"h3\");\nallReviewsHeading.textContent = \"All Installer Reviews (Owner Only)\";\nconst allReviewsContent = document.createElement(\"div\");\nallReviewsPanel.append(allReviewsHeading, allReviewsContent);\nreviewForm.insertAdjacentElement(\"afterend\", allReviewsPanel);\nallReviewsPanel.insertAdjacentElement(\"afterend\", accountingToggle);\naccountingToggle.insertAdjacentElement(\"afterend\", accountingPanel);\n\n\/\/ JOB STATUS is shown only to Owner \/ Project Manager.\n\/\/ Intermediate stages use gw_set_job_status. Final \"Completed\" still uses\n\/\/ gw_mark_job_completed so completed_at and the 30-day invoice due date remain atomic.\nconst completionButton = reviewButton.cloneNode(false);\ncompletionButton.id = \"gw-job-status-toggle\";\ncompletionButton.type = \"button\";\ncompletionButton.textContent = \"Job Status\";\ncompletionButton.hidden = true;\ncompletionButton.disabled = true;\ncompletionButton.style.width = \"100%\";\ncompletionButton.style.marginBottom = \"8px\";\ncompletionButton.setAttribute(\"aria-expanded\", \"false\");\n\nconst jobStatusPanel = document.createElement(\"section\");\njobStatusPanel.id = \"gw-job-status-panel\";\njobStatusPanel.hidden = true;\njobStatusPanel.style.cssText =\n  \"padding:14px;margin:0 0 12px;border:1px solid #cbd5e1;border-radius:8px;\";\n\nconst jobStatusHeading = document.createElement(\"h3\");\njobStatusHeading.textContent = \"Job Status\";\n\nconst jobStatusCurrent = document.createElement(\"p\");\njobStatusCurrent.id = \"gw-job-status-current\";\n\nconst jobStatusLabel = document.createElement(\"label\");\njobStatusLabel.htmlFor = \"gw-job-status-select\";\njobStatusLabel.textContent = \"Change status\";\njobStatusLabel.style.cssText = \"display:block;margin:10px 0 6px;font-weight:600;\";\n\nconst jobStatusSelect = document.createElement(\"select\");\njobStatusSelect.id = \"gw-job-status-select\";\njobStatusSelect.style.cssText = \"width:100%;max-width:460px;padding:10px;\";\n\n[\n  \"Approved\",\n  \"Final Measurement\",\n  \"Fabrication\",\n  \"Ready for Installation\",\n  \"Completed\"\n].forEach(function (stage) {\n  const option = document.createElement(\"option\");\n  option.value = stage;\n  option.textContent = stage;\n  jobStatusSelect.appendChild(option);\n});\n\nconst jobStatusSave = document.createElement(\"button\");\njobStatusSave.type = \"button\";\njobStatusSave.id = \"gw-job-status-save\";\njobStatusSave.textContent = \"Save Status\";\njobStatusSave.style.cssText = \"display:block;width:100%;margin:12px 0 6px;\";\n\nconst completionMessage = document.createElement(\"p\");\ncompletionMessage.id = \"gw-completion-message\";\ncompletionMessage.setAttribute(\"role\", \"status\");\ncompletionMessage.hidden = true;\ncompletionMessage.style.whiteSpace = \"pre-line\";\n\njobStatusPanel.append(\n  jobStatusHeading, jobStatusCurrent, jobStatusLabel,\n  jobStatusSelect, jobStatusSave, completionMessage\n);\n\nallReviewsPanel.insertAdjacentElement(\"afterend\", completionButton);\ncompletionButton.insertAdjacentElement(\"afterend\", jobStatusPanel);\n\/\/ Restore the pre-existing order: Installer Review, owner overview,\n\/\/ Job Status, Office Accounting.\njobStatusPanel.insertAdjacentElement(\"afterend\", accountingToggle);\naccountingToggle.insertAdjacentElement(\"afterend\", accountingPanel);\n\n\/\/ OWNER-ONLY JOB ASSIGNMENTS. Backend RLS and the owner-only roster RPC\n\/\/ enforce permissions independently of this interface.\nconst assignmentToggle = document.createElement(\"button\");\nassignmentToggle.id = \"gw-assignment-toggle\";\nassignmentToggle.type = \"button\";\nassignmentToggle.textContent = \"Assign Installers (Owner Only)\";\nassignmentToggle.hidden = true;\nassignmentToggle.style.cssText = \"width:100%;margin-bottom:12px;\";\nassignmentToggle.setAttribute(\"aria-expanded\", \"false\");\nconst assignmentPanel = document.createElement(\"section\");\nassignmentPanel.id = \"gw-assignment-panel\";\nassignmentPanel.hidden = true;\nassignmentPanel.style.cssText =\n  \"margin:12px 0 20px;padding:16px;border:1px solid #cbd5e1;border-radius:8px;\";\nconst assignmentHeading = document.createElement(\"h3\");\nassignmentHeading.textContent = \"Installer Assignments (Owner Only)\";\nconst assignmentList = document.createElement(\"div\");\nconst assignmentControls = document.createElement(\"div\");\nconst assignmentMessage = document.createElement(\"p\");\nassignmentMessage.setAttribute(\"role\", \"status\");\nassignmentPanel.append(assignmentHeading, assignmentList, assignmentControls, assignmentMessage);\ncompletionMessage.insertAdjacentElement(\"afterend\", assignmentToggle);\nassignmentToggle.insertAdjacentElement(\"afterend\", assignmentPanel);\nassignmentPanel.insertAdjacentElement(\"afterend\", accountingToggle);\naccountingToggle.insertAdjacentElement(\"afterend\", accountingPanel);\n\nlet assignmentJobId = null;\nlet assignmentRequestId = 0;\nlet assignmentBusy = false;\nfunction resetOwnerAssignments() {\n  assignmentRequestId++;\n  assignmentJobId = null;\n  assignmentBusy = false;\n  assignmentToggle.hidden = true;\n  assignmentToggle.setAttribute(\"aria-expanded\", \"false\");\n  assignmentPanel.hidden = true;\n  assignmentList.replaceChildren();\n  assignmentControls.replaceChildren();\n  assignmentMessage.textContent = \"\";\n}\nfunction configureOwnerAssignments(jobId) {\n  assignmentJobId = jobId;\n  assignmentToggle.hidden = false;\n  assignmentPanel.hidden = true;\n  assignmentToggle.setAttribute(\"aria-expanded\", \"false\");\n  assignmentMessage.textContent = \"\";\n}\nfunction ownerAssignmentIsCurrent(jobId, requestId) {\n  return !!client && !dashboard.hidden && !assignmentToggle.hidden &&\n    !assignmentPanel.hidden && assignmentJobId === jobId &&\n    jobIdInput.value.trim() === jobId &&\n    (requestId === undefined || requestId === assignmentRequestId);\n}\nasync function loadOwnerAssignments(jobId) {\n  const requestId = ++assignmentRequestId;\n  assignmentList.textContent = \"Loading assigned installers...\";\n  assignmentControls.replaceChildren();\n  assignmentMessage.textContent = \"\";\n  try {\n    \/\/ Function returns only the Installer display name and ID, and rejects non-owners.\n    const { data: installers, error: rosterError } =\n      await client.rpc(\"gw_owner_list_installers\");\n    if (rosterError) throw rosterError;\n    if (!ownerAssignmentIsCurrent(jobId, requestId)) return false;\n    const { data: assignments, error: assignmentError } = await client\n      .from(\"job_assignments\")\n      .select(\"id, job_id, user_id\")\n      .eq(\"job_id\", jobId)\n      .order(\"id\", { ascending: true });\n    if (assignmentError) throw assignmentError;\n    if (!ownerAssignmentIsCurrent(jobId, requestId)) return false;\n    const installerList = installers || [];\n    const assignedList = assignments || [];\n    const installerNames = new Map(installerList.map(function (installer) {\n      return [installer.user_id, installer.display_name || \"Unnamed installer\"];\n    }));\n    assignmentList.replaceChildren();\n    const count = document.createElement(\"p\");\n    count.textContent = \"Job \" + jobId + \" \u2014 \" + assignedList.length + \" assigned installer(s).\";\n    assignmentList.appendChild(count);\n    if (!assignedList.length) {\n      const empty = document.createElement(\"p\");\n      empty.textContent = \"No installers assigned yet.\";\n      assignmentList.appendChild(empty);\n    }\n    for (const item of assignedList) {\n      const row = document.createElement(\"div\");\n      row.style.cssText = \"padding:10px 0;border-bottom:1px solid #e3e8ed;\";\n      const name = installerNames.get(item.user_id) ||\n        \"Employee \" + item.user_id.slice(0, 8) + \" (not in installer roster)\";\n      const label = document.createElement(\"span\");\n      label.textContent = name + \" \";\n      const removeButton = document.createElement(\"button\");\n      removeButton.type = \"button\";\n      removeButton.textContent = \"Remove \" + name;\n      removeButton.style.marginLeft = \"10px\";\n      removeButton.addEventListener(\"click\", async function () {\n        if (!ownerAssignmentIsCurrent(jobId) || assignmentBusy) return;\n if (!window.confirm(\n  \"Remove \" + name + \" from job \" + jobId +\n  \"? They can still view the job by Job ID.\"\n)) return;\n        assignmentBusy = true;\n        removeButton.disabled = true;\n        assignmentMessage.textContent = \"Removing assignment...\";\n        try {\n          const { data: deleted, error } = await client.from(\"job_assignments\")\n            .delete().eq(\"id\", item.id).eq(\"job_id\", jobId)\n            .eq(\"user_id\", item.user_id).select(\"id\").maybeSingle();\n          if (error) throw error;\n          if (!deleted) throw new Error(\"Assignment not removed. Check permissions and refresh.\");\n          if (ownerAssignmentIsCurrent(jobId)) {\n            const refreshed = await loadOwnerAssignments(jobId);\n            if (refreshed && ownerAssignmentIsCurrent(jobId))\n              assignmentMessage.textContent = name + \" removed from \" + jobId + \".\";\n          }\n        } catch (error) {\n          if (ownerAssignmentIsCurrent(jobId))\n            assignmentMessage.textContent = \"Remove failed: \" + error.message;\n        } finally {\n          if (ownerAssignmentIsCurrent(jobId)) assignmentBusy = false;\n          removeButton.disabled = false;\n        }\n      });\n      row.append(label, removeButton);\n      assignmentList.appendChild(row);\n    }\n    const assignedUserIds = new Set(assignedList.map((item) => item.user_id));\n    const available = installerList.filter((installer) =>\n      !assignedUserIds.has(installer.user_id));\n    assignmentControls.replaceChildren();\n    if (!available.length) {\n      const none = document.createElement(\"p\");\n      none.textContent = \"No additional installer accounts available to assign.\";\n      assignmentControls.appendChild(none);\n    } else {\n      const selectLabel = document.createElement(\"label\");\n      selectLabel.textContent = \"Choose an installer to assign\";\n      selectLabel.style.display = \"block\";\n      const select = document.createElement(\"select\");\n      select.style.cssText = \"width:100%;max-width:400px;margin:8px 0;\";\n      const prompt = document.createElement(\"option\");\n      prompt.value = \"\";\n      prompt.textContent = \"Select an installer\";\n      select.appendChild(prompt);\n      for (const installer of available) {\n        const option = document.createElement(\"option\");\n        option.value = installer.user_id;\n        option.textContent = installer.display_name || \"Installer \" + installer.user_id.slice(0, 8);\n        select.appendChild(option);\n      }\n      const addButton = document.createElement(\"button\");\n      addButton.type = \"button\";\n      addButton.textContent = \"Assign Selected Installer\";\n      addButton.disabled = true;\n      select.addEventListener(\"change\", function () {\n        addButton.disabled = !select.value || assignmentBusy;\n      });\n      addButton.addEventListener(\"click\", async function () {\n        const userId = select.value;\n        if (!ownerAssignmentIsCurrent(jobId) || assignmentBusy ||\n            !available.some((installer) => installer.user_id === userId)) return;\n        assignmentBusy = true;\n        addButton.disabled = true;\n        select.disabled = true;\n        assignmentMessage.textContent = \"Assigning installer...\";\n        try {\n          const { data: added, error } = await client.from(\"job_assignments\")\n            .insert({ job_id: jobId, user_id: userId })\n            .select(\"id\").maybeSingle();\n          if (error) throw error;\n          if (!added) throw new Error(\"Assignment was not saved. Check permissions.\");\n          if (ownerAssignmentIsCurrent(jobId)) {\n            const refreshed = await loadOwnerAssignments(jobId);\n            if (refreshed && ownerAssignmentIsCurrent(jobId))\n              assignmentMessage.textContent = \"Installer assigned to \" + jobId + \".\";\n          }\n        } catch (error) {\n          if (ownerAssignmentIsCurrent(jobId))\n            assignmentMessage.textContent = \"Assign failed: \" + error.message;\n        } finally {\n          if (ownerAssignmentIsCurrent(jobId)) assignmentBusy = false;\n          select.disabled = false;\n          if (ownerAssignmentIsCurrent(jobId)) addButton.disabled = !select.value;\n        }\n      });\n      selectLabel.appendChild(select);\n      assignmentControls.append(selectLabel, addButton);\n    }\n    return true;\n  } catch (error) {\n    if (ownerAssignmentIsCurrent(jobId, requestId)) {\n      assignmentList.textContent = \"Unable to load installer assignments.\";\n      assignmentControls.replaceChildren();\n      assignmentMessage.textContent = error.message;\n    }\n    return false;\n  }\n}\nassignmentToggle.addEventListener(\"click\", async function () {\n  const jobId = assignmentJobId;\n  if (!jobId || dashboard.hidden || assignmentToggle.hidden ||\n      jobIdInput.value.trim() !== jobId) return;\n  assignmentPanel.hidden = !assignmentPanel.hidden;\n  assignmentToggle.setAttribute(\"aria-expanded\", String(!assignmentPanel.hidden));\n  if (assignmentPanel.hidden) assignmentRequestId++;\n  else await loadOwnerAssignments(jobId);\n});\n\nlet completionJobId = null;\nlet completionRequestId = 0;\nlet currentJobStatus = \"Approved\";\nlet currentCompletedAt = null;\n\nconst allowedJobStatuses = [\n  \"Approved\",\n  \"Final Measurement\",\n  \"Fabrication\",\n  \"Ready for Installation\",\n  \"Completed\"\n];\n\nfunction resetCompletion() {\n  completionRequestId++;\n  completionJobId = null;\n  currentJobStatus = \"Approved\";\n  currentCompletedAt = null;\n  completionButton.hidden = true;\n  completionButton.disabled = true;\n  completionButton.textContent = \"Job Status\";\n  completionButton.setAttribute(\"aria-expanded\", \"false\");\n  jobStatusPanel.hidden = true;\n  jobStatusSelect.disabled = false;\n  jobStatusSave.disabled = false;\n  jobStatusSelect.value = \"Approved\";\n  jobStatusCurrent.textContent = \"\";\n  completionMessage.hidden = true;\n  completionMessage.textContent = \"\";\n}\n\nfunction configureCompletion(jobId, jobStatus, completedAt) {\n  completionJobId = jobId;\n  currentCompletedAt = completedAt || null;\n  currentJobStatus = allowedJobStatuses.includes(jobStatus)\n    ? jobStatus\n    : (completedAt ? \"Completed\" : \"Approved\");\n\n  completionButton.hidden = false;\n  completionButton.disabled = false;\n  completionButton.textContent = \"Job Status \u2014 \" + currentJobStatus;\n  completionButton.setAttribute(\"aria-expanded\", \"false\");\n  jobStatusPanel.hidden = true;\n  completionMessage.hidden = false;\n  jobStatusSelect.value = currentJobStatus;\n  jobStatusCurrent.textContent = \"Current status: \" + currentJobStatus;\n\n  if (currentCompletedAt || currentJobStatus === \"Completed\") {\n    currentJobStatus = \"Completed\";\n    jobStatusSelect.value = \"Completed\";\n    jobStatusSelect.disabled = true;\n    jobStatusSave.disabled = true;\n    completionButton.textContent = \"Job Status \u2014 Completed\";\n    jobStatusCurrent.textContent = \"Current status: Completed\";\n    completionMessage.textContent =\n      \"This job is completed. Completion cannot be moved back to an earlier stage.\";\n  } else {\n    jobStatusSelect.disabled = false;\n    jobStatusSave.disabled = false;\n    completionMessage.textContent =\n      \"Owner \/ Office \/ Project Manager only. Choose the job's current stage and press Save Status.\";\n  }\n}\n\ncompletionButton.addEventListener(\"click\", function () {\n  const jobId = completionJobId;\n  if (!client || dashboard.hidden || !jobId ||\n      jobIdInput.value.trim() !== jobId || completionButton.disabled) return;\n  jobStatusPanel.hidden = !jobStatusPanel.hidden;\n  completionButton.setAttribute(\"aria-expanded\", String(!jobStatusPanel.hidden));\n});\n\nasync function refreshVisibleJobStatus(jobId) {\n  const { data: updatedJob, error: jobError } = await client\n    .from(\"Jobs\")\n    .select(\"job_id, customer_name, customer_phone, job_address, job_status, completed_at\")\n    .eq(\"job_id\", jobId)\n    .maybeSingle();\n\n  if (jobError || !updatedJob) return null;\n\n  jobResult.textContent =\n    \"Job ID: \" + updatedJob.job_id + \"\\n\" +\n    \"Customer: \" + (updatedJob.customer_name || \"\") + \"\\n\" +\n    \"Phone: \" + (updatedJob.customer_phone || \"\") + \"\\n\" +\n    \"Address: \" + (updatedJob.job_address || \"\") + \"\\n\" +\n    \"Status: \" + (updatedJob.job_status || \"\");\n\n  return updatedJob;\n}\n\njobStatusSave.addEventListener(\"click\", async function () {\n  const jobId = completionJobId;\n  const nextStatus = jobStatusSelect.value;\n\n  if (!client || dashboard.hidden || !jobId ||\n      jobIdInput.value.trim() !== jobId || jobStatusSave.disabled) return;\n\n  if (!allowedJobStatuses.includes(nextStatus)) {\n    completionMessage.textContent = \"Select a valid job status.\";\n    return;\n  }\n\n  if (currentCompletedAt || currentJobStatus === \"Completed\") {\n    completionMessage.textContent =\n      \"This job is already completed and cannot be moved back.\";\n    jobStatusSelect.value = \"Completed\";\n    return;\n  }\n\n  if (nextStatus === currentJobStatus) {\n    completionMessage.textContent = \"Status is already \" + currentJobStatus + \".\";\n    return;\n  }\n\n  if (!window.confirm(\n    \"Change job \" + jobId + \" status from \" + currentJobStatus +\n    \" to \" + nextStatus + \"?\"\n  )) {\n    jobStatusSelect.value = currentJobStatus;\n    return;\n  }\n\n  const requestId = ++completionRequestId;\n  completionButton.disabled = true;\n  jobStatusSelect.disabled = true;\n  jobStatusSave.disabled = true;\n  completionMessage.textContent = \"Saving job status...\";\n\n  try {\n    if (nextStatus === \"Completed\") {\n      if (!window.confirm(\n        \"FINAL STEP: Mark job \" + jobId + \" as COMPLETED?\\n\\n\" +\n        \"This permanently records its completion time and sets the invoice due date \" +\n        \"to 30 calendar days after completion. Completion cannot be moved back.\"\n      )) {\n        jobStatusSelect.value = currentJobStatus;\n        return;\n      }\n\n      const { data: dueDate, error } = await client.rpc(\"gw_mark_job_completed\", {\n        p_job_id: jobId\n      });\n      if (error) throw error;\n\n      if (requestId !== completionRequestId || dashboard.hidden ||\n          jobIdInput.value.trim() !== jobId) return;\n\n      const updatedJob = await refreshVisibleJobStatus(jobId);\n      currentJobStatus = \"Completed\";\n      currentCompletedAt = updatedJob?.completed_at || \"completed\";\n      completionButton.textContent = \"Job Status \u2014 Completed\";\n      jobStatusCurrent.textContent = \"Current status: Completed\";\n      jobStatusSelect.value = \"Completed\";\n      jobStatusSelect.disabled = true;\n      jobStatusSave.disabled = true;\n      completionMessage.textContent =\n        \"Job completed. Invoice due date: \" + dueDate + \".\";\n\n      if (!accountingToggle.hidden) {\n        const refreshed = await loadAccounting(jobId);\n        if (!refreshed && requestId === completionRequestId)\n          completionMessage.textContent +=\n            \" Refresh the job to view its updated invoice.\";\n      }\n      return;\n    }\n\n    const { data: savedStatus, error } = await client.rpc(\"gw_set_job_status\", {\n      p_job_id: jobId,\n      p_status: nextStatus\n    });\n    if (error) throw error;\n\n    if (savedStatus !== nextStatus)\n      throw new Error(\"Saved status could not be verified.\");\n\n    if (requestId !== completionRequestId || dashboard.hidden ||\n        jobIdInput.value.trim() !== jobId) return;\n\n    await refreshVisibleJobStatus(jobId);\n    currentJobStatus = nextStatus;\n    completionButton.textContent = \"Job Status \u2014 \" + nextStatus;\n    jobStatusCurrent.textContent = \"Current status: \" + nextStatus;\n    jobStatusSelect.value = nextStatus;\n    completionMessage.textContent = \"Status saved: \" + nextStatus + \".\";\n  } catch (error) {\n    if (requestId !== completionRequestId || dashboard.hidden ||\n        jobIdInput.value.trim() !== jobId) return;\n    completionMessage.textContent =\n      \"Status change failed: \" + error.message +\n      \"\\nNo other Portal section was changed.\";\n    jobStatusSelect.value = currentJobStatus;\n  } finally {\n    if (requestId === completionRequestId && !dashboard.hidden &&\n        jobIdInput.value.trim() === jobId &&\n        currentJobStatus !== \"Completed\" && !currentCompletedAt) {\n      completionButton.disabled = false;\n      jobStatusSelect.disabled = false;\n      jobStatusSave.disabled = false;\n    } else if (currentJobStatus === \"Completed\" || currentCompletedAt) {\n      completionButton.disabled = false;\n    }\n  }\n});\n\nasync function refreshOwnerReviews(jobId, signedInUserId) {\n  allReviewsContent.replaceChildren();\n  allReviewsContent.textContent = \"Loading employee reviews...\";\n  const { data: reviews, error } = await client\n    .from(\"installer_reviews\")\n    .select(\"id, user_id, installer_notes, installer_reviewed, ready_for_install, reviewed_at\")\n    .eq(\"job_id\", jobId)\n    .order(\"id\", { ascending: true });\n  \/\/ Do not display results from a job that is no longer selected.\n  if (dashboard.hidden || jobIdInput.value.trim() !== jobId) return;\n  allReviewsContent.replaceChildren();\n  if (error) {\n    allReviewsContent.textContent = \"Unable to load employee reviews: \" + error.message;\n    return;\n  }\n  if (!reviews || reviews.length === 0) {\n    allReviewsContent.textContent = \"No installer reviews for this job yet.\";\n    return;\n  }\n  for (const review of reviews) {\n    const entry = document.createElement(\"div\");\n    entry.style.padding = \"10px 0\";\n    entry.style.borderBottom = \"1px solid #e3e8ed\";\n    const person = document.createElement(\"strong\");\n    person.textContent = \"User ID: \" + review.user_id +\n      (review.user_id === signedInUserId ? \" (you)\" : \"\");\n    const details = document.createElement(\"p\");\n    details.style.whiteSpace = \"pre-wrap\";\n    details.textContent =\n      \"Notes: \" + (review.installer_notes || \"(none)\") + \"\\n\" +\n      \"Reviewed: \" + (review.installer_reviewed ? \"Yes\" : \"No\") + \"\\n\" +\n      \"Ready for installation: \" + (review.ready_for_install ? \"Yes\" : \"No\") +\n      \"\\nReviewed at: \" + (review.reviewed_at || \"Not confirmed\");\n    entry.append(person, details);\n    allReviewsContent.appendChild(entry);\n  }\n}\n\nreviewButton.addEventListener(\"click\", function () {\n  reviewForm.hidden = !reviewForm.hidden;\n});\nconst saveReview =\n  document.getElementById(\"gw-save-review\");\n\nconst reviewMessage =\n  document.getElementById(\"gw-review-message\");\n\nsaveReview.addEventListener(\"click\", async function () {\n  const jobId = jobIdInput.value.trim();\n\n  if (!client || dashboard.hidden || !jobId) {\n    reviewMessage.textContent = \"Please search for a job first.\";\n    return;\n  }\n\n  saveReview.disabled = true;\n  reviewMessage.textContent = \"Saving...\";\n\n  try {\n    const { data: auth, error: authError } =\n      await client.auth.getUser();\n\n    if (authError || !auth.user) {\n      reviewMessage.textContent = \"Please log in again.\";\n      return;\n    }\n\n    const record = {\n      job_id: jobId,\n      user_id: auth.user.id,\n      installer_notes:\n        document.getElementById(\"gw-review-notes\").value.trim(),\n      installer_reviewed:\n        document.getElementById(\"gw-review-confirmed\").checked,\n      ready_for_install:\n        document.getElementById(\"gw-review-ready\").checked,\n      reviewed_at:\n        document.getElementById(\"gw-review-confirmed\").checked\n          ? new Date().toISOString()\n          : null\n    };\n\n    const { data: existing, error: lookupError } = await client\n      .from(\"installer_reviews\")\n      .select(\"id\")\n      .eq(\"job_id\", jobId)\n      .eq(\"user_id\", auth.user.id)\n      .limit(1)\n      .maybeSingle();\n\n    if (lookupError) throw lookupError;\n\n    const { error } = existing\n      ? await client\n          .from(\"installer_reviews\")\n          .update(record)\n          .eq(\"id\", existing.id)\n      : await client\n          .from(\"installer_reviews\")\n          .insert(record);\n\n    if (error) throw error;\n\n    reviewMessage.textContent =\n      \"Installer Review saved successfully!\";\n     if (!allReviewsPanel.hidden && jobIdInput.value.trim() === jobId) {\n       await refreshOwnerReviews(jobId, auth.user.id);\n     }\n  } catch (error) {\n    reviewMessage.textContent =\n      \"Save failed: \" + error.message;\n  } finally {\n    saveReview.disabled = false;\n  }\n});\nconst photoButton =\n  document.getElementById(\"gw-job-photos\");\n\nconst photoForm =\n  document.getElementById(\"gw-photo-form\");\n\nphotoButton.addEventListener(\"click\", function () {\n  photoForm.hidden = !photoForm.hidden;\n});\nconst uploadPhoto = document.getElementById(\"gw-upload-photo\");\nconst photoMessage = document.getElementById(\"gw-photo-message\");\n\n\/\/ V3: one visible photo picker plus a persistent per-job pending upload queue.\n\/\/ Some iPhone picker routes return only ONE photo, even with `multiple`.\n\/\/ Retain the File objects across repeated selections; upload the whole queue later.\nconst photoFileInput = document.getElementById(\"gw-photo-file\");\nconst originalPhotoLabel = photoForm.querySelector('label[for=\"gw-photo-file\"]');\n\/\/ Hide the old single-photo\/camera picker, which users could accidentally choose.\n\/\/ A visible multi-photo input below still offers Photo Library \/ Take Photo on iOS.\nphotoFileInput.hidden = true;\nphotoFileInput.removeAttribute(\"capture\");\nif (originalPhotoLabel) originalPhotoLabel.hidden = true;\nconst photoLibraryLabel = document.createElement(\"label\");\nphotoLibraryLabel.htmlFor = \"gw-photo-library-file\";\nphotoLibraryLabel.textContent = \"Choose Photos (Photo Library \/ Camera) \u2014 V3\";\nphotoLibraryLabel.style.cssText = \"display:block;font-weight:600;margin:12px 0 6px;\";\nconst photoLibraryInput = document.createElement(\"input\");\nphotoLibraryInput.id = \"gw-photo-library-file\";\nphotoLibraryInput.type = \"file\";\nphotoLibraryInput.accept = \"image\/*\";\nphotoLibraryInput.multiple = true;\n\/\/ Never use capture: it can send iPhone directly to the single-shot camera.\nphotoLibraryInput.removeAttribute(\"capture\");\nphotoLibraryInput.style.cssText = \"display:block;box-sizing:border-box;width:100%;max-width:100%;margin-bottom:6px;\";\nconst photoLibraryHelp = document.createElement(\"p\");\nphotoLibraryHelp.textContent =\n  \"Select several photos in Photo Library if available. If iPhone only allows one, choose one, \" +\n  \"tap Add More Photos and repeat. Then tap Upload All Photos once.\";\nphotoLibraryHelp.style.cssText = \"font-size:14px;margin:4px 0 6px;\";\nconst photoSelectionMessage = document.createElement(\"p\");\nphotoSelectionMessage.id = \"gw-photo-selection-message\";\nphotoSelectionMessage.setAttribute(\"role\", \"status\");\nphotoSelectionMessage.style.cssText = \"font-size:14px;margin:4px 0 10px;\";\nconst photoQueueList = document.createElement(\"div\");\nphotoQueueList.id = \"gw-photo-pending-list\";\nphotoQueueList.style.cssText = \"margin:6px 0 12px;overflow-wrap:anywhere;\";\nconst addMorePhotos = document.createElement(\"button\");\naddMorePhotos.id = \"gw-photo-add-more\";\naddMorePhotos.type = \"button\";\naddMorePhotos.textContent = \"Add More Photos\";\naddMorePhotos.style.cssText = \"display:block;width:100%;margin:6px 0 10px;\";\nconst clearPhotos = document.createElement(\"button\");\nclearPhotos.id = \"gw-photo-clear-selection\";\nclearPhotos.type = \"button\";\nclearPhotos.textContent = \"Clear Pending Photos\";\nclearPhotos.style.cssText = \"display:block;width:100%;margin:6px 0 12px;\";\n(originalPhotoLabel || photoFileInput).before(\n  photoLibraryLabel, photoLibraryInput, photoLibraryHelp,\n  photoSelectionMessage, photoQueueList, addMorePhotos, clearPhotos\n);\nconst sourceActions = document.getElementById(\"gw-photo-source-actions\");\nconst cameraInput = document.getElementById(\"gw-camera-file\");\nif (sourceActions && cameraInput) {\n  sourceActions.hidden = false;\n  photoLibraryLabel.style.display = \"none\";\n  photoLibraryInput.style.display = \"none\";\n  photoLibraryHelp.style.display = \"none\";\n  addMorePhotos.style.display = \"none\";\n  clearPhotos.style.display = \"none\";\n  document.getElementById(\"gw-take-photo\").addEventListener(\"click\", () => { if (!photoUploadBusy) cameraInput.click(); });\n  document.getElementById(\"gw-photo-library\").addEventListener(\"click\", () => { if (!photoUploadBusy) photoLibraryInput.click(); });\n  cameraInput.addEventListener(\"change\", () => addChosenPhotos(cameraInput));\n  photoQueueList.classList.add(\"gw-pending-photo-grid\");\n}\nconst previewUrls = [];\nuploadPhoto.textContent = \"Upload All Photos\";\nlet pendingPhotos = [];\nlet pendingPhotoJobId = null;\nlet photoUploadBusy = false;\nfunction photoIdentity(file) {\n  return [file.name, file.size, file.lastModified || 0].join(\"|\");\n}\nfunction renderPendingPhotos() {\n  const count = pendingPhotos.length;\n  photoSelectionMessage.textContent = count\n    ? count + \" photo(s) ready to upload.\"\n    : \"No photos selected yet.\";\n  previewUrls.splice(0).forEach(url => window.URL.revokeObjectURL(url));\n  photoQueueList.replaceChildren();\n  pendingPhotos.forEach(function (file, index) {\n    const row = document.createElement(\"div\");\n    row.style.cssText = \"display:flex;align-items:center;justify-content:space-between;gap:8px;margin:5px 0;\";\n    const name = document.createElement(\"span\");\n    name.textContent = (index + 1) + \". \" + file.name;\n    name.style.cssText = \"min-width:0;overflow-wrap:anywhere;\";\n    const remove = document.createElement(\"button\");\n    remove.type = \"button\";\n    remove.textContent = \"Remove\";\n    remove.setAttribute(\"aria-label\", \"Remove \" + file.name);\n    remove.disabled = photoUploadBusy;\n    remove.addEventListener(\"click\", function () {\n      if (photoUploadBusy) return;\n      pendingPhotos.splice(index, 1);\n      if (!pendingPhotos.length) pendingPhotoJobId = null;\n      renderPendingPhotos();\n    });\n    if (sourceActions && cameraInput) {\n      row.className = \"gw-pending-photo\";\n      row.style.cssText = \"\";\n      const preview = document.createElement(\"img\");\n      preview.alt = file.name;\n      const url = window.URL.createObjectURL(file);\n      previewUrls.push(url);\n      preview.src = url;\n      remove.textContent = \"\u00d7\";\n      row.append(preview, remove);\n    } else row.append(name, remove);\n    photoQueueList.appendChild(row);\n  });\n  clearPhotos.disabled = photoUploadBusy || !count;\n  uploadPhoto.disabled = photoUploadBusy || !count;\n}\nfunction clearPendingPhotos() {\n  pendingPhotos = [];\n  pendingPhotoJobId = null;\n  photoLibraryInput.value = \"\";\n  photoFileInput.value = \"\";\n  renderPendingPhotos();\n}\nfunction addChosenPhotos(input) {\n  if (photoUploadBusy) return;\n  const incoming = Array.from(input.files || []);\n  const activeJob = jobIdInput.value.trim();\n  if (incoming.length && pendingPhotos.length && pendingPhotoJobId !== activeJob) {\n    clearPendingPhotos();\n  }\n  if (incoming.length && !pendingPhotos.length) pendingPhotoJobId = activeJob;\n  const seen = new Set(pendingPhotos.map(photoIdentity));\n  let duplicates = 0;\n  for (const file of incoming) {\n    const key = photoIdentity(file);\n    if (seen.has(key)) { duplicates++; continue; }\n    pendingPhotos.push(file);\n    seen.add(key);\n  }\n  \/\/ Reset the picker so another opening never REPLACES earlier queued Files.\n  \/\/ This also allows selecting the same photo after it has been removed.\n  input.value = \"\";\n  renderPendingPhotos();\n  if (duplicates) photoMessage.textContent = duplicates + \" duplicate selection(s) skipped.\";\n}\nphotoLibraryInput.addEventListener(\"change\", function () {\n  addChosenPhotos(photoLibraryInput);\n});\n\/\/ Defensive compatibility with any programmatic use of the original input.\nphotoFileInput.addEventListener(\"change\", function () {\n  addChosenPhotos(photoFileInput);\n});\naddMorePhotos.addEventListener(\"click\", function () {\n  if (!photoUploadBusy) photoLibraryInput.click();\n});\nclearPhotos.addEventListener(\"click\", function () {\n  if (!photoUploadBusy) clearPendingPhotos();\n});\nrenderPendingPhotos();\n\nuploadPhoto.addEventListener(\"click\", async function () {\n  if (photoUploadBusy) return;\n  const jobId = jobIdInput.value.trim();\n  const files = pendingPhotos.slice();\n  const photoType = document.getElementById(\"gw-photo-type\").value;\n  const description = document.getElementById(\"gw-photo-description\").value.trim();\n\n  if (!client || dashboard.hidden || !jobId) {\n    photoMessage.textContent = \"Please search for a job first.\";\n    return;\n  }\n  if (!files.length) {\n    photoMessage.textContent = \"Please choose one or more photos.\";\n    return;\n  }\n  if (pendingPhotoJobId !== jobId) {\n    photoMessage.textContent = \"Job ID changed. Search for the job again and reselect photos.\";\n    return;\n  }\n  const mimeByExtension = {\n    jpg: \"image\/jpeg\", jpeg: \"image\/jpeg\", png: \"image\/png\",\n    webp: \"image\/webp\", heic: \"image\/heic\", heif: \"image\/heif\"\n  };\n  const prepared = [];\n  for (const file of files) {\n    const extension = (file.name.split(\".\").pop() || \"\").toLowerCase();\n    const expectedType = mimeByExtension[extension];\n    const contentType = file.type || expectedType;\n    if (!expectedType || contentType !== expectedType ||\n        file.size > 20 * 1024 * 1024 || file.size === 0) {\n      photoMessage.textContent = \"Unsupported photo or over 20 MB: \" + file.name +\n        \". Use JPG, PNG, WebP, HEIC or HEIF, up to 20 MB per photo.\";\n      return;\n    }\n    prepared.push({ file, extension, contentType });\n  }\n\n  photoUploadBusy = true;\n  uploadPhoto.disabled = true;\n  photoFileInput.disabled = true;\n  photoLibraryInput.disabled = true;\n  addMorePhotos.disabled = true;\n  clearPhotos.disabled = true;\n  renderPendingPhotos();\n  photoMessage.textContent = \"Checking job and employee access...\";\n  try {\n    const { data: auth, error: authError } = await client.auth.getUser();\n    if (authError || !auth.user) {\n      photoMessage.textContent = \"Please log in again.\";\n      return;\n    }\n    const { data: job, error: jobError } = await client\n      .from(\"Jobs\").select(\"job_id\").eq(\"job_id\", jobId).maybeSingle();\n    if (jobError || !job) {\n      photoMessage.textContent = \"Job not found. Search again.\";\n      return;\n    }\n    let savedCount = 0;\n    const failureDetails = [];\n    const successfulFiles = [];\n    for (const { file, extension, contentType } of prepared) {\n      photoMessage.textContent = \"Uploading photo \" +\n        (savedCount + failureDetails.length + 1) + \" of \" + prepared.length + \"...\";\n      try {\n        const path = auth.user.id + \"\/\" + jobId + \"\/\" +\n          crypto.randomUUID() + \".\" + extension;\n        const { error: uploadError } = await client.storage\n          .from(\"job-photos\")\n          .upload(path, file, { contentType, upsert: false });\n        if (uploadError) throw new Error(uploadError.message);\n        const { error: recordError } = await client\n          .from(\"job_photo\")\n          .insert({\n            job_id: jobId, photo_type: photoType, photo_url: path,\n            description, uploaded_by: auth.user.email,\n            taken_at: new Date().toISOString()\n          });\n        if (recordError) {\n          throw new Error(\"Photo stored but record failed: \" + recordError.message);\n        }\n        savedCount++;\n        successfulFiles.push(file);\n      } catch (error) {\n        failureDetails.push(file.name + \": \" + (error.message || \"Upload failed\"));\n      }\n    }\n    photoMessage.textContent = savedCount + \" of \" + prepared.length +\n      \" photo(s) uploaded successfully.\" +\n      (failureDetails.length ? \" Failed: \" + failureDetails.join(\"; \") : \"\");\n    \/\/ Remove only successfully uploaded files, so retry cannot re-upload them.\n    if (pendingPhotoJobId === jobId) {\n      const completed = new Set(successfulFiles);\n      pendingPhotos = pendingPhotos.filter(file => !completed.has(file));\n      if (!pendingPhotos.length) pendingPhotoJobId = null;\n    }\n    if (savedCount && !failureDetails.length && gwDetailOpen) {\n      document.getElementById(\"gw-photo-editor\").hidden = true;\n      document.getElementById(\"gw-photo-description\").value = \"\";\n      resetPhotoView(); viewPhotos.click();\n    }\n    if (failureDetails.length) {\n      photoMessage.textContent += \" Check the gallery before retrying failed photos.\";\n    }\n  } catch (error) {\n    photoMessage.textContent =\n      \"Connection error: \" + (error.message || \"Please try again.\");\n  } finally {\n    photoUploadBusy = false;\n    photoFileInput.disabled = false;\n    photoLibraryInput.disabled = false;\n    addMorePhotos.disabled = false;\n    renderPendingPhotos();\n  }\n});\nconst viewPhotos = document.getElementById(\"gw-view-photos\");\nconst photoGallery = document.getElementById(\"gw-photo-gallery\");\n\n\/\/ Full-screen, keyboard-accessible photo viewer. It reuses the same signed URL\n\/\/ as the gallery and does not make the private Storage bucket public.\nconst photoZoom = document.createElement(\"div\");\nphotoZoom.id = \"gw-photo-zoom\";\nphotoZoom.setAttribute(\"role\", \"dialog\");\nphotoZoom.setAttribute(\"aria-modal\", \"true\");\nphotoZoom.setAttribute(\"aria-label\", \"Enlarged job photo\");\nphotoZoom.style.cssText =\n  \"display:none;position:fixed;inset:0;z-index:2147483647;\" +\n  \"background:rgba(0,0,0,.94);color:white;flex-direction:column;padding:12px;box-sizing:border-box;\";\nconst zoomToolbar = document.createElement(\"div\");\nzoomToolbar.style.cssText =\n  \"display:flex;align-items:center;justify-content:flex-end;gap:10px;flex-wrap:wrap;margin-bottom:8px;\";\nconst zoomSize = document.createElement(\"button\");\nzoomSize.type = \"button\";\nzoomSize.textContent = \"Zoom to original size\";\nconst zoomClose = document.createElement(\"button\");\nzoomClose.type = \"button\";\nzoomClose.textContent = \"Close \u00d7\";\nfor (const control of [zoomSize, zoomClose]) {\n  control.style.cssText = \"padding:10px 14px;border:1px solid #cbd5e1;\" +\n    \"border-radius:7px;background:#fff;color:#111;cursor:pointer;font-size:16px;\";\n}\nzoomToolbar.append(zoomSize, zoomClose);\nconst zoomScroll = document.createElement(\"div\");\nzoomScroll.style.cssText =\n  \"flex:1;min-height:0;overflow:auto;display:flex;align-items:center;justify-content:center;\";\nconst zoomImage = document.createElement(\"img\");\nzoomImage.alt = \"Enlarged job photo\";\nzoomImage.style.cssText = \"display:block;max-width:100%;max-height:100%;object-fit:contain;\";\nzoomScroll.appendChild(zoomImage);\nconst zoomCaption = document.createElement(\"p\");\nzoomCaption.style.cssText = \"text-align:center;margin:8px 0 0;overflow-wrap:anywhere;\";\nphotoZoom.append(zoomToolbar, zoomScroll, zoomCaption);\ndocument.body.appendChild(photoZoom);\nlet zoomOriginalSize = false;\nlet zoomReturnFocus = null;\nlet photoRequestId = 0;\nfunction closePhotoZoom() {\n  if (photoZoom.style.display === \"none\") return;\n  photoZoom.style.display = \"none\";\n  zoomImage.removeAttribute(\"src\");\n  zoomCaption.textContent = \"\";\n  if (zoomReturnFocus && zoomReturnFocus.isConnected) zoomReturnFocus.focus();\n  zoomReturnFocus = null;\n}\nfunction openPhotoZoom(url, label, trigger) {\n  if (!client || dashboard.hidden) return;\n  zoomReturnFocus = trigger;\n  zoomOriginalSize = false;\n  zoomImage.src = url;\n  zoomImage.alt = label || \"Job photo\";\n  zoomCaption.textContent = label || \"Job photo\";\n  zoomImage.style.maxWidth = \"100%\";\n  zoomImage.style.maxHeight = \"100%\";\n  zoomSize.textContent = \"Zoom to original size\";\n  photoZoom.style.display = \"flex\";\n  zoomClose.focus();\n}\nzoomClose.addEventListener(\"click\", closePhotoZoom);\nphotoZoom.addEventListener(\"click\", function (event) {\n  if (event.target === photoZoom) closePhotoZoom();\n});\nzoomSize.addEventListener(\"click\", function () {\n  zoomOriginalSize = !zoomOriginalSize;\n  zoomImage.style.maxWidth = zoomOriginalSize ? \"none\" : \"100%\";\n  zoomImage.style.maxHeight = zoomOriginalSize ? \"none\" : \"100%\";\n  zoomSize.textContent = zoomOriginalSize ? \"Fit to screen\" : \"Zoom to original size\";\n  zoomScroll.scrollTop = 0;\n  zoomScroll.scrollLeft = 0;\n});\ndocument.addEventListener(\"keydown\", function (event) {\n  if (event.key === \"Escape\" && photoZoom.style.display !== \"none\") {\n    event.preventDefault();\n    closePhotoZoom();\n  }\n});\nfunction resetPhotoView() {\n  photoRequestId++;\n  closePhotoZoom();\n  photoGallery.hidden = true;\n  photoGallery.replaceChildren();\n}\n\nviewPhotos.addEventListener(\"click\", async function () {\n  if (!photoGallery.hidden &&\n      photoGallery.childNodes.length > 0) {\n    resetPhotoView();\n    return;\n  }\n\n  const requestId = ++photoRequestId;\n  photoGallery.hidden = false;\n  const jobId = jobIdInput.value.trim();\n  photoGallery.replaceChildren();\n\n  if (!client || dashboard.hidden || !jobId) {\n    photoGallery.textContent = \"Please search for a job first.\";\n    return;\n  }\n\n  viewPhotos.disabled = true;\n  photoGallery.textContent = \"Loading photos...\";\n\n  try {\n    const { data: auth, error: authError } =\n      await client.auth.getUser();\n\n    if (authError || !auth.user) {\n      photoGallery.textContent = \"Please log in again.\";\n      return;\n    }\n\n    const { data: photos, error } = await client\n      .from(\"job_photo\")\n      .select(\"id, photo_url, photo_type, description\")\n      .eq(\"job_id\", jobId);\n\n    if (error) throw error;\n    if (requestId !== photoRequestId || dashboard.hidden || jobIdInput.value.trim() !== jobId) return;\n\n    photoGallery.replaceChildren();\n\n    const selectedPhotos=(photos || []).filter(p=>!gwDetailOpen || p.photo_type === document.getElementById(\"gw-photo-type\").value);\n    if (gwDetailOpen) { const h=document.getElementById(\"gw-category-heading\"); h.textContent=h.textContent.replace(\/ \\(\\d+\\)$\/, \"\") + \" (\" + selectedPhotos.length + \")\"; }\n    if (selectedPhotos.length === 0) {\n      photoGallery.textContent = \"No photos found.\";\n      return;\n    }\n\n    photoGallery.style.cssText=\"display:grid;grid-template-columns:repeat(auto-fill,minmax(100px,1fr));gap:10px;\";\n    for (const photo of selectedPhotos) {\n      const { data: signed, error: urlError } =\n        await client.storage\n          .from(\"job-photos\")\n          .createSignedUrl(photo.photo_url, 300);\n\n      if (requestId !== photoRequestId || dashboard.hidden || jobIdInput.value.trim() !== jobId) return;\n      if (urlError || !signed?.signedUrl) {\n        const warning = document.createElement(\"p\");\n        warning.textContent = \"Unable to open one photo.\";\n        photoGallery.appendChild(warning);\n        continue;\n      }\n\n      const heading = document.createElement(\"h4\");\n      heading.textContent = photo.photo_type || \"Job Photo\";\n\n      const enlarge = document.createElement(\"button\");\n      enlarge.type = \"button\";\n      enlarge.setAttribute(\"aria-label\", \"Enlarge \" + (photo.description || photo.photo_type || \"job photo\"));\n      enlarge.title = \"Click to enlarge photo\";\n      enlarge.style.cssText =\n        \"display:block;max-width:400px;width:100%;padding:0;border:0;background:none;cursor:zoom-in;\";\n      const image = document.createElement(\"img\");\n      image.src = signed.signedUrl;\n      image.alt = photo.description || \"Job photo\";\n      image.style.width = \"100%\";\n      image.style.maxWidth = \"400px\";\n      image.style.height = \"auto\";\n      enlarge.appendChild(image);\n      enlarge.addEventListener(\"click\", function () {\n        if (jobIdInput.value.trim() !== jobId || dashboard.hidden || !client) return;\n        openPhotoZoom(signed.signedUrl, photo.description || photo.photo_type || \"Job photo\", enlarge);\n      });\n\n      const description = document.createElement(\"p\");\n      description.textContent = photo.description || \"\";\n\n      const tile=document.createElement(\"div\");\n      tile.style.cssText=\"min-width:0;\";\n      heading.style.cssText=\"font-size:12px;margin:4px 0;\";\n      enlarge.style.cssText=\"display:block;width:100%;min-height:0;margin:0;padding:0;background:none;border:0;cursor:zoom-in;\";\n      image.style.cssText=\"width:100%;height:100px;object-fit:cover;border-radius:6px;\";\n      image.loading=\"lazy\";\n      description.style.cssText=\"font-size:12px;margin:4px 0;\";\n      tile.append(heading,enlarge,description);\n      if(photo.photo_type===\"Problem\")gwRE3Optional(description,photo.description);\n      if (gwDetailOpen && ['Before','After'].includes(photo.photo_type)) {\n        const profile=await qRole();\n        if(profile.is_active && ['owner','office'].includes(profile.role)) {\n          const del=document.createElement('button');del.type='button';del.textContent='\ud83d\uddd1';del.title='Delete photo';del.setAttribute('aria-label','Delete photo');tile.append(del);\n          del.onclick=async()=>{if(!confirm('Permanently delete this photo?'))return;del.disabled=true;try{qCheck(await client.storage.from('job-photos').remove([photo.photo_url]));qCheck(await client.rpc('gw_delete_job_photo',{p_photo_id:photo.id}));resetPhotoView();viewPhotos.click();void gwRefreshDetailIndicators(jobId);}catch(e){alert(e.message);del.disabled=false;}};\n        }\n      }\n      photoGallery.append(tile);\n    }\n  } catch (error) {\n    if (requestId === photoRequestId) photoGallery.textContent =\n      \"Unable to load photos: \" + error.message;\n  } finally {\n    viewPhotos.disabled = false;\n  }\n});\n\/\/ CUSTOMER PHOTO APPROVALS (OWNER \/ OFFICE \/ PROJECT MANAGER).\n\/\/ DB RLS limits reading approval flags; the SECURITY DEFINER RPC alone changes\n\/\/ visibility. Do not put secret keys or customer lookup codes in this browser.\nconst photoApprovalToggle = document.createElement(\"button\");\nphotoApprovalToggle.type = \"button\";\nphotoApprovalToggle.id = \"gw-customer-photo-toggle\";\nphotoApprovalToggle.textContent = \"Customer Photo Approvals (Owner \/ Office \/ PM)\";\nphotoApprovalToggle.hidden = true;\nphotoApprovalToggle.setAttribute(\"aria-expanded\", \"false\");\nphotoApprovalToggle.style.cssText = \"width:100%;margin:12px 0 8px;\";\nconst photoApprovalPanel = document.createElement(\"section\");\nphotoApprovalPanel.id = \"gw-customer-photo-panel\";\nphotoApprovalPanel.hidden = true;\nphotoApprovalPanel.style.cssText =\n  \"box-sizing:border-box;width:100%;padding:16px;margin:8px 0 20px;\" +\n  \"border:1px solid #cbd5e1;border-radius:8px;overflow-wrap:anywhere;\";\nconst photoApprovalHeading = document.createElement(\"h3\");\nphotoApprovalHeading.textContent = \"Approve Before \/ After Photos for Customer\";\nconst photoApprovalHelp = document.createElement(\"p\");\nphotoApprovalHelp.textContent =\n  \"Only individually approved Before \/ After photos appear in the customer lookup. \" +\n  \"Evidence photos cannot be approved. Revoking prevents new customer lookups, \" +\n  \"but does not recall downloads or previously issued short-lived links.\";\nconst photoApprovalJobLabel = document.createElement(\"p\");\nconst photoApprovalRefresh = document.createElement(\"button\");\nphotoApprovalRefresh.type = \"button\";\nphotoApprovalRefresh.id = \"gw-customer-photo-refresh\";\nphotoApprovalRefresh.textContent = \"Refresh Photo Approvals\";\nphotoApprovalRefresh.style.cssText = \"width:100%;margin:8px 0;\";\nconst photoApprovalMessage = document.createElement(\"p\");\nphotoApprovalMessage.id = \"gw-customer-photo-message\";\nphotoApprovalMessage.setAttribute(\"role\", \"status\");\nconst photoApprovalList = document.createElement(\"div\");\nphotoApprovalList.id = \"gw-customer-photo-list\";\nconst photoApprovalClose = document.createElement(\"button\");\nphotoApprovalClose.type = \"button\";\nphotoApprovalClose.textContent = \"Close Photo Approvals\";\nphotoApprovalClose.style.cssText = \"width:100%;margin-top:12px;\";\nphotoApprovalPanel.append(\n  photoApprovalHeading, photoApprovalHelp, photoApprovalJobLabel,\n  photoApprovalRefresh, photoApprovalMessage, photoApprovalList, photoApprovalClose\n);\n\/\/ Customer Photo Approvals belong inside Job Photos.\n\/\/ Append them to the existing Job Photos form so they open\/close with that section.\nphotoForm.appendChild(photoApprovalToggle);\nphotoForm.appendChild(photoApprovalPanel);\n\nlet photoApprovalJobId = null;\nlet photoApprovalUserId = null;\nlet photoApprovalGeneration = 0;\nlet photoApprovalRequestId = 0;\nlet photoApprovalBusy = false;\nfunction resetPhotoApprovalView() {\n  photoApprovalGeneration++;\n  photoApprovalRequestId++;\n  photoApprovalJobId = null;\n  photoApprovalUserId = null;\n  photoApprovalBusy = false;\n  photoApprovalToggle.hidden = true;\n  photoApprovalToggle.setAttribute(\"aria-expanded\", \"false\");\n  photoApprovalPanel.hidden = true;\n  photoApprovalJobLabel.textContent = \"\";\n  photoApprovalMessage.textContent = \"\";\n  photoApprovalList.replaceChildren();\n  photoApprovalToggle.disabled = false;\n  photoApprovalRefresh.disabled = false;\n  photoApprovalClose.disabled = false;\n}\nfunction photoApprovalIsCurrent(jobId, userId, generation) {\n  return !!client && !logout.hidden && !jobSearch.hidden && !dashboard.hidden &&\n    !photoApprovalToggle.hidden && !photoApprovalPanel.hidden &&\n    photoApprovalJobId === jobId && photoApprovalUserId === userId &&\n    jobIdInput.value.trim() === jobId && photoApprovalGeneration === generation;\n}\nfunction configurePhotoApprovalView(jobId, role, userId) {\n  resetPhotoApprovalView();\n  if (![\"owner\", \"office\", \"project_manager\"].includes(role) ||\n      !jobId || !userId || dashboard.hidden || logout.hidden || jobSearch.hidden ||\n      jobIdInput.value.trim() !== jobId) return;\n  photoApprovalJobId = jobId;\n  photoApprovalUserId = userId;\n  photoApprovalJobLabel.textContent = \"Selected Job ID: \" + jobId;\n  photoApprovalToggle.hidden = false;\n}\nfunction photoApprovalStoragePath(path, jobId) {\n  if (typeof path !== \"string\") return false;\n  const segments = path.split(\"\/\");\n  return segments.length === 3 &&\n    \/^[0-9a-fA-F-]{36}$\/.test(segments[0]) &&\n    segments[1] === jobId && segments[2].length > 0;\n}\nasync function loadPhotoApprovals() {\n  const jobId = photoApprovalJobId;\n  const userId = photoApprovalUserId;\n  const generation = photoApprovalGeneration;\n  if (!photoApprovalIsCurrent(jobId, userId, generation) || photoApprovalBusy) return;\n  const requestId = ++photoApprovalRequestId;\n  photoApprovalRefresh.disabled = true;\n  photoApprovalList.replaceChildren();\n  photoApprovalMessage.textContent = \"Loading Before \/ After photos and approval status...\";\n  try {\n    const { data: auth, error: authError } = await client.auth.getUser();\n    if (authError || !auth.user || auth.user.id !== userId)\n      throw new Error(\"Please log in again.\");\n    const { data: active, error: activeError } = await client.rpc(\"gw_employee_is_active\");\n    if (activeError || active !== true)\n      throw new Error(\"Unable to verify active employee access.\");\n    const { data: profile, error: profileError } = await client.from(\"employee_profiles\")\n      .select(\"role\").eq(\"user_id\", userId).maybeSingle();\n    if (profileError || !profile ||\n        ![\"owner\", \"office\", \"project_manager\"].includes(profile.role))\n      throw new Error(\"Photo approval access is unavailable for this account.\");\n    if (!photoApprovalIsCurrent(jobId, userId, generation) ||\n        requestId !== photoApprovalRequestId) return;\n\n    \/\/ Match the customer endpoint's most recent 100-photo window.\n    const { data: photos, error: photoError } = await client.from(\"job_photo\")\n      .select(\"id,photo_type,photo_url,description,is_evidence\")\n      .eq(\"job_id\", jobId).in(\"photo_type\", [\"Before\", \"After\"])\n      .order(\"id\", { ascending: false }).limit(100);\n    if (photoError) throw photoError;\n    if (!photoApprovalIsCurrent(jobId, userId, generation) ||\n        requestId !== photoApprovalRequestId) return;\n\n    const photoIds = (photos || []).filter((p) => Number.isSafeInteger(p.id))\n      .map((p) => p.id);\n    let approvals = [];\n    if (photoIds.length) {\n      \/\/ Column-level SELECT grant + manager-only RLS is required. Fail closed if absent.\n      const { data, error } = await client.from(\"job_photo_customer_approvals\")\n        .select(\"photo_id,customer_visible\").in(\"photo_id\", photoIds);\n      if (error) throw new Error(\"Cannot read photo approval status. Ask the office to check database permissions.\");\n      approvals = data || [];\n    }\n    if (!photoApprovalIsCurrent(jobId, userId, generation) ||\n        requestId !== photoApprovalRequestId) return;\n    photoApprovalList.replaceChildren();\n    if (!photos || !photos.length) {\n      photoApprovalMessage.textContent = \"No Before \/ After photos found for this job.\";\n      return;\n    }\n    const approvedIds = new Set(approvals.filter((a) => a.customer_visible === true)\n      .map((a) => a.photo_id));\n    photoApprovalMessage.textContent =\n      \"Showing up to the most recent 100 Before \/ After photos. Approval is per photo.\";\n    for (const photo of photos) {\n      if (!photoApprovalIsCurrent(jobId, userId, generation) ||\n          requestId !== photoApprovalRequestId) return;\n      if (!Number.isSafeInteger(photo.id)) continue;\n      const approved = approvedIds.has(photo.id);\n      const eligible = photo.is_evidence !== true &&\n        photoApprovalStoragePath(photo.photo_url, jobId);\n      const item = document.createElement(\"section\");\n      item.style.cssText =\n        \"padding:12px 0;border-bottom:1px solid #cbd5e1;overflow-wrap:anywhere;\";\n      const heading = document.createElement(\"h4\");\n      heading.textContent = \"Photo #\" + photo.id + \" \u2014 \" + photo.photo_type;\n      const status = document.createElement(\"p\");\n      status.textContent = approved ? \"Customer visibility: APPROVED\" :\n        \"Customer visibility: Not shared\";\n      const caption = document.createElement(\"p\");\n      caption.textContent = photo.description || \"No description\";\n      item.append(heading, status, caption);\n      if (!eligible) {\n        const warning = document.createElement(\"p\");\n        warning.textContent = photo.is_evidence === true\n          ? \"Evidence photo \u2014 cannot approve for customers.\"\n          : \"Photo storage path unavailable \u2014 cannot approve.\";\n        item.appendChild(warning);\n      } else {\n        const { data: signed, error: signedError } = await client.storage\n          .from(\"job-photos\").createSignedUrl(photo.photo_url, 300);\n        if (!photoApprovalIsCurrent(jobId, userId, generation) ||\n            requestId !== photoApprovalRequestId) return;\n        if (!signedError && signed?.signedUrl) {\n          const preview = document.createElement(\"img\");\n          preview.src = signed.signedUrl;\n          preview.alt = photo.photo_type + \" photo \" + photo.id;\n          preview.loading = \"lazy\";\n          preview.style.cssText =\n            \"display:block;width:100%;max-width:300px;height:auto;margin:8px 0;\";\n          item.appendChild(preview);\n        } else {\n          const warning = document.createElement(\"p\");\n          warning.textContent = \"Preview unavailable. Approval is disabled until the photo can be opened.\";\n          item.appendChild(warning);\n        }\n        \/\/ If a preview cannot be signed, still allow revoking an existing approval.\n        if (!approved && (signedError || !signed?.signedUrl)) {\n          photoApprovalList.appendChild(item);\n          continue;\n        }\n      }\n      if (eligible || approved) {\n        const changeButton = document.createElement(\"button\");\n        changeButton.type = \"button\";\n        changeButton.textContent = approved ? \"Revoke Customer Access\" :\n          \"Approve for Customer\";\n        changeButton.style.cssText = \"width:100%;margin:8px 0;\";\n        changeButton.addEventListener(\"click\", async function () {\n          if (!photoApprovalIsCurrent(jobId, userId, generation) || photoApprovalBusy) return;\n          const nextVisibility = !approved;\n          const action = nextVisibility ? \"APPROVE\" : \"REVOKE\";\n          if (!window.confirm(action + \" customer visibility for photo #\" + photo.id +\n              \" (\" + photo.photo_type + \") on \" + jobId + \"?\" +\n              (nextVisibility ? \"\\n\\nCustomers with this job's valid private code will be able to see it.\" :\n                \"\\n\\nPreviously downloaded images or unexpired links cannot be recalled.\"))) return;\n          photoApprovalBusy = true;\n          photoApprovalRefresh.disabled = true;\n          photoApprovalClose.disabled = true;\n          photoApprovalList.querySelectorAll(\"button\").forEach((b) => { b.disabled = true; });\n          photoApprovalMessage.textContent = \"Saving photo visibility...\";\n          let rpcConfirmed = false;\n          try {\n            const { data: currentAuth, error: currentAuthError } = await client.auth.getUser();\n            if (currentAuthError || !currentAuth.user || currentAuth.user.id !== userId ||\n                !photoApprovalIsCurrent(jobId, userId, generation))\n              throw new Error(\"Employee session changed.\");\n            const { data: activeNow, error: activeNowError } =\n              await client.rpc(\"gw_employee_is_active\");\n            if (activeNowError || activeNow !== true ||\n                !photoApprovalIsCurrent(jobId, userId, generation))\n              throw new Error(\"Employee access changed.\");\n            const { data: saved, error: saveError } = await client.rpc(\n              \"gw_set_photo_customer_visibility\",\n              { p_photo_id: photo.id, p_visible: nextVisibility }\n            );\n            if (saveError || saved !== true)\n              throw new Error(\"Could not confirm the visibility change.\");\n            rpcConfirmed = true;\n          } catch (_error) {\n            if (photoApprovalIsCurrent(jobId, userId, generation)) {\n              photoApprovalMessage.textContent =\n                \"Unable to confirm photo visibility. Refresh to check current status.\";\n              \/\/ Clear stale buttons and statuses rather than allowing blind retries.\n              photoApprovalList.replaceChildren();\n            }\n          } finally {\n            if (photoApprovalGeneration === generation) {\n              photoApprovalBusy = false;\n              photoApprovalClose.disabled = false;\n              photoApprovalRefresh.disabled = false;\n            }\n          }\n          if (rpcConfirmed && photoApprovalIsCurrent(jobId, userId, generation)) {\n            \/\/ Re-read flags from the database; no unverified 'success' message.\n            await loadPhotoApprovals();\n          }\n        });\n        item.appendChild(changeButton);\n      }\n      photoApprovalList.appendChild(item);\n    }\n  } catch (error) {\n    if (photoApprovalIsCurrent(jobId, userId, generation) &&\n        requestId === photoApprovalRequestId) {\n      photoApprovalList.replaceChildren();\n      photoApprovalMessage.textContent = error.message ||\n        \"Unable to load photo approval status. No changes were made.\";\n    }\n  } finally {\n    if (photoApprovalGeneration === generation &&\n        requestId === photoApprovalRequestId) photoApprovalRefresh.disabled = false;\n  }\n}\nphotoApprovalToggle.addEventListener(\"click\", function () {\n  if (!client || photoApprovalToggle.hidden || photoApprovalBusy ||\n      dashboard.hidden || logout.hidden ||\n      jobIdInput.value.trim() !== photoApprovalJobId) return;\n  photoApprovalPanel.hidden = !photoApprovalPanel.hidden;\n  photoApprovalToggle.setAttribute(\"aria-expanded\", String(!photoApprovalPanel.hidden));\n  photoApprovalRequestId++;\n  if (photoApprovalPanel.hidden) {\n    photoApprovalList.replaceChildren();\n    photoApprovalMessage.textContent = \"\";\n  } else {\n    void loadPhotoApprovals();\n  }\n});\nphotoApprovalRefresh.addEventListener(\"click\", function () {\n  if (!photoApprovalBusy) void loadPhotoApprovals();\n});\nphotoApprovalClose.addEventListener(\"click\", function () {\n  if (photoApprovalBusy) return;\n  photoApprovalPanel.hidden = true;\n  photoApprovalToggle.setAttribute(\"aria-expanded\", \"false\");\n  photoApprovalRequestId++;\n  photoApprovalList.replaceChildren();\n  photoApprovalMessage.textContent = \"\";\n});\n\n\/\/ JOB DRAWINGS: upload existing PDF\/images and list drawings for an authorized job.\n\/\/ The job-drawings Storage bucket and public.job_drawings RLS are the actual access\n\/\/ boundaries. UI visibility is not authorization. No overwrite or delete is provided.\nconst drawingToggle = document.createElement(\"button\");\ndrawingToggle.id = \"gw-drawing-toggle\";\ndrawingToggle.type = \"button\";\ndrawingToggle.textContent = \"View PDF\";\nconst gwRE173UploadLink=document.createElement(\"button\");gwRE173UploadLink.type=\"button\";gwRE173UploadLink.textContent=\"Upload PDF\";gwRE173UploadLink.hidden=true;\ndrawingToggle.hidden = true;\ndrawingToggle.setAttribute(\"aria-expanded\", \"false\");\ndrawingToggle.style.cssText = \"width:100%;margin:14px 0 8px;\";\n\nconst drawingPanel = document.createElement(\"section\");\ndrawingPanel.id = \"gw-drawing-panel\";\ndrawingPanel.hidden = true;\ndrawingPanel.style.cssText =\n  \"box-sizing:border-box;width:100%;padding:16px;margin:8px 0 20px;\" +\n  \"border:1px solid #cbd5e1;border-radius:10px;background:#fff;overflow-wrap:anywhere;\";\nconst drawingHeading = document.createElement(\"h3\");\ndrawingHeading.textContent = \"Job Drawings \/ Cutting Plans\";\nconst drawingHelp = document.createElement(\"p\");\ndrawingHelp.textContent =\n  \"Upload a prepared PDF, JPG, PNG, WebP or HEIC for this job (maximum 50 MB). \" +\n  \"Existing drawings remain saved; this form does not replace or delete them.\";\nconst drawingFileLabel = document.createElement(\"label\");\ndrawingFileLabel.htmlFor = \"gw-drawing-file\";\ndrawingFileLabel.textContent = \"Choose Drawing (PDF \/ Image)\";\ndrawingFileLabel.style.cssText = \"display:block;margin:16px 0 6px;font-weight:600;\";\nconst drawingFile = document.createElement(\"input\");\ndrawingFile.id = \"gw-drawing-file\";\ndrawingFile.type = \"file\";\ndrawingFile.accept = \"application\/pdf,image\/jpeg,image\/png,image\/webp,image\/heic\";\ndrawingFile.style.cssText = \"box-sizing:border-box;width:100%;max-width:100%;\";\nconst drawingUpload = document.createElement(\"button\");\ndrawingUpload.id = \"gw-upload-drawing\";\ndrawingUpload.type = \"button\";\ndrawingUpload.textContent = \"Upload PDF \/ Drawing\";\ndrawingUpload.style.width = \"100%\";\nconst drawingUploadMessage = document.createElement(\"p\");\ndrawingUploadMessage.id = \"gw-drawing-upload-message\";\ndrawingUploadMessage.setAttribute(\"role\", \"status\");\nconst drawingListHeading = document.createElement(\"h4\");\ndrawingListHeading.textContent = \"Final Measurement \/ Job Drawings\";\nconst drawingRefresh = document.createElement(\"button\");\ndrawingRefresh.id = \"gw-view-drawings\";\ndrawingRefresh.type = \"button\";\ndrawingRefresh.textContent = \"Refresh Drawings\";\ndrawingRefresh.style.width = \"100%\";\nconst drawingList = document.createElement(\"div\");\ndrawingList.id = \"gw-drawing-list\";\ndrawingList.setAttribute(\"aria-live\", \"polite\");\ndrawingPanel.append(\n  drawingHeading, drawingHelp, drawingFileLabel, drawingFile,\n  drawingUpload, drawingUploadMessage, drawingListHeading,\n  drawingRefresh, drawingList\n);\n\/\/ Drawing \/ Cutting Plans belongs inside Final Measurement.\nmeasurementActions.append(gwRE173UploadLink);\nconst gwRE173PdfSection=document.createElement(\"div\");gwRE173PdfSection.className=\"gw-re173-pdf\";\ngwRE173PdfSection.append(drawingToggle,drawingPanel);measurementDashboardContent.after(gwRE173PdfSection);\nconst gwRE173UploadControls=[drawingHelp,drawingFileLabel,drawingFile,drawingUpload,drawingUploadMessage];\nfunction gwRE173DrawingMode(upload){for(const e of gwRE173UploadControls)e.hidden=!upload;}\ngwRE173UploadLink.onclick=()=>{if(gwRE173UploadLink.hidden||drawingUploadBusy)return;gwRE173DrawingMode(true);if(drawingPanel.hidden)drawingToggle.click();drawingFile.scrollIntoView({block:\"center\",behavior:\"smooth\"});};\n\nlet drawingJobId = null;\nlet drawingRequestId = 0;\nlet drawingUploadBusy = false;\nconst drawingMimeExtensions = Object.freeze({\n  \"application\/pdf\": \"pdf\",\n  \"image\/jpeg\": \"jpg\",\n  \"image\/png\": \"png\",\n  \"image\/webp\": \"webp\",\n  \"image\/heic\": \"heic\"\n});\n\nfunction resetDrawingView() {\n  drawingRequestId++;\n  drawingJobId = null;\n  drawingUploadBusy = false;\n  drawingToggle.hidden = true;\n  gwRE173UploadLink.hidden=true;gwRE173DrawingMode(false);\n  drawingToggle.disabled = false;\n  drawingToggle.setAttribute(\"aria-expanded\", \"false\");\n  drawingPanel.hidden = true;\n  drawingFile.value = \"\";\n  drawingUpload.disabled = false;\n  drawingRefresh.disabled = false;\n  drawingUploadMessage.textContent = \"\";\n  drawingList.replaceChildren();\n}\n\nfunction drawingIsCurrent(jobId, requestId) {\n  return !!client && !logout.hidden && !jobSearch.hidden && !dashboard.hidden &&\n    !drawingToggle.hidden && !drawingPanel.hidden &&\n    drawingJobId === jobId && jobIdInput.value.trim() === jobId &&\n    (requestId === undefined || requestId === drawingRequestId);\n}\n\nfunction configureDrawingView(jobId, role) {\n  resetDrawingView();\n  if (!\/^(owner|office|project_manager|installer|fabricator)$\/.test(role || \"\") ||\n      !jobId || (dashboard.hidden&&(!gwDetailOpen||gwDetailSelectedJobId!==jobId)) || logout.hidden ||\n      jobIdInput.value.trim() !== jobId) return;\n  drawingJobId = jobId;\n  drawingToggle.hidden = false;\n  gwRE173UploadLink.hidden=!['owner','office','project_manager','installer'].includes(role);\n}\n\nasync function loadDrawingList() {\n  const jobId = drawingJobId;\n  if (!drawingIsCurrent(jobId)) return;\n  const requestId = ++drawingRequestId;\n  drawingRefresh.disabled = true;\n  drawingList.textContent = \"Loading drawings...\";\n  try {\n    const { data: auth, error: authError } = await client.auth.getUser();\n    if (authError || !auth.user) throw new Error(\"Please log in again.\");\n    const { data: isActive, error: accessError } =\n      await client.rpc(\"gw_employee_is_active\");\n    if (accessError || isActive !== true)\n      throw new Error(\"Unable to verify active Portal access.\");\n    const { data: drawings, error } = await client.from(\"job_drawings\")\n      .select(\"id, job_id, storage_path, file_name, mime_type, created_at\")\n      .eq(\"job_id\", jobId)\n      .order(\"created_at\", { ascending: false })\n      .order(\"id\", { ascending: false });\n    if (error) throw error;\n    if (!drawingIsCurrent(jobId, requestId)) return;\n    drawingList.replaceChildren();\n    if (!drawings || drawings.length === 0) {\n      drawingList.textContent = \"No drawings uploaded for this job yet.\";\n      return;\n    }\n    for (const drawing of drawings) {\n      const row = document.createElement(\"div\");\n      row.style.cssText = \"padding:12px 0;border-bottom:1px solid #e2e8f0;\";\n\n      const title = document.createElement(\"strong\");\n      title.textContent = drawing.file_name || \"Drawing\";\n\n      const details = document.createElement(\"p\");\n      details.textContent = drawing.created_at\n        ? \"Uploaded: \" + new Date(drawing.created_at).toLocaleString()\n        : \"Drawing\";\n      details.style.cssText = \"margin:6px 0;overflow-wrap:anywhere;\";\n\n      const viewer = document.createElement(\"div\");\n      viewer.style.cssText = \"margin-top:10px;\";\n\n      const rowMessage = document.createElement(\"p\");\n      rowMessage.setAttribute(\"role\", \"status\");\n      rowMessage.textContent = \"Opening drawing...\";\n      viewer.appendChild(rowMessage);\n\n      row.append(title, details, viewer);\n      drawingList.appendChild(row);\n\n      try {\n        const { data: signed, error: urlError } = await client.storage\n          .from(\"job-drawings\")\n          .createSignedUrl(drawing.storage_path, 300);\n\n        if (urlError || !signed?.signedUrl)\n          throw urlError || new Error(\"Unable to open drawing.\");\n\n        if (!drawingIsCurrent(jobId, requestId)) return;\n\n        viewer.replaceChildren();\n\n        const mime = (drawing.mime_type || \"\").toLowerCase();\n        const isPdf = mime === \"application\/pdf\";\n        const canPreviewImage =\n          mime === \"image\/jpeg\" ||\n          mime === \"image\/png\" ||\n          mime === \"image\/webp\";\n\n        if (canPreviewImage) {\n          const imageButton = document.createElement(\"button\");\n          imageButton.type = \"button\";\n          imageButton.style.cssText =\n            \"display:block;width:100%;padding:0;border:1px solid #cbd5e1;\" +\n            \"border-radius:8px;background:#fff;overflow:hidden;cursor:pointer;\";\n\n          const preview = document.createElement(\"img\");\n          preview.src = signed.signedUrl;\n          preview.alt = drawing.file_name || \"Job drawing\";\n          preview.loading = \"lazy\";\n          preview.style.cssText =\n            \"display:block;width:100%;max-height:420px;object-fit:contain;background:#f8fafc;\";\n\n          imageButton.appendChild(preview);\n          imageButton.addEventListener(\"click\", function () {\n            if (!drawingIsCurrent(jobId, requestId)) return;\n            openPhotoZoom(\n              signed.signedUrl,\n              drawing.file_name || \"Job drawing\",\n              imageButton\n            );\n          });\n\n          const hint = document.createElement(\"p\");\n          hint.textContent = \"Tap drawing to enlarge\";\n          hint.style.cssText = \"margin:6px 0 0;font-size:14px;\";\n\n          viewer.append(imageButton, hint);\n        } else {\n          const link = document.createElement(\"a\");\n          link.href = signed.signedUrl;\n          link.target = \"_blank\";\n          link.rel = \"noopener noreferrer\";\n          link.textContent = isPdf ? \"Open PDF\" : \"Open Drawing\";\n          link.style.cssText =\n            \"display:block;box-sizing:border-box;width:100%;padding:12px 14px;\" +\n            \"border-radius:7px;background:#1f6fb2;color:#fff;text-align:center;\" +\n            \"text-decoration:none;font-weight:600;\";\n          viewer.appendChild(link);\n          if(isPdf){const download=document.createElement('button');download.type='button';download.textContent='Download PDF';download.onclick=async()=>{if(!drawingIsCurrent(jobId,requestId))return;try{const r=await client.storage.from('job-drawings').createSignedUrl(drawing.storage_path,300,{download:drawing.file_name||'drawing.pdf'});if(r.error)throw r.error;if(drawingIsCurrent(jobId,requestId)){const a=document.createElement('a');a.href=r.data.signedUrl;a.rel='noopener noreferrer';a.click();}}catch(e){if(drawingIsCurrent(jobId,requestId))drawingUploadMessage.textContent=e.message||'Download failed.';}};viewer.append(download);}\n\n        }\n      } catch (error) {\n        if (drawingIsCurrent(jobId, requestId)) {\n          viewer.replaceChildren();\n          const warning = document.createElement(\"p\");\n          warning.textContent =\n            \"Unable to open drawing: \" +\n            (drawing.file_name || \"Drawing\") +\n            \" \u2014 \" + error.message;\n          warning.style.cssText =\n            \"padding:10px;border:1px solid #f1b9b9;border-radius:6px;overflow-wrap:anywhere;\";\n          viewer.appendChild(warning);\n          console.error(\"GW Portal drawing signed URL failed\", {\n            jobId: jobId,\n            storage_path: drawing.storage_path,\n            error: error\n          });\n        }\n      }\n    }\n  } catch (error) {\n    if (drawingIsCurrent(jobId, requestId))\n      drawingList.textContent = \"Unable to load drawings: \" + error.message;\n  } finally {\n    if (drawingJobId === jobId && requestId === drawingRequestId &&\n        !drawingToggle.hidden && !logout.hidden) drawingRefresh.disabled = false;\n  }\n}\n\ndrawingToggle.addEventListener(\"click\", function () {\n  if (!client || drawingToggle.hidden || drawingToggle.disabled ||\n      dashboard.hidden || logout.hidden || !drawingJobId ||\n      jobIdInput.value.trim() !== drawingJobId) return;\n  drawingPanel.hidden = !drawingPanel.hidden;\n  if(drawingPanel.hidden)gwRE173DrawingMode(false);\n  drawingToggle.setAttribute(\"aria-expanded\", String(!drawingPanel.hidden));\n  if (drawingPanel.hidden) {\n    drawingRequestId++;\n    drawingList.replaceChildren(); \/\/ discard expiring signed links\n    drawingRefresh.disabled = false;\n  } else {\n    void loadDrawingList();\n  }\n});\n\ndrawingRefresh.addEventListener(\"click\", function () {\n  if (!drawingUploadBusy) void loadDrawingList();\n});\n\ndrawingUpload.addEventListener(\"click\", async function () {\n  const jobId = drawingJobId;\n  if (!drawingIsCurrent(jobId) || drawingUploadBusy) return;\n  const file = drawingFile.files && drawingFile.files[0];\n  if (!file) {\n    drawingUploadMessage.textContent = \"Choose a PDF or image first.\";\n    return;\n  }\n  const extension = drawingMimeExtensions[file.type];\n  if (!extension || file.size === 0 || file.size > 50 * 1024 * 1024 ||\n      file.name.length > 180) {\n    drawingUploadMessage.textContent =\n      \"Choose a nonempty PDF\/JPG\/PNG\/WebP\/HEIC, at most 50 MB, with a filename under 181 characters.\";\n    return;\n  }\n  if (!window.confirm(\"Upload drawing '\" + file.name + \"' to job \" + jobId +\n      \"? Existing drawings will not be replaced.\")) return;\n  drawingUploadBusy = true;\n  drawingUpload.disabled = true;\n  drawingToggle.disabled = true;\n  drawingUploadMessage.textContent = \"Checking permissions...\";\n  try {\n    const requestId = drawingRequestId;\n    const { data: auth, error: authError } = await client.auth.getUser();\n    if (authError || !auth.user) throw new Error(\"Please log in again.\");\n    const { data: isActive, error: accessError } =\n      await client.rpc(\"gw_employee_is_active\");\n    if (accessError || isActive !== true)\n      throw new Error(\"Unable to verify active Portal access.\");\n    if (!drawingIsCurrent(jobId, requestId)) return;\n    const storagePath = auth.user.id + \"\/\" + jobId + \"\/\" +\n      crypto.randomUUID() + \".\" + extension;\n    drawingUploadMessage.textContent = \"Uploading drawing...\";\n    const { error: uploadError } = await client.storage.from(\"job-drawings\")\n      .upload(storagePath, file, { contentType: file.type, upsert: false });\n    if (uploadError) throw uploadError;\n    \/\/ No Storage DELETE permission: if metadata fails, report the orphaned path\n    \/\/ to the office instead of falsely claiming upload success or retrying.\n    const { data: saved, error: recordError } = await client.from(\"job_drawings\")\n      .insert({\n        job_id: jobId,\n        storage_path: storagePath,\n        file_name: file.name,\n        mime_type: file.type,\n        uploaded_by: auth.user.id\n      }).select(\"id, job_id\").maybeSingle();\n    if (recordError || !saved || saved.job_id !== jobId) {\n      if (drawingIsCurrent(jobId))\n        drawingUploadMessage.textContent =\n          \"File stored but its drawing record could not be saved. \" +\n          \"Contact the office; do not upload this file again. \" +\n          \"Storage path: \" + storagePath;\n      return;\n    }\n    if (!drawingIsCurrent(jobId)) return;\n    drawingFile.value = \"\";\n    drawingUploadMessage.textContent = \"Drawing uploaded and recorded successfully.\";\n    await loadDrawingList();\n  } catch (error) {\n    if (drawingIsCurrent(jobId))\n      drawingUploadMessage.textContent =\n        \"Upload failed or could not be confirmed: \" + error.message +\n        \". Check the drawing list before trying again.\";\n  } finally {\n    if (drawingJobId === jobId && !logout.hidden) {\n      drawingUploadBusy = false;\n      drawingUpload.disabled = false;\n      drawingToggle.disabled = false;\n    }\n  }\n});\n\n\/\/ JOB PROBLEM REPORTS: create and view an immutable issue history. Authorized\n\/\/ employees resolve Open problems via the server-checked RPC; no delete\/edit UI.\n\/\/ Database RLS and the SECURITY DEFINER RPC enforce access independently of UI.\nconst problemToggle = document.createElement(\"button\");\nproblemToggle.id = \"gw-problem-toggle\";\nproblemToggle.type = \"button\";\nproblemToggle.textContent = \"Issues \/ Rework\";\nproblemToggle.hidden = true;\nproblemToggle.setAttribute(\"aria-expanded\", \"false\");\nproblemToggle.style.cssText = \"width:100%;margin:14px 0 8px;\";\n\nconst problemPanel = document.createElement(\"section\");\nproblemPanel.id = \"gw-problem-panel\";\nproblemPanel.hidden = true;\nproblemPanel.style.cssText =\n  \"box-sizing:border-box;width:100%;padding:16px;margin:8px 0 20px;\" +\n  \"border:1px solid #cbd5e1;border-radius:10px;background:#fff;overflow-wrap:anywhere;\";\nconst problemHeading = document.createElement(\"h3\");\nproblemHeading.textContent = \"Job Issues \/ Rework\";\nconst problemHelp = document.createElement(\"p\");\nproblemHelp.textContent =\n  \"Record job issues and rework for the selected job. Resolved reports remain in the history. \" +\n  \"For photos, use Job Photos \u2192 Problem \/ Damage for this same job.\";\nconst problemIssueTypeLabel = document.createElement(\"label\");\nproblemIssueTypeLabel.textContent = \"Issue Type\";\nproblemIssueTypeLabel.style.cssText = \"display:block;margin:16px 0 6px;font-weight:600;\";\nconst problemIssueType = document.createElement(\"select\");\nproblemIssueType.id = \"gw-problem-issue-type\";\nproblemIssueType.style.cssText = \"box-sizing:border-box;width:100%;font-size:16px;padding:8px;\";\nfor (const [value, label] of [\n  [\"\", \"Select issue type\"],\n  [\"Measurement Error\", \"Measurement Error\"],\n  [\"Fabrication \/ Cutting Error\", \"Fabrication \/ Cutting Error\"],\n  [\"Sink \/ Cooktop Error\", \"Sink \/ Cooktop Error\"],\n  [\"Edge Error\", \"Edge Error\"],\n  [\"Installation Error\", \"Installation Error\"],\n  [\"Material Damage\", \"Material Damage\"],\n  [\"Other\", \"Other\"]\n]) {\n  const option = document.createElement(\"option\");\n  option.value = value;\n  option.textContent = label;\n  problemIssueType.appendChild(option);\n}\nproblemIssueTypeLabel.appendChild(problemIssueType);\n\nconst problemWorkersLabel = document.createElement(\"label\");\nproblemWorkersLabel.textContent = \"Worker(s) involved\";\nproblemWorkersLabel.style.cssText = \"display:block;margin:16px 0 6px;font-weight:600;\";\nconst problemWorkers = document.createElement(\"input\");\nproblemWorkers.type = \"text\";\nproblemWorkers.id = \"gw-problem-workers\";\nproblemWorkers.maxLength = 500;\nproblemWorkers.placeholder = \"Example: Jose, Carlos\";\nproblemWorkers.style.cssText = \"box-sizing:border-box;width:100%;font-size:16px;padding:8px;\";\nproblemWorkersLabel.appendChild(problemWorkers);\nconst problemWorkerSelect = document.createElement(\"select\");\nproblemWorkerSelect.id = \"gw-problem-worker-select\";\nproblemWorkerSelect.multiple = true;\nproblemWorkerSelect.size = 6;\nproblemWorkerSelect.style.cssText =\n  \"box-sizing:border-box;width:100%;font-size:16px;padding:8px;margin-top:6px;\";\n\nproblemWorkers.hidden = true;\n\nproblemWorkersLabel.appendChild(problemWorkerSelect);\n\nasync function loadProblemWorkerOptions() {\n  problemWorkerSelect.replaceChildren();\n\n  const loading = document.createElement(\"option\");\n  loading.textContent = \"Loading employees...\";\n  loading.disabled = true;\n  problemWorkerSelect.appendChild(loading);\n\n  const result = await client.rpc(\"gw_problem_worker_list\");\n\n  problemWorkerSelect.replaceChildren();\n\n  if (result.error) {\n    const failed = document.createElement(\"option\");\n    failed.textContent = \"Unable to load employee list\";\n    failed.disabled = true;\n    problemWorkerSelect.appendChild(failed);\n    return;\n  }\n\n  for (const employee of result.data || []) {\n    const option = document.createElement(\"option\");\n    option.value = employee.user_id;\n    option.textContent =\n      employee.display_name + \" \u2014 \" + employee.role;\n    option.dataset.employeeName = employee.display_name;\n    problemWorkerSelect.appendChild(option);\n  }\n}\n\nproblemWorkerSelect.addEventListener(\"change\", function () {\n  const names = Array.from(problemWorkerSelect.selectedOptions)\n    .map(function (option) {\n      return option.dataset.employeeName || option.textContent;\n    });\n\n  problemWorkers.value = names.join(\", \");\n});\n\nconst problemDescriptionLabel = document.createElement(\"label\");\nproblemDescriptionLabel.htmlFor = \"gw-problem-description\";\nproblemDescriptionLabel.textContent = \"Describe the problem (required)\";\nproblemDescriptionLabel.style.cssText =\n  \"display:block;margin:16px 0 6px;font-weight:600;\";\nconst problemDescription = document.createElement(\"textarea\");\nproblemDescription.id = \"gw-problem-description\";\nproblemDescription.rows = 4;\nproblemDescription.maxLength = 4000;\nproblemDescription.style.cssText =\n  \"box-sizing:border-box;width:100%;max-width:100%;font-size:16px;\";\n\nconst problemActionLabel = document.createElement(\"label\");\nproblemActionLabel.textContent = \"Action Needed\";\nproblemActionLabel.style.cssText = \"display:block;margin:16px 0 6px;font-weight:600;\";\nconst problemAction = document.createElement(\"textarea\");\nproblemAction.rows = 3;\nproblemAction.maxLength = 4000;\nproblemAction.style.cssText = \"box-sizing:border-box;width:100%;max-width:100%;font-size:16px;\";\nproblemActionLabel.appendChild(problemAction);\n\nconst problemReworkCostLabel = document.createElement(\"label\");\nproblemReworkCostLabel.textContent = \"Rework Cost ($)\";\nproblemReworkCostLabel.style.cssText = \"display:block;margin:16px 0 6px;font-weight:600;\";\nconst problemReworkCost = document.createElement(\"input\");\nproblemReworkCost.type = \"number\";\nproblemReworkCost.min = \"0\";\nproblemReworkCost.step = \"0.01\";\nproblemReworkCost.placeholder = \"0.00\";\nproblemReworkCost.style.cssText = \"box-sizing:border-box;width:100%;font-size:16px;padding:8px;\";\nproblemReworkCostLabel.appendChild(problemReworkCost);\n\nconst problemNotesLabel = document.createElement(\"label\");\nproblemNotesLabel.textContent = \"Internal Notes\";\nproblemNotesLabel.style.cssText = \"display:block;margin:16px 0 6px;font-weight:600;\";\nconst problemNotes = document.createElement(\"textarea\");\nproblemNotes.rows = 3;\nproblemNotes.maxLength = 4000;\nproblemNotes.style.cssText = \"box-sizing:border-box;width:100%;max-width:100%;font-size:16px;\";\nproblemNotesLabel.appendChild(problemNotes);\nconst problemSubmit = document.createElement(\"button\");\nproblemSubmit.id = \"gw-submit-problem\";\nproblemSubmit.type = \"button\";\nproblemSubmit.textContent = \"Submit Issue \/ Rework\";\nproblemSubmit.style.width = \"100%\";\nconst problemSubmitMessage = document.createElement(\"p\");\nproblemSubmitMessage.id = \"gw-problem-submit-message\";\nproblemSubmitMessage.setAttribute(\"role\", \"status\");\nconst problemListHeading = document.createElement(\"h4\");\nproblemListHeading.textContent = \"Issue \/ Rework History (Open and Resolved)\";\nconst problemRefresh = document.createElement(\"button\");\nproblemRefresh.id = \"gw-refresh-problems\";\nproblemRefresh.type = \"button\";\nproblemRefresh.textContent = \"Refresh Issues \/ Rework\";\nproblemRefresh.style.width = \"100%\";\nconst problemList = document.createElement(\"div\");\nproblemList.id = \"gw-problem-list\";\nproblemList.setAttribute(\"aria-live\", \"polite\");\nproblemPanel.append(\n  problemHeading, problemHelp, problemIssueTypeLabel, problemWorkersLabel,\n  problemDescriptionLabel, problemDescription, problemActionLabel, problemReworkCostLabel,\n  problemNotesLabel, problemSubmit, problemSubmitMessage, problemListHeading,\n  problemRefresh, problemList\n);\ndrawingPanel.insertAdjacentElement(\"afterend\", problemToggle);\nproblemToggle.insertAdjacentElement(\"afterend\", problemPanel);\n\nlet problemJobId = null;\nlet problemGeneration = 0;\nlet problemRequestId = 0;\nlet problemSubmitBusy = false;\nlet problemResolveBusy = false;\n\nfunction resetProblemView() {\n  problemGeneration++;\n  problemRequestId++;\n  problemJobId = null;\n  problemSubmitBusy = false;\n  problemResolveBusy = false;\n  problemToggle.hidden = true;\n  problemToggle.setAttribute(\"aria-expanded\", \"false\");\n  problemPanel.hidden = true;\n  problemIssueType.value = \"\";\n  problemWorkers.value = \"\";\n  for (const option of problemWorkerSelect.options) {\n    option.selected = false;\n  }\n  problemDescription.value = \"\";\n  problemAction.value = \"\";\n  problemReworkCost.value = \"\";\n  problemNotes.value = \"\";\n  problemIssueType.disabled = false;\n  problemWorkers.disabled = false;\n  problemWorkerSelect.disabled = false;\n  problemDescription.disabled = false;\n  problemAction.disabled = false;\n  problemReworkCost.disabled = false;\n  problemNotes.disabled = false;\n  problemSubmit.disabled = false;\n  problemRefresh.disabled = false;\n  problemSubmitMessage.textContent = \"\";\n  problemList.replaceChildren();\n}\n\nfunction problemIsCurrent(jobId, generation) {\n  return !!client && !logout.hidden && !jobSearch.hidden && !dashboard.hidden &&\n    !problemToggle.hidden && !problemPanel.hidden &&\n    problemJobId === jobId && jobIdInput.value.trim() === jobId &&\n    (generation === undefined || generation === problemGeneration);\n}\n\nfunction configureProblemView(jobId, role) {\n  resetProblemView();\n  if (!\/^(owner|office|project_manager|installer|fabricator)$\/.test(role || \"\") ||\n      !jobId || dashboard.hidden || logout.hidden ||\n      jobIdInput.value.trim() !== jobId) return;\n  problemJobId = jobId;\n  problemToggle.hidden = false;\nvoid loadProblemWorkerOptions();\n}\n\nfunction problemEmployeeLabel(userId, currentUserId) {\n  if (!userId) return \"Not recorded\";\n  return userId === currentUserId ? \"You\" : \"Employee \" + String(userId).slice(0, 8);\n}\n\nasync function loadProblemList() {\n  const jobId = problemJobId;\n  if (!problemIsCurrent(jobId)) return;\n  const generation = problemGeneration;\n  const requestId = ++problemRequestId;\n  problemRefresh.disabled = true;\n  problemList.textContent = \"Loading problem reports...\";\n  try {\n    const { data: auth, error: authError } = await client.auth.getUser();\n    if (authError || !auth.user) throw new Error(\"Please log in again.\");\n    const { data: isActive, error: accessError } =\n      await client.rpc(\"gw_employee_is_active\");\n    if (accessError || isActive !== true)\n      throw new Error(\"Unable to verify active Portal access.\");\n    const { data: problems, error } = await client.from(\"job_problems\")\n      .select(\"id, job_id, issue_type, workers, description, action_needed, rework_cost, photo_path, notes, status, created_by, created_at, resolution_notes, resolved_by, resolved_at\")\n      .eq(\"job_id\", jobId)\n      .order(\"created_at\", { ascending: false })\n      .order(\"id\", { ascending: false });\n    if (error) throw error;\n    if (!problemIsCurrent(jobId, generation) || requestId !== problemRequestId) return;\n    problemList.replaceChildren();\n    if (!problems || problems.length === 0) {\n      problemList.textContent = \"No problem reports for this job yet.\";\n      return;\n    }\n    for (const problem of problems) {\n      const row = document.createElement(\"section\");\n      row.style.cssText =\n        \"box-sizing:border-box;padding:14px 0;border-bottom:1px solid #e2e8f0;overflow-wrap:anywhere;\";\n      const heading = document.createElement(\"h4\");\n      heading.textContent = \"Report #\" + problem.id + \" \u2014 \" + (problem.issue_type || \"Issue\") + \" \u2014 \" + problem.status;\n      const report = document.createElement(\"p\");\n      report.textContent = problem.description;\n      report.style.cssText = \"white-space:pre-wrap;overflow-wrap:anywhere;\";\n      const details = document.createElement(\"p\");\n      const detailParts = [];\n      if (problem.workers) detailParts.push(\"Worker(s): \" + problem.workers);\n      if (problem.action_needed) detailParts.push(\"Action Needed: \" + problem.action_needed);\n      if (problem.rework_cost !== null && problem.rework_cost !== undefined && problem.rework_cost !== \"\") {\n        const cost = Number(problem.rework_cost);\n        detailParts.push(\"Rework Cost: \" + (Number.isFinite(cost) ? \"$\" + cost.toFixed(2) : problem.rework_cost));\n      }\n      if (problem.notes) detailParts.push(\"Internal Notes: \" + problem.notes);\n      details.textContent = detailParts.join(\"\\n\");\n      details.style.cssText = \"white-space:pre-wrap;overflow-wrap:anywhere;\";\n      const submitted = document.createElement(\"p\");\n      submitted.textContent = \"Reported: \" +\n        (problem.created_at ? new Date(problem.created_at).toLocaleString() : \"Not recorded\") +\n        \" | By: \" + problemEmployeeLabel(problem.created_by, auth.user.id);\n      row.append(heading, report);\n      gwRE3Optional(report,problem.description);\n      if (details.textContent) row.appendChild(details);\n      row.appendChild(submitted);\n      if (problem.status === \"Resolved\") {\n        const resolved = document.createElement(\"p\");\n        resolved.textContent = \"Resolved: \" +\n          (problem.resolved_at ? new Date(problem.resolved_at).toLocaleString() : \"Not recorded\") +\n          \" | By: \" + problemEmployeeLabel(problem.resolved_by, auth.user.id);\n        const resolution = document.createElement(\"p\");\n        resolution.textContent = \"Resolution notes: \" + (problem.resolution_notes || \"None\");\n        resolution.style.cssText = \"white-space:pre-wrap;overflow-wrap:anywhere;\";\n        row.append(resolved, resolution);\n        if(problem.resolution_notes)gwRE3Optional(resolution,\"Resolution notes: \"+problem.resolution_notes);\n      } else if (problem.status === \"Open\") {\n        const notesLabel = document.createElement(\"label\");\n        const notes = document.createElement(\"textarea\");\n        notes.id = \"gw-problem-resolution-\" + problem.id;\n        notesLabel.htmlFor = notes.id;\n        notesLabel.textContent = \"Resolution notes (optional)\";\n        notesLabel.style.cssText = \"display:block;margin:12px 0 6px;font-weight:600;\";\n        notes.maxLength = 4000;\n        notes.rows = 3;\n        notes.style.cssText =\n          \"box-sizing:border-box;width:100%;max-width:100%;font-size:16px;\";\n        const resolveButton = document.createElement(\"button\");\n        resolveButton.type = \"button\";\n        resolveButton.textContent = \"Mark Resolved\";\n        resolveButton.style.width = \"100%\";\n        const rowMessage = document.createElement(\"p\");\n        rowMessage.setAttribute(\"role\", \"status\");\n        resolveButton.addEventListener(\"click\", async function () {\n          if (!problemIsCurrent(jobId, generation) || problemResolveBusy ||\n              resolveButton.disabled) return;\n          if (!window.confirm(\"Mark report #\" + problem.id +\n              \" as Resolved? The original report will remain saved.\")) return;\n          problemResolveBusy = true;\n          resolveButton.disabled = true;\n          notes.disabled = true;\n          rowMessage.textContent = \"Resolving problem...\";\n          try {\n            const { data: userData, error: userError } = await client.auth.getUser();\n            if (userError || !userData.user) throw new Error(\"Please log in again.\");\n            const { data: resolvedId, error: resolveError } = await client.rpc(\n              \"gw_resolve_job_problem\",\n              { p_problem_id: problem.id, p_resolution_notes: notes.value.trim() || null }\n            );\n            if (resolveError) throw resolveError;\n            if (Number(resolvedId) !== Number(problem.id))\n              throw new Error(\"The resolution could not be verified. Refresh before trying again.\");\n            if (!problemIsCurrent(jobId, generation)) return;\n            rowMessage.textContent = \"Resolved. Refreshing saved history...\";\n            await loadProblemList();\n          } catch (error) {\n            if (problemIsCurrent(jobId, generation))\n              rowMessage.textContent = \"Unable to resolve: \" + error.message;\n       } finally {\n  if (problemGeneration === generation) {\n    if (problemJobId === jobId) {\n      if (!logout.hidden) {\n        problemSubmitBusy = false;\n        problemSubmit.disabled = false;\n        problemIssueType.disabled = false;\n        problemWorkers.disabled = false;\n        problemDescription.disabled = false;\n        problemAction.disabled = false;\n        problemReworkCost.disabled = false;\n        problemNotes.disabled = false;\n      }\n    }\n  }\n}\n        });\n        row.append(notesLabel, notes, resolveButton, rowMessage);\n      }\n      problemList.appendChild(row);\n    }\n  } catch (error) {\n    if (problemIsCurrent(jobId, generation) && requestId === problemRequestId)\n      problemList.textContent = \"Unable to load problems: \" + error.message;\n  } finally {\n    if (problemIsCurrent(jobId, generation) && requestId === problemRequestId)\n      problemRefresh.disabled = false;\n  }\n}\n\nproblemToggle.addEventListener(\"click\", function () {\n  if (!client || problemToggle.hidden || dashboard.hidden || logout.hidden ||\n      !problemJobId || jobIdInput.value.trim() !== problemJobId) return;\n  problemPanel.hidden = !problemPanel.hidden;\n  problemToggle.setAttribute(\"aria-expanded\", String(!problemPanel.hidden));\n  if (problemPanel.hidden) {\n    problemRequestId++;\n    problemList.replaceChildren();\n    problemRefresh.disabled = false;\n  } else {\n    void loadProblemList();\n  }\n});\n\nproblemRefresh.addEventListener(\"click\", function () {\n  if (!problemSubmitBusy && !problemResolveBusy) void loadProblemList();\n});\n\nproblemSubmit.addEventListener(\"click\", async function () {\n  const jobId = problemJobId;\n  if (!problemIsCurrent(jobId) || problemSubmitBusy) return;\n  const issueType = problemIssueType.value.trim();\n  const workers = problemWorkers.value.trim();\n  const description = problemDescription.value.trim();\n  const actionNeeded = problemAction.value.trim();\n  const notesValue = problemNotes.value.trim();\n  const rawCost = problemReworkCost.value.trim();\n  if (!issueType) {\n    problemSubmitMessage.textContent = \"Select an Issue Type.\";\n    return;\n  }\n  if (!description || description.length > 4000) {\n    problemSubmitMessage.textContent = \"Enter a problem description (1\u20134000 characters).\";\n    return;\n  }\n  let reworkCost = null;\n  if (rawCost !== \"\") {\n    reworkCost = Number(rawCost);\n    if (!Number.isFinite(reworkCost) || reworkCost < 0) {\n      problemSubmitMessage.textContent = \"Enter a valid Rework Cost of 0 or more.\";\n      return;\n    }\n  }\n  problemSubmitBusy = true;\n  problemSubmit.disabled = true;\n  problemIssueType.disabled = true;\n  problemWorkers.disabled = true;\n  problemWorkerSelect.disabled = true;\n  problemDescription.disabled = true;\n  problemAction.disabled = true;\n  problemReworkCost.disabled = true;\n  problemNotes.disabled = true;\n  const generation = problemGeneration;\n  problemSubmitMessage.textContent = \"Submitting problem...\";\n  try {\n    const { data: auth, error: authError } = await client.auth.getUser();\n    if (authError || !auth.user) throw new Error(\"Please log in again.\");\n    const { data: isActive, error: accessError } =\n      await client.rpc(\"gw_employee_is_active\");\n    if (accessError || isActive !== true)\n      throw new Error(\"Unable to verify active Portal access.\");\n    if (!problemIsCurrent(jobId, generation)) return;\n    const { data: saved, error } = await client.from(\"job_problems\")\n      .insert({\n        job_id: jobId,\n        issue_type: issueType,\n        workers: workers || null,\n        description,\n        action_needed: actionNeeded || null,\n        rework_cost: reworkCost,\n        photo_path: null,\n        notes: notesValue || null,\n        created_by: auth.user.id\n      })\n      .select(\"id, job_id, status\").maybeSingle();\n    if (error) throw error;\n    if (!saved || saved.job_id !== jobId || saved.status !== \"Open\")\n      throw new Error(\"Submission could not be confirmed. Refresh the list before retrying.\");\n    if (!problemIsCurrent(jobId, generation)) return;\n\n    const selectedWorkerRows = Array.from(problemWorkerSelect.selectedOptions)\n      .filter(function (option) { return !!option.value; })\n      .map(function (option) {\n        return {\n          problem_id: saved.id,\n          worker_user_id: option.value,\n          worker_name: option.dataset.employeeName || option.textContent.split(\" \u2014 \")[0]\n        };\n      });\n\n    if (selectedWorkerRows.length > 0) {\n      const workerResult = await client\n        .from(\"job_problem_workers\")\n        .insert(selectedWorkerRows);\n\n      if (workerResult.error) {\n        problemSubmitMessage.textContent =\n          \"Issue \/ Rework #\" + saved.id +\n          \" was saved, but worker link failed: \" + workerResult.error.message +\n          \". Do not submit the issue again.\";\n        await loadProblemList();\n        return;\n      }\n    }\n\n    problemIssueType.value = \"\";\n    problemWorkers.value = \"\";\n    for (const option of problemWorkerSelect.options) {\n      option.selected = false;\n    }\n    problemDescription.value = \"\";\n    problemAction.value = \"\";\n    problemReworkCost.value = \"\";\n    problemNotes.value = \"\";\n    problemSubmitMessage.textContent = \"Issue \/ Rework #\" + saved.id + \" submitted and saved.\";\n    await loadProblemList();\n  } catch (error) {\n    if (problemIsCurrent(jobId, generation))\n      problemSubmitMessage.textContent = \"Unable to submit: \" + error.message +\n        \". Check the problem list before retrying.\";\n } finally {\n  if (problemGeneration === generation) {\n    if (problemJobId === jobId) {\n      if (!logout.hidden) {\n        problemSubmitBusy = false;\n        problemSubmit.disabled = false;\n        problemIssueType.disabled = false;\n        problemWorkers.disabled = false;\n        problemWorkerSelect.disabled = false;\n        problemDescription.disabled = false;\n        problemAction.disabled = false;\n        problemReworkCost.disabled = false;\n        problemNotes.disabled = false;\n      }\n    }\n  }\n}\n});\n\ndocument.getElementById(\"gw-final-measurement\")\n   .insertAdjacentElement(\"afterend\", measurementDashboard);\nmeasurementDashboard.insertAdjacentElement(\"afterend\", measurementForm);\n\ndocument.getElementById(\"gw-site-preparation\")\n   .insertAdjacentElement(\"afterend\", preparationDashboard);\npreparationDashboard.insertAdjacentElement(\"afterend\", preparationForm);\n\ndocument.getElementById(\"gw-job-photos\")\n  .insertAdjacentElement(\n    \"afterend\",\n    document.getElementById(\"gw-photo-form\")\n  );\n resetWorkDashboards();\n document.head.appendChild(script);\n savePassword.addEventListener(\"click\", async function () {\n  const newValue = newPassword.value;\n  const confirmValue = confirmPassword.value;\n\n  if (newValue.length < 12) {\n    passwordMessage.textContent =\n      \"Password must be at least 12 characters.\";\n    return;\n  }\n\n  if (newValue !== confirmValue) {\n    passwordMessage.textContent =\n      \"Passwords do not match.\";\n    return;\n  }\n\n  if (!client) {\n    passwordMessage.textContent =\n      \"Login system is still loading.\";\n    return;\n  }\n\n  savePassword.disabled = true;\n  passwordMessage.textContent = \"Setting password...\";\n\n  try {\n    const { data, error: authError } =\n      await client.auth.getUser();\n\n    if (authError || !data.user) {\n      passwordMessage.textContent =\n        \"Invitation not verified. Please open your invitation link.\";\n      return;\n    }\n\n    const { error } = await client.auth.updateUser({\n      password: newValue\n    });\n\n    if (error) {\n      passwordMessage.textContent =\n        \"Unable to set password: \" + error.message;\n      return;\n    }\n\n    newPassword.value = \"\";\n    confirmPassword.value = \"\";\n    passwordMessage.textContent = \"Password set successfully! Opening Portal...\";\n    clearRecoveryMarker();\n    recoveringPassword = false;\n    setPasswordForm.hidden = true;\n    await showSignedIn();\n  } catch (error) {\n    passwordMessage.textContent =\n      \"Connection error. Please try again.\";\n  } finally {\n    savePassword.disabled = false;\n  }\n});\n  }\n\n  if (document.readyState === \"loading\") {\n    document.addEventListener(\"DOMContentLoaded\", startPortal);\n  } else {\n    startPortal();\n  }\n})();\n\n\/\/ ================================================================\n\/\/ GW PORTAL LANGUAGE SWITCHER\n\/\/ English \/ Traditional Chinese \/ Spanish\n\/\/ This block is deliberately outside startPortal(). It waits for the DOM\n\/\/ when needed, but also starts immediately if WordPress loaded the page first.\n\/\/ ================================================================\n(function () {\n  const LANGUAGE_KEY = \"gwPortalLanguage\";\n\n  const gwTranslations = {\n    en: {\n      employeeLogin: \"Employee Login\",\n      email: \"Email\",\n      password: \"Password\",\n      remember: \"Remember Me on this device\",\n      login: \"Log In\"\n    },\n\n    zh: {\n      employeeLogin: \"\u54e1\u5de5\u767b\u5165\",\n      email: \"\u96fb\u90f5\",\n      password: \"\u5bc6\u78bc\",\n      remember: \"\u5728\u6b64\u88dd\u7f6e\u8a18\u4f4f\u6211\",\n      login: \"\u767b\u5165\"\n    },\n\n    es: {\n      employeeLogin: \"Inicio de sesi\u00f3n de empleados\",\n      email: \"Correo electr\u00f3nico\",\n      password: \"Contrase\u00f1a\",\n      remember: \"Recordarme en este dispositivo\",\n      login: \"Iniciar sesi\u00f3n\"\n    }\n  };\n\n  function gwSetLanguage(lang) {\n    if (!Object.prototype.hasOwnProperty.call(gwTranslations, lang)) {\n      lang = \"en\";\n    }\n\n    const t = gwTranslations[lang];\n\n    const loginTitle = document.querySelector(\".gw-login > h2\");\n    const emailLabel = document.querySelector('label[for=\"gw-email\"]');\n    const passwordLabel = document.querySelector('label[for=\"gw-password\"]');\n    const rememberCheckbox = document.getElementById(\"gw-remember\");\n    const loginButton = document.querySelector('#gw-login-form button[type=\"submit\"]');\n\n    if (loginTitle) loginTitle.textContent = t.employeeLogin;\n    if (emailLabel) emailLabel.textContent = t.email;\n    if (passwordLabel) passwordLabel.textContent = t.password;\n\n    if (rememberCheckbox) {\n      const rememberLabel = rememberCheckbox.closest(\"label\");\n      if (rememberLabel) {\n        \/\/ Preserve the existing checkbox element and its checked state.\n        rememberLabel.replaceChildren(\n          rememberCheckbox,\n          document.createTextNode(\" \" + t.remember)\n        );\n      }\n    }\n\n    if (loginButton) loginButton.textContent = t.login;\n\n    document.querySelectorAll(\".gw-lang-btn\").forEach(function (button) {\n      const active = button.dataset.lang === lang;\n      button.classList.toggle(\"active\", active);\n      button.setAttribute(\"aria-pressed\", active ? \"true\" : \"false\");\n    });\n\n    try {\n      localStorage.setItem(LANGUAGE_KEY, lang);\n    } catch (_error) {\n      \/\/ Language still works for this page even if storage is unavailable.\n    }\n\n    document.documentElement.lang = lang === \"zh\" ? \"zh-Hant\" : lang;\n\n    \/\/ Notify signed-in Portal features that the display language changed.\n    window.dispatchEvent(new CustomEvent(\"gw-language-changed\", {\n      detail: { lang: lang }\n    }));\n  }\n\n  function startGwTranslation() {\n    const buttons = document.querySelectorAll(\".gw-lang-btn\");\n\n    if (!buttons.length) {\n      console.warn(\"GW Portal language buttons were not found.\");\n      return;\n    }\n\n    buttons.forEach(function (button) {\n      \/\/ Prevent duplicate listeners if a page builder re-runs this script.\n      if (button.dataset.gwLanguageBound === \"1\") return;\n      button.dataset.gwLanguageBound = \"1\";\n\n      button.addEventListener(\"click\", function () {\n        gwSetLanguage(button.dataset.lang || \"en\");\n      });\n    });\n\n    let savedLanguage = \"en\";\n    try {\n      savedLanguage = localStorage.getItem(LANGUAGE_KEY) || \"en\";\n    } catch (_error) {\n      savedLanguage = \"en\";\n    }\n\n    gwSetLanguage(savedLanguage);\n  }\n\n  \/\/ Expose only the setter so the rest of the Portal can reuse the same\n  \/\/ language choice when the full Portal translation layer is added.\n  window.gwSetLanguage = gwSetLanguage;\n\n  if (document.readyState === \"loading\") {\n    document.addEventListener(\"DOMContentLoaded\", startGwTranslation, { once: true });\n  } else {\n    startGwTranslation();\n  }\n})();\n\n\/\/ ================================================================\n\/\/ GW FIELD PORTAL UI LANGUAGE LABELS V1\n\/\/ Translates static interface text only. Never translates addresses, names,\n\/\/ job IDs, materials, or free-text records. Works for dynamically opened tabs.\n\/\/ ================================================================\n(function () {\n  const dictionary = {\n    \"On-Site Work\": [\"\u73fe\u5834\u65bd\u5de5\", \"Trabajo en sitio\"],\n    \"Field Job Details\": [\"\u73fe\u5834\u5de5\u7a0b\u8a73\u60c5\", \"Detalles del trabajo en sitio\"],\n    \"\u2190 Back to Job Board\": [\"\u2190 \u8fd4\u56de\u5de5\u7a0b\u5217\u8868\", \"\u2190 Volver a la lista de trabajos\"],\n    \"Important Job Notes\": [\"\u91cd\u8981\u5de5\u7a0b\u5099\u8a3b\", \"Notas importantes del trabajo\"],\n    \"Before Photos\": [\"\u65bd\u5de5\u524d\u7167\u7247\", \"Fotos antes\"],\n    \"After Photos\": [\"\u65bd\u5de5\u5f8c\u7167\u7247\", \"Fotos despu\u00e9s\"],\n    \"Issue Photo\": [\"\u554f\u984c\u7167\u7247\", \"Fotos de problemas\"],\n    \"Issue Photos\": [\"\u554f\u984c\u7167\u7247\", \"Fotos de problemas\"],\n    \"Additional Work\": [\"\u984d\u5916\u5de5\u7a0b\", \"Trabajo adicional\"],\n    \"Extra on-site work\": [\"\u984d\u5916\u73fe\u5834\u65bd\u5de5\", \"Trabajo adicional en sitio\"],\n    \"Before installation\": [\"\u5b89\u88dd\u524d\", \"Antes de instalar\"],\n    \"After installation\": [\"\u5b89\u88dd\u5f8c\", \"Despu\u00e9s de instalar\"],\n    \"Issues & damage\": [\"\u554f\u984c\u53ca\u640d\u58de\", \"Problemas y da\u00f1os\"],\n    \"Measurements & specifications\": [\"\u91cf\u5c3a\u53ca\u898f\u683c\", \"Medidas y especificaciones\"],\n    \"Not completed\": [\"\u672a\u5b8c\u6210\", \"No completado\"],\n    \"Checking\u2026\": [\"\u6aa2\u67e5\u4e2d\u2026\", \"Comprobando\u2026\"],\n    \"Photo count unavailable\": [\"\u7167\u7247\u6578\u91cf\u672a\u80fd\u53d6\u5f97\", \"Cantidad de fotos no disponible\"],\n    \"Status unavailable\": [\"\u72c0\u614b\u672a\u80fd\u53d6\u5f97\", \"Estado no disponible\"],\n    \"No Issue\": [\"\u6c92\u6709\u554f\u984c\", \"Sin problemas\"],\n    \"Issue\": [\"\u6709\u554f\u984c\", \"Problema\"],\n    \"Solved\": [\"\u5df2\u89e3\u6c7a\", \"Resuelto\"],\n    \"In Process\": [\"\u9032\u884c\u4e2d\", \"En proceso\"],\n    \"Fabricated\": [\"\u5df2\u52a0\u5de5\", \"Fabricado\"],\n    \"On Hold\": [\"\u66ab\u505c\", \"En espera\"],\n    \"\ud83d\udccd Map\": [\"\ud83d\udccd \u5730\u5716\", \"\ud83d\udccd Mapa\"],\n    \"\u260e Call\": [\"\u260e \u81f4\u96fb\", \"\u260e Llamar\"],\n    \"+ Add Location\": [\"+ \u65b0\u589e\u4f4d\u7f6e\", \"+ Agregar ubicaci\u00f3n\"],\n    \"Save Note\": [\"\u5132\u5b58\u5099\u8a3b\", \"Guardar nota\"],\n    \"Select Photos\": [\"\u9078\u64c7\u7167\u7247\", \"Seleccionar fotos\"],\n    \"Remove\": [\"\u79fb\u9664\", \"Eliminar\"],\n    \"Write the location and work details...\": [\"\u8f38\u5165\u4f4d\u7f6e\u53ca\u65bd\u5de5\u8a73\u60c5\u2026\", \"Escriba la ubicaci\u00f3n y los detalles del trabajo...\"],\n    \"Photo description (optional)\": [\"\u7167\u7247\u8aaa\u660e\uff08\u9078\u586b\uff09\", \"Descripci\u00f3n de la foto (opcional)\"],\n    \"Note saved.\": [\"\u5099\u8a3b\u5df2\u5132\u5b58\u3002\", \"Nota guardada.\"],\n    \"Photos saved.\": [\"\u7167\u7247\u5df2\u5132\u5b58\u3002\", \"Fotos guardadas.\"],\n    \"Translate\": [\"\u7ffb\u8b6f\", \"Traducir\"],\n    \"Show Original\": [\"\u986f\u793a\u539f\u6587\", \"Mostrar original\"],\n\n    \"Take Photo\": [\"\u62cd\u7167\", \"Tomar foto\"],\n    \"Photo Library\": [\"\u76f8\u7247\u5eab\", \"Biblioteca de fotos\"],\n    \"Add Photo\": [\"\u65b0\u589e\u76f8\u7247\", \"Agregar foto\"],\n    \"Description (Optional)\": [\"\u63cf\u8ff0\uff08\u9078\u586b\uff09\", \"Descripci\u00f3n (opcional)\"],\n    \"Log Out\": [\"\u767b\u51fa\", \"Cerrar sesi\u00f3n\"],\n    \"Bulletin Board\": [\"\u516c\u544a\u6b04\", \"Tabl\u00f3n de anuncios\"],\n    \"\u2190 Back to Portal\": [\"\u2190 \u8fd4\u56de\u5de5\u4f5c\u5e73\u53f0\", \"\u2190 Volver al portal\"],\n    \"+ Add Announcement\": [\"\uff0b \u65b0\u589e\u901a\u544a\", \"+ Agregar nota\"],\n    \"Closed Announcements\": [\"\u5df2\u5b8c\u6210\u901a\u544a\", \"Notas completadas\"],\n    \"Post Note\": [\"\u767c\u4f48\u901a\u544a\", \"Publicar nota\"],\n    \"Save Changes\": [\"\u5132\u5b58\u4fee\u6539\", \"Guardar cambios\"],\n    \"Save\": [\"\u5132\u5b58\", \"Guardar\"],\n    \"Cancel\": [\"\u53d6\u6d88\", \"Cancelar\"],\n    \"Edit\": [\"\u7de8\u8f2f\", \"Editar\"],\n    \"Delete\": [\"\u522a\u9664\", \"Eliminar\"],\n    \"Done\": [\"\u5b8c\u6210\", \"Hecho\"],\n    \"Title\": [\"\u6a19\u984c\", \"T\u00edtulo\"],\n    \"Note\": [\"\u5099\u8a3b\", \"Nota\"],\n    \"For\": [\"\u5c0d\u8c61\", \"Para\"],\n    \"Everyone\": [\"\u6240\u6709\u54e1\u5de5\", \"Todos\"],\n    \"Installer\": [\"\u5b89\u88dd\u5de5\", \"Instalador\"],\n    \"Fabricator\": [\"\u52a0\u5de5\u5de5\", \"Fabricador\"],\n    \"Office\": [\"\u8fa6\u516c\u5ba4\", \"Oficina\"],\n    \"Project Manager\": [\"\u5de5\u7a0b\u7d93\u7406\", \"Gerente de proyectos\"],\n    \"Owner\": [\"\u8001\u95c6\", \"Propietario\"],\n    \"Employee Accounts (Owner Only)\": [\"\u54e1\u5de5\u5e33\u6236\uff08\u50c5\u8001\u95c6\uff09\", \"Cuentas de empleados (solo propietario)\"],\n    \"Add Employee\": [\"\u65b0\u589e\u54e1\u5de5\", \"Agregar empleado\"],\n    \"Employee name\": [\"\u54e1\u5de5\u59d3\u540d\", \"Nombre del empleado\"],\n    \"Employee email\": [\"\u54e1\u5de5\u96fb\u90f5\", \"Correo del empleado\"],\n    \"Employee role\": [\"\u54e1\u5de5\u8077\u4f4d\", \"Cargo del empleado\"],\n    \"Select role\": [\"\u9078\u64c7\u8077\u4f4d\", \"Seleccionar cargo\"],\n    \"Send Employee Invitation\": [\"\u767c\u9001\u54e1\u5de5\u9080\u8acb\", \"Enviar invitaci\u00f3n\"],\n    \"Edit Name\": [\"\u4fee\u6539\u59d3\u540d\", \"Editar nombre\"],\n    \"Save Name\": [\"\u5132\u5b58\u59d3\u540d\", \"Guardar nombre\"],\n    \"Edit Role\": [\"\u4fee\u6539\u8077\u4f4d\", \"Editar cargo\"],\n    \"Save Role\": [\"\u5132\u5b58\u8077\u4f4d\", \"Guardar cargo\"],\n    \"Job ID\": [\"\u5de5\u7a0b\u7de8\u865f\", \"ID del trabajo\"],\n    \"Job ID (optional)\": [\"\u5de5\u7a0b\u7de8\u865f\uff08\u53ef\u9078\uff09\", \"ID del trabajo (opcional)\"],\n    \"Job Address\": [\"\u5de5\u7a0b\u5730\u5740\", \"Direcci\u00f3n del trabajo\"],\n    \"Search Job\": [\"\u641c\u5c0b\u5de5\u7a0b\", \"Buscar trabajo\"],\n    \"Find Job\": [\"\u5c0b\u627e\u5de5\u7a0b\", \"Buscar trabajo\"],\n    \"This Month Job IDs\": [\"\u672c\u6708\u5de5\u7a0b\", \"Trabajos de este mes\"],\n    \"This Month Jobs\": [\"\u672c\u6708\u5de5\u7a0b\", \"Trabajos de este mes\"],\n    \"Loading...\": [\"\u8f09\u5165\u4e2d...\", \"Cargando...\"],\n    \"No Job IDs yet.\": [\"\u66ab\u6642\u672a\u6709\u5de5\u7a0b\u7de8\u865f\u3002\", \"Todav\u00eda no hay trabajos.\"],\n    \"Final Measurement\": [\"\u6700\u7d42\u91cf\u5c3a\", \"Medici\u00f3n final\"],\n    \"Job Details\": [\"\u5de5\u7a0b\u8a73\u60c5\", \"Detalles del trabajo\"],\n    \"Open Notes\": [\"\u516c\u958b\u5099\u8a3b\", \"Notas abiertas\"],\n    \"Office \/ Owner Notes\": [\"\u8fa6\u516c\u5ba4 \/ \u8001\u95c6\u5099\u8a3b\", \"Notas de oficina \/ propietario\"],\n    \"+ Add Note\": [\"+ \u65b0\u589e\u5099\u8a3b\", \"+ A\u00f1adir nota\"],\n    \"Add Note\": [\"\u65b0\u589e\u5099\u8a3b\", \"A\u00f1adir nota\"],\n    \"Load Older Notes\": [\"\u8f09\u5165\u8f03\u65e9\u5099\u8a3b\", \"Cargar notas anteriores\"],\n    \"Site Preparation\": [\"\u5de5\u5730\u6e96\u5099\", \"Preparaci\u00f3n del sitio\"],\n    \"Problem Report\": [\"\u554f\u984c\u5831\u544a\", \"Informe de problema\"],\n    \"Photos\": [\"\u76f8\u7247\", \"Fotos\"],\n    \"Upload Photos\": [\"\u4e0a\u50b3\u76f8\u7247\", \"Subir fotos\"],\n    \"Installation\": [\"\u5b89\u88dd\", \"Instalaci\u00f3n\"],\n    \"Fabrication\": [\"\u52a0\u5de5\", \"Fabricaci\u00f3n\"],\n    \"Approved\": [\"\u5df2\u6279\u51c6\", \"Aprobado\"],\n    \"Completed\": [\"\u5df2\u5b8c\u6210\", \"Completado\"],\n    \"Status\": [\"\u72c0\u614b\", \"Estado\"],\n    \"Date\": [\"\u65e5\u671f\", \"Fecha\"],\n    \"Address\": [\"\u5730\u5740\", \"Direcci\u00f3n\"],\n    \"Material\": [\"\u6750\u6599\", \"Material\"],\n    \"Notes\": [\"\u5099\u8a3b\", \"Notas\"],\n    \"Refresh\": [\"\u91cd\u65b0\u6574\u7406\", \"Actualizar\"],\n    \"Back\": [\"\u8fd4\u56de\", \"Volver\"],\n    \"Search\": [\"\u641c\u5c0b\", \"Buscar\"],\n    \"Submit\": [\"\u63d0\u4ea4\", \"Enviar\"],\n    \"Close\": [\"\u95dc\u9589\", \"Cerrar\"],\n    \"Dashboard\": [\"\u4e3b\u9801\", \"Inicio\"],\n    \"Load Job\": [\"\u8f09\u5165\u5de5\u7a0b\", \"Cargar trabajo\"],\n    \"Upload All Photos\": [\"\u4e0a\u50b3\u6240\u6709\u76f8\u7247\", \"Subir todas las fotos\"],\n    \"Add More Photos\": [\"\u65b0\u589e\u66f4\u591a\u76f8\u7247\", \"Agregar m\u00e1s fotos\"],\n    \"Clear Pending Photos\": [\"\u6e05\u9664\u5f85\u4e0a\u50b3\u76f8\u7247\", \"Borrar fotos pendientes\"],\n    \"\u2190 Job Details\": [\"\u2190 \u5de5\u7a0b\u8a73\u60c5\", \"\u2190 Detalles del trabajo\"]\n  };\n  const gwRE3ExtraKeys=new Set([\"On-Site Work\",\"Field Job Details\",\"\u2190 Back to Job Board\",\"Important Job Notes\",\"Before Photos\",\"After Photos\",\"Issue Photo\",\"Issue Photos\",\"Additional Work\",\"Extra on-site work\",\"Before installation\",\"After installation\",\"Issues & damage\",\"Measurements & specifications\",\"Not completed\",\"Checking\u2026\",\"Photo count unavailable\",\"Status unavailable\",\"No Issue\",\"Issue\",\"Solved\",\"In Process\",\"Fabricated\",\"On Hold\",\"\ud83d\udccd Map\",\"\u260e Call\",\"+ Add Location\",\"Save Note\",\"Select Photos\",\"Remove\",\"Write the location and work details...\",\"Photo description (optional)\",\"Note saved.\",\"Photos saved.\",\"Translate\",\"Show Original\"]);\n  const reverse = new Map();\n  Object.keys(dictionary).forEach(function (english) {\n    reverse.set(english, english);\n    dictionary[english].forEach(function (translated) { reverse.set(translated, english); });\n  });\n  const variableLabels = [\n    [\/^Bulletin Board\\s+\u2022 NEW \\(\\d+\\)$\/, \/^Bulletin Board\\s+\u2022 NEW \\((\\d+)\\)$\/],\n    [\/^Completed Notes \\(\\d+\\)$\/, \/^Completed Notes \\((\\d+)\\)$\/]\n  ];\n  function originalString(value) {\n    const clean = String(value || \"\").trim();\n    if (reverse.has(clean)) return reverse.get(clean);\n    return null;\n  }\n  function translateElement(el, language) {\n    if (!el || !el.isConnected || el.closest(\"#gw-monthly-job-ids\") || el.closest(\"[data-gw-re3-optional]\") || el.hasAttribute(\"data-gw-re3-label\")) return;\n    \/\/ Skip editor fields and all user\/business data displays.\n    const tag = el.tagName;\n    if (![\"BUTTON\", \"LABEL\", \"H1\", \"H2\", \"H3\", \"H4\", \"OPTION\"].includes(tag)) return;\n    if (el.querySelector(\"input,select,textarea,button\")) return;\n    const en = originalString(el.textContent);\n    if (!en) return;\n    if (gwRE3ExtraKeys.has(en) && !el.closest(\"#gw-focused-job-details,#gw-re173-action-header,#gw-measurement-dashboard,#gw-photo-form,[data-gw-re3-additional]\")) return;\n    const index = language === \"zh\" ? 0 : language === \"es\" ? 1 : -1;\n    const next = index < 0 ? en : dictionary[en][index];\n    if (el.textContent !== next) el.textContent = next;\n  }\n  let running = false;\n  function applyLanguage() {\n    if (running) return;\n    running = true;\n    try {\n      let lang = \"en\";\n      try { lang = localStorage.getItem(\"gwPortalLanguage\") || \"en\"; } catch (_) {}\n      document.querySelectorAll(\"button,label,h1,h2,h3,h4,option\").forEach(function (el) {\n        translateElement(el, lang);\n      });\n    } finally { running = false; }\n  }\n  function start() {\n    applyLanguage();\n    window.addEventListener(\"gw-language-changed\", applyLanguage);\n    let pending = false;\n    new MutationObserver(function () {\n      if (pending) return;\n      pending = true;\n      Promise.resolve().then(function () { pending = false; applyLanguage(); });\n    }).observe(document.body, { childList: true, subtree: true, characterData: true });\n  }\n  if (document.readyState === \"loading\") document.addEventListener(\"DOMContentLoaded\", start, { once: true });\n  else start();\n})();\n ;(() => {\n function init(){\n const root=document.querySelector('.gw-login'); if(!root)return;\n const detail=document.getElementById('gw-focused-job-details'), board=document.getElementById('gw-monthly-job-ids');\n const office=document.getElementById('gw-office-portal-link'), accounts=document.getElementById('gw-employee-directory-toggle');\n const logout=Array.from(root.querySelectorAll('button')).find(b=>['Log Out','\u767b\u51fa','Cerrar sesi\u00f3n'].includes(b.textContent.trim()));\n const schedule=document.getElementById('gw-weekly-schedule-entry'), report=document.getElementById('gw-annual-problem-toggle'), reportPanel=document.getElementById('gw-annual-problem-panel');\n if(!detail||!board||!office||!accounts||!logout||!schedule||!report||!reportPanel)return;\n const header=document.createElement('div');header.id='gw-global-navigation';header.hidden=true;header.style.cssText='display:grid;grid-template-columns:minmax(0,3fr) minmax(0,1fr);gap:8px;margin:10px 0;';\n const lang=root.querySelector('.gw-lang-btn');let anchor=lang;while(anchor&&anchor.parentElement!==root)anchor=anchor.parentElement;\n if(anchor)anchor.after(header);else root.prepend(header);\n header.append(logout);\n const heading=root.querySelector(\"#gw-home-heading\"); if(heading){heading.after(header);}\n const actionRow=root.querySelector(\"#gw-job-action-row\");const bulletin=root.querySelector(\"#gw-bulletin-entry\");if(actionRow&&bulletin){\n actionRow.prepend(schedule,bulletin);\n for(const b of actionRow.children){if(b.tagName!=='BUTTON')continue;\n b.style.removeProperty('flex');\n for(const [k,v] of Object.entries({'width':'100%','min-width':'0','max-width':'100%','box-sizing':'border-box','height':'auto','min-height':'44px','padding':'8px 6px','font-size':'14px','white-space':'normal','overflow-wrap':'normal','word-break':'normal','justify-self':'stretch'}))b.style.setProperty(k,v,'important');\n }\n }\n for(const b of [logout]){b.style.setProperty('width','100%','important');b.style.setProperty('margin','0','important');b.style.setProperty('min-width','0','important');b.style.setProperty('min-height','42px','important');}\n const footer=document.createElement('div');footer.className='gw-dashboard-footer';root.append(footer);const monthly=document.getElementById('gw-monthly-jobs-nav');\n footer.style.gridTemplateColumns='repeat(3,minmax(0,1fr))';\n report.style.setProperty('grid-column','1 \/ -1');report.style.setProperty('margin','0','important');footer.append(report);if(monthly)footer.append(monthly);footer.append(office,accounts);root.append(reportPanel);\n const management=document.createElement('details');management.className='gw-warm-management';const managementTitle=document.createElement('summary');const managementLabel=()=>{let lang='en';try{lang=localStorage.getItem('gwPortalLanguage')||'en';}catch(_){}managementTitle.textContent=({zh:'\u7ba1\u7406\u529f\u80fd',es:'Administraci\u00f3n'})[lang]||'Management';};managementLabel();window.addEventListener('gw-language-changed',managementLabel);footer.before(management);management.append(managementTitle,footer);\n accounts.style.width='';accounts.textContent='Employee Accounts';office.textContent='Office Portal';\n const sync=()=>{const signedIn=!logout.hidden;header.hidden=!signedIn;header.style.display=signedIn?'grid':'none';if(heading){if(signedIn&&heading.parentNode!==header)header.prepend(heading);if(!signedIn&&heading.parentNode===header)header.before(heading);}const visible=signedIn&&!board.hidden&&board.style.display!=='none'&&detail.hidden&&!(monthly&&monthly.hidden);footer.hidden=!visible;management.hidden=!visible||![report,monthly,office,accounts].some(b=>b&&!b.hidden&&b.style.display!=='none');if(!visible&&!reportPanel.hidden){reportPanel.hidden=true;report.setAttribute('aria-expanded','false');}};\n for(const el of [board,detail,logout,monthly,report,office,accounts].filter(Boolean))new MutationObserver(sync).observe(el,{attributes:true,attributeFilter:['hidden','style']});\n report.addEventListener('click',()=>{if(!reportPanel.hidden)reportPanel.scrollIntoView({block:'start',behavior:'smooth'});});sync();\n }\n if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',init,{once:true});else init();\n})();\n\n;(() => {\nconst css=`\n.gw-login{--gw-forest:#1769aa;--gw-ink:#263243;--gw-sand:#e4d3b5;--gw-paper:#ffffff;--gw-line:#d9d2c4;background:#faf9f6!important;color:var(--gw-ink)!important;border-color:var(--gw-line)!important;border-radius:18px!important;font-family:system-ui,-apple-system,Segoe UI,Arial,sans-serif!important;line-height:1.45;}\n.gw-login [hidden]{display:none!important}\n.gw-login :is(h1,h2,h3,h4){color:var(--gw-forest)!important}\n.gw-login button:not(.gw-job-code):not(.gw-field-action){background:var(--gw-forest)!important;color:white!important;border-color:transparent!important;border-radius:9px!important;min-height:44px;white-space:normal;}\n.gw-login button:disabled{opacity:.55;cursor:not-allowed}\n.gw-login :is(button,a,input,select,textarea,summary):focus-visible{outline:3px solid #a16a25!important;outline-offset:2px}\n.gw-login :is(input:not([type=checkbox]):not([type=radio]):not([type=file]),select,textarea){background:var(--gw-paper)!important;color:var(--gw-ink)!important;border:1px solid #bcb5a8!important;border-radius:8px!important;font-size:16px!important;min-height:44px;max-width:100%;box-sizing:border-box;}\n.gw-login a{color:#365b45;overflow-wrap:anywhere}\n.gw-login #gw-home-heading,.gw-login #gw-signed-in-name{color:var(--gw-forest)!important}\n.gw-login .gw-lang-btn{min-height:44px!important}\n.gw-login .gw-lang-btn[aria-pressed=false]{background:#e8dfcd!important;color:#51402b!important}\n.gw-login button.gw-warm-register{background:#dfe8d8!important;color:#365b45!important}\n.gw-login button.gw-warm-quote{background:#e8e0ec!important;color:#5c476a!important}\n.gw-login button:has(>img){background:transparent!important;padding:0!important}\n\n.gw-login #gw-weekly-schedule-entry{background:#e4d3b5!important;color:#51402b!important;font-size:16px!important;min-height:54px!important}\n.gw-login #gw-bulletin-entry{background:#eadbbf!important;color:#5c482b!important}\n.gw-login :is(#gw-monthly-job-ids,#gw-focused-job-details,#gw-employee-weekly-schedule,#gw-measurement-dashboard,#gw-bulletin-board){background:var(--gw-paper)!important;border-color:var(--gw-line)!important;border-radius:14px!important;color:var(--gw-ink)!important;}\n.gw-login #gw-monthly-job-ids [data-gw-board-kind]{padding:6px 4px;margin:4px 0;border-radius:0;background:transparent;border-bottom:1px solid #e3e6eb;}\n.gw-login #gw-monthly-job-ids [data-gw-board-kind=ready]{background:transparent}\n.gw-login #gw-monthly-job-ids [data-gw-board-kind=hold]{background:transparent}\n.gw-login #gw-monthly-job-ids [data-gw-board-kind=completed]{background:transparent}\n.gw-login #gw-monthly-job-ids [data-gw-board-kind=issues]{background:transparent}\n.gw-login #gw-monthly-job-ids .gw-board-heading{margin:0!important;font-size:16px!important}\n.gw-login #gw-monthly-job-ids .gw-board-heading button{background:transparent!important;color:#1769aa!important;min-height:44px!important;font-size:16px!important;}\n.gw-login #gw-monthly-job-ids .gw-board-heading button:after{content:'\u25be';float:right}.gw-login #gw-monthly-job-ids .gw-board-heading button[aria-expanded=false]:after{content:'\u25b8'}\n.gw-login :is(#gw-monthly-job-ids,#gw-re17-quotations) .gw-board-grid{grid-template-columns:repeat(auto-fill,minmax(124px,1fr))!important;gap:7px!important;margin:4px 0!important;}\n.gw-login :is(#gw-monthly-job-ids,#gw-re17-quotations) .gw-job-icon{background-color:#ffffff;border-color:#cfc8bb!important;color:var(--gw-ink)!important;padding:7px 4px!important;min-height:76px!important;}\n.gw-login :is(#gw-monthly-job-ids,#gw-re17-quotations) .gw-job-code{color:#1769aa!important;font-size:13px!important;min-height:36px!important;width:100%!important;}\n.gw-login :is(#gw-monthly-job-ids,#gw-re17-quotations) .gw-job-address{font-size:12px!important}\n.gw-login :is(#gw-focused-job-details,#gw-re173-action-header) .gw-field-job{background:#ffffff!important;color:var(--gw-ink)!important;border:1px solid #dce3eb!important;}\n.gw-login :is(#gw-focused-job-details,#gw-re173-action-header) :is(.gw-field-code,.gw-field-address,.gw-field-eyebrow,.gw-field-heading,.gw-field-title){color:var(--gw-forest)!important}\n.gw-login :is(#gw-focused-job-details,#gw-re173-action-header) .gw-field-action{background:#e4d3b5!important;color:#51402b!important;border:0!important;min-height:96px!important;}\n.gw-login :is(#gw-focused-job-details,#gw-re173-action-header) .gw-field-action[data-gw-action=before]{background:#e8dfcd!important;color:#695439!important}\n.gw-login :is(#gw-focused-job-details,#gw-re173-action-header) .gw-field-action[data-gw-action=after]{background:#dfe8d8!important;color:#365b45!important}\n.gw-login :is(#gw-focused-job-details,#gw-re173-action-header) .gw-field-action[data-gw-action=issue]{background:#f1dcd2!important;color:#873c29!important}\n.gw-login :is(#gw-focused-job-details,#gw-re173-action-header) .gw-field-action[data-gw-action=additional]{background:#e8e0ec!important;color:#5c476a!important}\n.gw-login :is(#gw-focused-job-details,#gw-re173-action-header) .gw-field-action small{color:inherit!important}\n.gw-login :is(#gw-focused-job-details,#gw-re173-action-header) .gw-field-action[data-state=alert]{outline:2px solid #a04d37!important;}\n.gw-login :is(#gw-focused-job-details,#gw-re173-action-header) .gw-field-action[data-state=done]{outline:2px solid #658568!important;}\n.gw-login details{border-color:var(--gw-line)!important;border-radius:10px!important;}\n.gw-login details>summary{cursor:pointer;color:#1769aa!important;font-weight:700;min-height:44px;box-sizing:border-box;padding:10px 8px!important;}\n.gw-login .gw-warm-measure-summary,.gw-login .gw-warm-management{background:#ebe5d9!important;padding:6px 10px!important;margin:10px 0!important;}\n.gw-login .gw-warm-measure-summary>div{background:#ffffff;padding:10px;border-radius:8px;overflow-wrap:anywhere;}\n.gw-login .gw-warm-day{background:#ffffff!important;border:0!important;border-radius:10px!important;margin:5px 0!important;padding:8px!important;}\n.gw-login .gw-warm-date{background:#1769aa!important;color:white!important;border:0!important;border-radius:8px!important;padding:7px 2px!important;}\n.gw-login .gw-warm-empty{background:#ebe7de!important;}.gw-login .gw-warm-empty .gw-warm-date{background:#ded9cf!important;color:#615849!important;}\n.gw-login .gw-warm-schedule-note{color:#873c29!important;font-weight:600;}\n.gw-login #gw-employee-weekly-schedule button[aria-pressed=false]{background:#e8dfcd!important;color:#51402b!important}\n.gw-login #gw-employee-weekly-schedule button[aria-pressed=true]{background:#1769aa!important;color:white!important}\n.gw-login .gw-dashboard-footer{gap:8px!important;}\n@media(max-width:480px){.gw-login{padding:10px!important}.gw-login :is(#gw-monthly-job-ids,#gw-re17-quotations) .gw-board-grid{grid-template-columns:repeat(2,minmax(0,1fr))!important}.gw-login #gw-focused-job-details{padding:10px!important}.gw-login .gw-dashboard-footer{grid-template-columns:repeat(2,minmax(0,1fr))!important}}\n.gw-login .gw-job-info-header .gw-field-address{font-size:clamp(20px,4.8vw,27px)!important;line-height:1.35!important;font-weight:800!important;color:#263243!important;white-space:normal!important;overflow-wrap:anywhere!important;margin:10px 0 12px!important;user-select:text;}\n.gw-login .gw-job-info-header .gw-field-contact{display:flex;flex-wrap:wrap;gap:8px;align-items:center;}\n.gw-login .gw-job-info-header .gw-field-contact a,.gw-login .gw-job-info-header .gw-field-contact button{display:inline-flex;align-items:center;justify-content:center;min-height:44px!important;padding:8px 14px!important;width:auto!important;margin:0!important;border-radius:8px!important;font-size:15px!important;font-weight:700!important;text-decoration:none!important;box-sizing:border-box;}\n\n\n.gw-login .gw-job-info-header{background:#fff!important;border:1px solid #dce3eb!important;border-radius:12px!important;padding:14px!important;}\n.gw-login .gw-warm-schedule-address{font-size:17px!important;font-weight:650!important;color:#263243!important;line-height:1.4!important;}\n`;\nconst st=document.createElement('style');st.id='gw-worker-blue-re7';st.textContent=css;document.head.append(st);\n})();\n\n;(() => {\n document.addEventListener('click', async e => {\n  const button=e.target.closest?.('button.gw-copy-address');\n  if(!button || !button.closest('.gw-login,[data-gw-re3-additional]')) return;\n  const address=button.dataset.gwCopyAddress; if(!address) return;\n  let lang='en';try{lang=localStorage.getItem('gwPortalLanguage')||'en';}catch(_){}\n  const original=button.textContent;\n  try{\n   if(!navigator.clipboard?.writeText) throw new Error('Clipboard unavailable');\n   await navigator.clipboard.writeText(address);\n   button.textContent=({zh:'\u5df2\u8907\u88fd',es:'Copiada'})[lang]||'Copied!';\n   setTimeout(()=>{if(button.isConnected)button.textContent=original;},1500);\n  }catch(_){window.prompt(({zh:'\u8acb\u8907\u88fd\u5730\u5740',es:'Copie la direcci\u00f3n'})[lang]||'Copy this address:',address);}\n });\n})();\n;(() => {\n const style=document.createElement('style');style.id='gw-clean-re12';style.textContent=`\n.gw-login{--gw-line:#dce3eb;background:#fff!important;border-radius:10px!important;line-height:1.4!important;}\n.gw-login #gw-weekly-schedule-entry,.gw-login #gw-bulletin-entry,.gw-login button.gw-warm-register,.gw-login button.gw-warm-quote{background:#1769aa!important;color:#fff!important;font-size:14px!important;min-height:44px!important;}\n.gw-login .gw-lang-btn[aria-pressed=false],.gw-login #gw-employee-weekly-schedule button[aria-pressed=false]{background:#f3f6f9!important;color:#1769aa!important;border:1px solid #dce3eb!important;}\n.gw-login .gw-warm-management,.gw-login .gw-warm-measure-summary,.gw-login .gw-warm-empty{background:#f5f7fa!important;}\n.gw-login .gw-warm-empty .gw-warm-date{background:#edf1f5!important;color:#526174!important;}\n.gw-login #gw-focused-job-details{padding:10px!important;border:0!important;margin:6px 0!important;}\n.gw-login :is(#gw-focused-job-details,#gw-re173-action-header) .gw-field-title{font-size:16px!important;margin:0 0 8px!important;}\n.gw-login :is(#gw-focused-job-details,#gw-re173-action-header) .gw-field-back{background:transparent!important;color:#1769aa!important;text-align:left!important;width:auto!important;padding:0!important;margin:0!important;font-size:14px!important;min-height:44px!important;}\n.gw-login :is(#gw-focused-job-details,#gw-re173-action-header) .gw-field-job{padding:10px!important;margin-bottom:12px!important;border-radius:8px!important;}\n.gw-login :is(#gw-focused-job-details,#gw-re173-action-header) .gw-field-code{font-size:20px!important;}\n.gw-login :is(#gw-focused-job-details,#gw-re173-action-header) .gw-field-customer{font-size:15px!important;margin-top:6px!important;}\n.gw-login :is(#gw-focused-job-details,#gw-re173-action-header) .gw-field-address{font-size:17px!important;line-height:1.35!important;margin:4px 0!important;}\n.gw-login :is(#gw-focused-job-details,#gw-re173-action-header) .gw-field-contact{gap:4px 12px!important;align-items:center!important;}\n.gw-login :is(#gw-focused-job-details,#gw-re173-action-header) .gw-field-contact :is(a,button),.gw-login :is(#gw-focused-job-details,#gw-re173-action-header) .gw-field-contact a[href*=\"google.com\/maps\"],.gw-login :is(#gw-focused-job-details,#gw-re173-action-header) .gw-field-contact .gw-copy-address,.gw-login #gw-measurement-dashboard .gw-re12-measure-links button{background:transparent!important;color:#1769aa!important;border:0!important;box-shadow:none!important;border-radius:0!important;text-decoration:underline!important;font-size:14px!important;font-weight:600!important;padding:4px 0!important;min-height:44px!important;width:auto!important;margin:0!important;}\n.gw-login #gw-measurement-dashboard .gw-re12-measure-links{display:flex!important;flex-wrap:wrap!important;gap:4px 16px!important;align-items:center!important;}\n.gw-login :is(#gw-focused-job-details,#gw-re173-action-header) .gw-field-heading{font-size:15px!important;margin:0 0 4px!important;}\n.gw-login :is(#gw-focused-job-details,#gw-re173-action-header) .gw-field-action[data-state=done] small,.gw-login :is(#gw-focused-job-details,#gw-re173-action-header) .gw-field-action[data-state=done] .gw-field-mark{color:#15803d!important;}\n.gw-login :is(#gw-focused-job-details,#gw-re173-action-header) .gw-field-action[data-state=alert] small,.gw-login :is(#gw-focused-job-details,#gw-re173-action-header) .gw-field-action[data-state=alert] .gw-field-mark{color:#b42318!important;}\n.gw-login :is(#gw-focused-job-details,#gw-re173-action-header) .gw-field-actions button.gw-field-action:focus-visible{outline:2px solid #1769aa!important;outline-offset:2px!important;}\n.gw-login #gw-focused-job-details .gw-v5-status select{font-size:14px!important;min-width:0!important;height:44px!important;line-height:normal!important;padding:5px!important;}\n@media(max-width:480px){.gw-login{padding:8px!important}.gw-login #gw-focused-job-details{padding:4px!important}.gw-login :is(#gw-focused-job-details,#gw-re173-action-header) .gw-field-contact{gap:4px 10px!important}.gw-login :is(#gw-focused-job-details,#gw-re173-action-header) .gw-field-action small{max-width:100px}.gw-login #gw-global-navigation{grid-template-columns:minmax(0,2fr) minmax(0,1fr)!important;}}\n`;document.head.append(style);\n})();\n\n;(() => {\nconst style=document.createElement('style');style.id='gw-re14';style.textContent=`\n.gw-login #gw-global-navigation{grid-template-columns:minmax(0,1fr) auto!important;align-items:center;gap:8px!important;margin:4px 0!important;}\n.gw-login #gw-global-navigation #gw-home-heading{margin:0!important;text-align:left!important;font-size:16px!important;}\n.gw-login #gw-global-navigation button{background:transparent!important;color:#1769aa!important;border:0!important;box-shadow:none!important;text-decoration:underline!important;width:auto!important;padding:4px!important;font-size:14px!important;}\n.gw-login #gw-job-action-row{display:grid!important;grid-template-columns:repeat(2,minmax(0,1fr))!important;gap:8px!important;}\n.gw-login #gw-job-action-row>button{width:100%!important;min-height:44px!important;margin:0!important;padding:6px!important;background:#1769aa!important;color:white!important;-webkit-text-fill-color:white!important;font-size:14px!important;font-weight:650!important;white-space:normal!important;}\n.gw-login #gw-job-action-row>button[hidden]{display:none!important;}\n.gw-login #gw-bulletin-entry span{color:#fff!important;-webkit-text-fill-color:#fff!important;}\n.gw-login :is(#gw-focused-job-details,#gw-re173-action-header) .gw-field-actions{display:grid!important;grid-template-columns:repeat(2,minmax(0,1fr))!important;gap:8px!important;}\n.gw-login :is(#gw-focused-job-details,#gw-re173-action-header) .gw-field-action{min-height:72px!important;padding:6px!important;gap:3px!important;}\n.gw-login :is(#gw-focused-job-details,#gw-re173-action-header) .gw-field-action .gw-field-icon{font-size:22px!important;}\n.gw-login :is(#gw-focused-job-details,#gw-re173-action-header) .gw-field-action small{color:inherit!important;max-width:none!important;text-align:center!important;}\n:is(.gw-login,[data-gw-re3-additional]) .gw-job-info-header .gw-field-contact{display:flex!important;flex-wrap:wrap!important;gap:0 12px!important;align-items:center!important;}\n:is(.gw-login,[data-gw-re3-additional]) .gw-job-info-header .gw-field-contact :is(a,button){background:transparent!important;color:#1769aa!important;-webkit-text-fill-color:#1769aa!important;border:0!important;box-shadow:none!important;border-radius:0!important;text-decoration:underline!important;font-size:14px!important;font-weight:600!important;padding:4px 0!important;min-height:44px!important;width:auto!important;margin:0!important;}\n:is(.gw-login,[data-gw-re3-additional]) .gw-job-info-header .gw-field-contact :is(a,button):disabled{opacity:.5!important;}\n.gw-login #gw-measurement-dashboard .gw-re14-measure-header{display:flex;align-items:center;flex-wrap:wrap;gap:4px 12px;}\n.gw-login #gw-measurement-dashboard .gw-re14-measure-header h3{margin:0!important;font-size:16px!important;}\n.gw-login #gw-measurement-dashboard .gw-re12-measure-links{width:auto!important;flex:0 1 auto!important;margin:0!important;gap:4px 12px!important;}\n.gw-login #gw-measurement-dashboard .gw-re12-measure-links button[hidden]{display:none!important;}\n.gw-login #gw-measurement-dashboard details{background:#fff!important;}\n`;document.head.append(style);\n})();\n\n;(() => {\nconst style=document.createElement('style');style.id='gw-re16-text-links';style.textContent=`\n.gw-login .gw-job-info-header .gw-field-contact,\n[data-gw-re3-additional] .gw-job-info-header .gw-field-contact,\n.gw-login #gw-measurement-dashboard .gw-re12-measure-links{display:flex!important;flex-wrap:wrap!important;align-items:center!important;justify-content:flex-start!important;gap:0 12px!important;}\n.gw-login .gw-job-info-header .gw-field-contact > :is(a,button),\n[data-gw-re3-additional] .gw-job-info-header .gw-field-contact > :is(a,button),\n.gw-login :is(#gw-focused-job-details,#gw-re173-action-header) .gw-job-info-header .gw-field-contact > :is(a,button),\n.gw-login #gw-measurement-dashboard .gw-re12-measure-links > button{display:inline-flex!important;align-items:center!important;justify-content:center!important;flex:0 0 auto!important;width:auto!important;min-width:0!important;max-width:none!important;min-height:44px!important;height:auto!important;padding:0!important;margin:0!important;background:transparent!important;background-image:none!important;border:0!important;box-shadow:none!important;border-radius:0!important;color:#1769aa!important;-webkit-text-fill-color:#1769aa!important;text-decoration:underline!important;font-size:14px!important;font-weight:600!important;line-height:1.3!important;white-space:nowrap!important;word-break:normal!important;overflow-wrap:normal!important;}\n.gw-login #gw-measurement-dashboard .gw-re12-measure-links > button[hidden]{display:none!important;}\n.gw-login #gw-measurement-dashboard .gw-re14-measure-header{display:flex!important;align-items:center!important;justify-content:flex-start!important;flex-wrap:wrap!important;gap:0 16px!important;}\n.gw-login #gw-measurement-dashboard .gw-re14-measure-header h3{flex:0 0 auto!important;width:auto!important;}\n.gw-login .gw-job-info-header .gw-field-contact > :is(a,button):focus-visible,.gw-login #gw-measurement-dashboard .gw-re12-measure-links > button:focus-visible{outline:2px solid #1769aa!important;outline-offset:2px!important;}\n`;document.head.append(style);\n})();\n;(() => {const style=document.createElement('style');style.id='gw-re17-id-style';style.textContent=`\n.gw-login #gw-re17-quotations button.gw-re17-q-card{background:#eef5fb!important;background-image:none!important;border:1px solid #b5c9dc!important;color:#163b5a!important;-webkit-text-fill-color:#163b5a!important;width:124px!important;min-height:76px!important;padding:7px 4px!important;box-shadow:none!important;}\n.gw-login #gw-re17-quotations button.gw-re17-q-card span{color:#163b5a!important;-webkit-text-fill-color:#163b5a!important;}\n.gw-login #gw-re17-quotations button.gw-re17-q-card[data-status=Converted]{background:#e0f2e4!important;}\n.gw-login #gw-re17-quotations button.gw-re17-q-card[data-status=N]{background:#e7e6e6!important;}\n.gw-login :is(#gw-monthly-job-ids,#gw-re17-quotations) button.gw-job-code{background:transparent!important;background-image:none!important;color:#0b4f8a!important;-webkit-text-fill-color:#0b4f8a!important;box-shadow:none!important;}\n.gw-login :is(#gw-monthly-job-ids,#gw-re17-quotations) button.gw-job-code *{color:#0b4f8a!important;-webkit-text-fill-color:#0b4f8a!important;}\n.gw-login #gw-re17-quotations .gw-re17-id,.gw-login #gw-employee-weekly-schedule button.gw-re17-id,.gw-job-info-header .gw-field-code>.gw-re17-id{display:inline-block!important;background:#1769aa!important;color:white!important;-webkit-text-fill-color:white!important;border-radius:5px!important;padding:5px 9px!important;font-size:16px!important;font-weight:700!important;white-space:nowrap!important;width:auto!important;}\n.gw-login #gw-measurement-dashboard .gw-re12-measure-links #gw-drawing-toggle{font-weight:700!important;}\n`;document.head.append(style);})();\n\n;(() => {const style=document.createElement('style');style.id='gw-re173';style.textContent=`\n.gw-login:has(#gw-focused-job-details:not([hidden])) #gw-job-action-row,.gw-login:has(#gw-re173-action-header:not([hidden])) #gw-job-action-row,.gw-login:has(#gw-create-job-panel:not([hidden])) #gw-job-action-row{display:none!important;}\n.gw-login button.gw-re173-back{background:#795548!important;color:white!important;-webkit-text-fill-color:white!important;font-weight:700!important;width:100%!important;min-height:44px!important;border-radius:9px!important;}\n.gw-login .gw-re173-job-nav{display:grid!important;grid-template-columns:repeat(2,minmax(0,1fr))!important;gap:8px!important;margin:8px 0 12px!important;}\n.gw-login .gw-re173-additional{margin:8px 0;}.gw-login .gw-re173-additional>button{width:100%!important;min-height:44px!important;}\n.gw-login #gw-measurement-dashboard .gw-re14-measure-header h3{font-size:24px!important;line-height:1.3!important;}\n.gw-login #gw-measurement-dashboard .gw-re173-pdf>button{background:transparent!important;color:#1769aa!important;-webkit-text-fill-color:#1769aa!important;border:0!important;box-shadow:none!important;text-decoration:underline!important;text-align:left!important;font-weight:700!important;width:auto!important;padding:8px!important;}\n.gw-login #gw-measurement-dashboard .gw-re173-measure-drop{border:1px solid #cbd5e1;padding:8px;margin:12px 0;}\n.gw-login #gw-measurement-dashboard .gw-re173-measure-drop>div{padding:8px;}\n`;document.head.append(style);})();\n\n;(() => {const style=document.createElement('style');style.id='gw-re174';style.textContent=`\n.gw-re174-job-top{display:flex!important;align-items:center!important;justify-content:space-between!important;gap:8px!important;flex-wrap:wrap!important;margin:4px 0 12px!important;}\n.gw-re174-job-top .gw-re174-job-id{display:inline-block!important;background:#1769aa!important;color:#fff!important;-webkit-text-fill-color:#fff!important;border-radius:5px!important;padding:5px 9px!important;font-size:16px!important;font-weight:700!important;white-space:nowrap!important;}\n.gw-login :is(#gw-focused-job-details,#gw-re173-action-header) .gw-re174-job-top button.gw-re173-back,.gw-re174-job-top button.gw-re173-back{background:#795548!important;background-image:none!important;color:#fff!important;-webkit-text-fill-color:#fff!important;border:0!important;border-radius:9px!important;min-height:44px!important;width:auto!important;flex:0 1 auto!important;padding:8px 12px!important;margin:0!important;font-weight:700!important;text-align:center!important;}\n.gw-login:has(#gw-re173-action-header:not([hidden])) .gw-re174-old-nav{display:none!important;}\n.gw-re174-additional-drop{border:1px solid #cbd5e1;border-radius:9px;padding:12px;margin:12px 0;}\n.gw-re174-additional-drop>summary{color:#1769aa;font-weight:700;cursor:pointer;}\n.gw-login #gw-measurement-dashboard .gw-re174-additional-drop button.gw-field-action{background:#e8e0ec!important;color:#5c476a!important;-webkit-text-fill-color:#5c476a!important;display:flex!important;flex-direction:column;align-items:center;gap:4px;width:100%!important;}\n.gw-login #gw-measurement-dashboard .gw-re174-additional-drop button.gw-field-action small{color:inherit!important;}\n`;document.head.append(style);})();\n\n<\/script>\n\n<div class=\"gw-login\">\n  <div id=\"gw-language-switcher\">\n    <button type=\"button\" class=\"gw-lang-btn\" data-lang=\"en\">English<\/button>\n    <button type=\"button\" class=\"gw-lang-btn\" data-lang=\"zh\">\u7e41\u9ad4\u4e2d\u6587<\/button>\n    <button type=\"button\" class=\"gw-lang-btn\" data-lang=\"es\">Espa\u00f1ol<\/button>\n  <\/div>\n  <h2>Employee Login<\/h2>\n\n  <form id=\"gw-login-form\" onsubmit=\"return false;\">\n    <label for=\"gw-email\">Email<\/label>\n    <input id=\"gw-email\" type=\"email\" autocomplete=\"username\" required=\"\">\n\n    <label for=\"gw-password\">Password<\/label>\n    <input id=\"gw-password\" type=\"password\" autocomplete=\"current-password\" required=\"\">\n\n    <label class=\"gw-remember\">\n      <input id=\"gw-remember\" type=\"checkbox\" checked=\"\">\n      Remember Me on this device\n    <\/label>\n\n    <button type=\"submit\">Log In<\/button>\n    <p id=\"gw-login-message\" role=\"status\"><\/p>\n  <\/form>\n\n  <div id=\"gw-set-password\" hidden=\"\">\n    <h3>Set Your Password<\/h3>\n\n    <label for=\"gw-new-password\">New Password<\/label>\n    <input id=\"gw-new-password\" type=\"password\" autocomplete=\"new-password\" minlength=\"12\">\n\n    <label for=\"gw-confirm-password\">Confirm Password<\/label>\n    <input id=\"gw-confirm-password\" type=\"password\" autocomplete=\"new-password\" minlength=\"12\">\n\n    <button id=\"gw-save-password\" type=\"button\">\n      Set Password\n    <\/button>\n\n    <p id=\"gw-password-message\" role=\"status\"><\/p>\n  <\/div>\n\n  <div id=\"gw-job-search\" hidden=\"\">\n    <h2 id=\"gw-home-heading\">Employee Portal<\/h2>\n\n    <label for=\"gw-job-id\">Job ID<\/label>\n    <div id=\"gw-search-row\" class=\"gw-search-row\">\n      <input id=\"gw-job-id\" type=\"text\" placeholder=\"GW-2611-013\" autocomplete=\"off\" autocapitalize=\"characters\" spellcheck=\"false\">\n      <button id=\"gw-find-job\" type=\"button\">Load Job<\/button>\n    <\/div>\n\n    <p id=\"gw-job-result\" role=\"status\"><\/p>\n\n    <div id=\"gw-job-dashboard\" hidden=\"\">\n      <h2>Job Dashboard<\/h2>\n\n      <button id=\"gw-final-measurement\" type=\"button\">\n        Final Measurement\n      <\/button>\n\n      <button id=\"gw-site-preparation\" type=\"button\">\n        Site Preparation\n      <\/button>\n\n      <button id=\"gw-job-photos\" type=\"button\">\n        Job Photos\n      <\/button>\n\n      <!-- JOB PHOTOS -->\n      <div id=\"gw-photo-form\" hidden=\"\">\n        <div class=\"gw-photo-heading-row\">\n          <h3 id=\"gw-category-heading\">Job Photos<\/h3>\n          <button id=\"gw-gallery-add\" type=\"button\" hidden=\"\">Add Photo<\/button>\n        <\/div>\n        <div id=\"gw-gallery-first\"><\/div>\n        <div id=\"gw-photo-editor\">\n\n        <label for=\"gw-photo-type\">Photo Type<\/label>\n        <select id=\"gw-photo-type\">\n          <option value=\"Before\">Before Installation<\/option>\n          <option value=\"After\">After Installation<\/option>\n          <option value=\"Measurement\">Measurement Photos<\/option>\n          <option value=\"Problem\">Problem \/ Damage<\/option>\n        <\/select>\n\n        <label for=\"gw-photo-file\">Choose Photo<\/label>\n        <div id=\"gw-photo-source-actions\" class=\"gw-photo-source-actions\" hidden=\"\">\n          <button id=\"gw-take-photo\" type=\"button\">Take Photo<\/button>\n          <button id=\"gw-photo-library\" type=\"button\">Photo Library<\/button>\n        <\/div>\n        <input id=\"gw-camera-file\" type=\"file\" accept=\"image\/*\" capture=\"environment\" hidden=\"\">\n\n        <!-- iPhone Photo Library \/ Camera Supported -->\n        <input id=\"gw-photo-file\" type=\"file\" accept=\"image\/jpeg,image\/png,image\/webp,image\/heic\" multiple=\"\">\n\n        <label for=\"gw-photo-description\">Description (Optional)<\/label>\n        <textarea id=\"gw-photo-description\" rows=\"3\"><\/textarea>\n\n        <div id=\"gw-photo-submit-actions\" class=\"gw-photo-submit-actions\">\n        <button id=\"gw-upload-photo\" type=\"button\">\n          Upload Photo\n        <\/button>\n\n        <button id=\"gw-gallery-cancel\" type=\"button\" hidden=\"\">Cancel<\/button>\n        <\/div>\n        <p id=\"gw-photo-message\" role=\"status\"><\/p>\n        <\/div>\n        <h4 id=\"gw-gallery-heading\">Job Photo Gallery<\/h4>\n\n        <button id=\"gw-view-photos\" type=\"button\">\n          View Job Photos\n        <\/button>\n\n        <div id=\"gw-photo-gallery\"><\/div>\n      <\/div>\n\n      <!-- SITE PREPARATION -->\n      <div id=\"gw-preparation-form\" hidden=\"\">\n        <h3>Site Preparation<\/h3>\n\n        <label for=\"gw-water-condition\">Water Shutoff Condition<\/label>\n        <input id=\"gw-water-condition\" type=\"text\" placeholder=\"Good \/ Leaking \/ Not accessible\">\n\n        <label class=\"gw-remember\">\n          <input id=\"gw-water-replace\" type=\"checkbox\">\n          Water Shutoff Replacement Required\n        <\/label>\n\n        <label for=\"gw-faucet-condition\">Faucet Condition<\/label>\n        <input id=\"gw-faucet-condition\" type=\"text\" placeholder=\"Good \/ Damaged \/ Replacement needed\">\n\n        <label class=\"gw-remember\">\n          <input id=\"gw-plumbing-modification\" type=\"checkbox\">\n          Plumbing Modification Required\n        <\/label>\n\n        <label for=\"gw-plumbing-notes\">Plumbing Notes<\/label>\n        <textarea id=\"gw-plumbing-notes\" rows=\"3\"><\/textarea>\n\n        <h4>Electrical<\/h4>\n\n        <label class=\"gw-remember\">\n          <input id=\"gw-electrical-modification\" type=\"checkbox\">\n          Electrical Modification Required\n        <\/label>\n\n        <label class=\"gw-remember\">\n          <input id=\"gw-outlet-issue\" type=\"checkbox\">\n          Outlet Issue\n        <\/label>\n\n        <label for=\"gw-electrical-notes\">Electrical Notes<\/label>\n        <textarea id=\"gw-electrical-notes\" rows=\"3\"><\/textarea>\n\n        <h4>Bathroom Mirror<\/h4>\n\n        <label for=\"gw-mirror-removal\">Mirror Removal<\/label>\n        <select id=\"gw-mirror-removal\">\n          <option value=\"\">Select an option<\/option>\n          <option value=\"Not Required\">Not Required<\/option>\n          <option value=\"Required\">Required<\/option>\n          <option value=\"To Be Confirmed\">To Be Confirmed<\/option>\n        <\/select>\n\n        <h4>Wall<\/h4>\n\n        <label for=\"gw-wall-condition\">Wall Condition<\/label>\n        <input id=\"gw-wall-condition\" type=\"text\" placeholder=\"Good \/ Damaged \/ Uneven\">\n\n        <label class=\"gw-remember\">\n          <input id=\"gw-wall-work-required\" type=\"checkbox\">\n          Wall Work Required\n        <\/label>\n\n        <h4>Floor Protection<\/h4>\n\n        <label for=\"gw-floor-type\">Floor Type<\/label>\n        <input id=\"gw-floor-type\" type=\"text\" placeholder=\"Wood \/ Tile \/ Carpet\">\n\n        <label class=\"gw-remember\">\n          <input id=\"gw-floor-protection-required\" type=\"checkbox\">\n          Floor Protection Required\n        <\/label>\n\n        <label for=\"gw-floor-protection-type\">Protection Type<\/label>\n        <input id=\"gw-floor-protection-type\" type=\"text\" placeholder=\"Ram Board \/ Plywood \/ Other\">\n\n        <label for=\"gw-protection-notes\">Protection Notes<\/label>\n        <textarea id=\"gw-protection-notes\" rows=\"3\"><\/textarea>\n\n        <h4>Site Access<\/h4>\n\n        <label for=\"gw-access-condition\">Access Condition<\/label>\n        <input id=\"gw-access-condition\" type=\"text\" placeholder=\"Clear \/ Narrow \/ Difficult\">\n\n        <label class=\"gw-remember\">\n          <input id=\"gw-stairs-required\" type=\"checkbox\">\n          Stairs Required\n        <\/label>\n\n        <label for=\"gw-special-access-notes\">Special Access Notes<\/label>\n        <textarea id=\"gw-special-access-notes\" rows=\"3\"><\/textarea>\n\n        <h4>Special Tools &amp; Parts<\/h4>\n\n        <label class=\"gw-remember\">\n          <input id=\"gw-special-tools-required\" type=\"checkbox\">\n          Special Tools Required\n        <\/label>\n\n        <label for=\"gw-special-tools-list\">Special Tools List<\/label>\n        <textarea id=\"gw-special-tools-list\" rows=\"3\"><\/textarea>\n\n        <label class=\"gw-remember\">\n          <input id=\"gw-special-parts-required\" type=\"checkbox\">\n          Special Parts Required\n        <\/label>\n\n        <label for=\"gw-special-parts-list\">Special Parts List<\/label>\n        <textarea id=\"gw-special-parts-list\" rows=\"3\"><\/textarea>\n\n        <h4>Preparation &amp; Installer Review<\/h4>\n\n        <label for=\"gw-installer-notes\">Installer Notes<\/label>\n        <textarea id=\"gw-installer-notes\" rows=\"3\"><\/textarea>\n\n        <label for=\"gw-prepared-by\">Prepared By<\/label>\n        <input id=\"gw-prepared-by\" type=\"text\">\n\n        <label class=\"gw-remember\">\n          <input id=\"gw-preparation-complete\" type=\"checkbox\">\n          Preparation Complete\n        <\/label>\n\n        <label class=\"gw-remember\">\n          <input id=\"gw-installer-reviewed\" type=\"checkbox\">\n          Installer Reviewed\n        <\/label>\n\n        <label for=\"gw-installer-reviewed-by\">Reviewed By<\/label>\n        <input id=\"gw-installer-reviewed-by\" type=\"text\">\n\n        <label class=\"gw-remember\">\n          <input id=\"gw-ready-for-install\" type=\"checkbox\">\n          Ready for Installation\n        <\/label>\n\n        <button id=\"gw-save-preparation\" type=\"button\">\n          Save Site Preparation\n        <\/button>\n\n        <p id=\"gw-preparation-message\" role=\"status\"><\/p>\n      <\/div>\n\n      <!-- INSTALLER REVIEW -->\n      <button id=\"gw-installer-review-button\" type=\"button\">\n        Installer Review\n      <\/button>\n\n      <div id=\"gw-installer-review-form\" hidden=\"\">\n        <h3>Installer Review<\/h3>\n\n        <label for=\"gw-review-notes\">Installer Notes<\/label>\n        <textarea id=\"gw-review-notes\" rows=\"3\"><\/textarea>\n\n        <label>\n          <input id=\"gw-review-confirmed\" type=\"checkbox\">\n          Installer Reviewed\n        <\/label>\n\n        <label>\n          <input id=\"gw-review-ready\" type=\"checkbox\">\n          Ready for Installation\n        <\/label>\n\n        <button id=\"gw-save-review\" type=\"button\">\n          Save Installer Review\n        <\/button>\n\n        <p id=\"gw-review-message\" role=\"status\"><\/p>\n      <\/div>\n\n      <!-- FINAL MEASUREMENT -->\n      <div id=\"gw-measurement-form\" hidden=\"\">\n        <h3>Final Measurement<\/h3>\n\n        <label for=\"gw-measured-by\">Measured By<\/label>\n        <input id=\"gw-measured-by\" type=\"text\">\n\n        <label for=\"gw-measurement-date\">Measurement Date<\/label>\n        <input id=\"gw-measurement-date\" type=\"date\">\n\n        <label for=\"gw-project-area\">Project Area<\/label>\n        <input id=\"gw-project-area\" type=\"text\" placeholder=\"Kitchen, Bathroom...\">\n\n        <label for=\"gw-materials\">Material<\/label>\n        <input id=\"gw-materials\" type=\"text\" placeholder=\"Quartz, Granite, Quartzite...\">\n\n        <label for=\"gw-edge\">Edge<\/label>\n        <select id=\"gw-edge\">\n          <option value=\"\">Select Edge<\/option>\n          <option value=\"Eased\">Eased<\/option>\n          <option value=\"Bevel\">Bevel<\/option>\n          <option value=\"Bullnose\">Bullnose<\/option>\n          <option value=\"Mitered\">Mitered<\/option>\n          <option value=\"Other\">Other<\/option>\n        <\/select>\n\n        <label for=\"gw-sink-type\">Sink Type<\/label>\n        <select id=\"gw-sink-type\">\n          <option value=\"\">Select Sink<\/option>\n          <option value=\"Undermount\">Undermount<\/option>\n          <option value=\"Drop-in\">Drop-in<\/option>\n          <option value=\"Farmhouse\">Farmhouse<\/option>\n          <option value=\"None\">None<\/option>\n        <\/select>\n\n        <label for=\"gw-sink-model\">Sink Model<\/label>\n        <input id=\"gw-sink-model\" type=\"text\" placeholder=\"Brand \/ Model Number\">\n\n        <label for=\"gw-stove-type\">Stove Size \/ Model<\/label>\n        <input id=\"gw-stove-type\" type=\"text\" placeholder=\"e.g. 30 inches \/ GE Model JGS760\">\n\n        <label for=\"gw-faucet\">Faucet<\/label>\n        <input id=\"gw-faucet\" type=\"text\" placeholder=\"Brand \/ Model \/ Hole Location\">\n\n        <label for=\"gw-backsplash\">Backsplash<\/label>\n        <input id=\"gw-backsplash\" type=\"text\" placeholder=\"4 inch, Full Height, None...\">\n\n        <label class=\"gw-remember\">\n          <input id=\"gw-seam-required\" type=\"checkbox\">\n          Seam Required\n        <\/label>\n\n        <label for=\"gw-field-notes\">Field Notes<\/label>\n        <textarea id=\"gw-field-notes\" rows=\"4\"><\/textarea>\n\n        <button id=\"gw-save-measurement\" type=\"button\">\n          Save Measurement\n        <\/button>\n\n        <p id=\"gw-measurement-message\" role=\"status\"><\/p>\n      <\/div>\n\n    <\/div>\n  <\/div>\n<\/div>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n","protected":false},"excerpt":{"rendered":"<p>English \u7e41\u9ad4\u4e2d\u6587 Espa\u00f1ol Employee Login Email Password Remember Me on this device Log In Set Your Password New Password Confirm [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":0,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"","meta":{"site-sidebar-layout":"default","site-content-layout":"","ast-site-content-layout":"default","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","ast-disable-related-posts":"","theme-transparent-header-meta":"","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"default","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"footnotes":""},"class_list":["post-85","page","type-page","status-publish","hentry"],"_links":{"self":[{"href":"https:\/\/gwkitchen.com\/wp2026\/index.php?rest_route=\/wp\/v2\/pages\/85","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/gwkitchen.com\/wp2026\/index.php?rest_route=\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/gwkitchen.com\/wp2026\/index.php?rest_route=\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/gwkitchen.com\/wp2026\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/gwkitchen.com\/wp2026\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=85"}],"version-history":[{"count":231,"href":"https:\/\/gwkitchen.com\/wp2026\/index.php?rest_route=\/wp\/v2\/pages\/85\/revisions"}],"predecessor-version":[{"id":526,"href":"https:\/\/gwkitchen.com\/wp2026\/index.php?rest_route=\/wp\/v2\/pages\/85\/revisions\/526"}],"wp:attachment":[{"href":"https:\/\/gwkitchen.com\/wp2026\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=85"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}