(() => {
const $ = (s, r = document) => r.querySelector(s);
const $$ = (s, r = document) => [...r.querySelectorAll(s)];
const h = (value) => String(value ?? "").replace(/[&<>"']/g, (c) => ({"&":"&","<":"<",">":">",'"':""","'":"'"}[c]));
const cash = (cents) => new Intl.NumberFormat("en-US", {style:"currency", currency:"USD"}).format((cents || 0) / 100);
const toast = (message) => { const box = $("#toast"); if (!box) return; box.textContent = message; box.classList.add("show"); clearTimeout(window.__ahsToast); window.__ahsToast = setTimeout(() => box.classList.remove("show"), 3000); };
async function api(path, options = {}) {
const init = {...options, headers:{"Content-Type":"application/json", ...(options.headers || {})}};
if (init.body && typeof init.body !== "string") init.body = JSON.stringify(init.body);
const response = await fetch(path, init); let data = {};
try { data = await response.json(); } catch (_) {}
if (!response.ok) { const e = new Error(data?.error?.message || data?.message || `Request failed (${response.status})`); e.status = response.status; e.data = data; throw e; }
return data;
}
const needLogin = (next = location.pathname + location.search) => { localStorage.setItem("amazon-home-services-return", next); location.href = `/login?next=${encodeURIComponent(next)}`; };
async function createProject(service, appointment = "") {
try {
const result = await api("/api/projects", {method:"POST", body:{service}});
if (appointment) localStorage.setItem(`amazon-home-services-appointment-${result.project_id}`, appointment);
location.href = `/projects/${result.project_id}`;
} catch (error) { if (error.status === 401) { localStorage.setItem("amazon-home-services-pending-service", service); if (appointment) localStorage.setItem("amazon-home-services-pending-appointment", appointment); needLogin(); } else toast(error.message); }
}
$$('[data-start-project]').forEach((button) => button.addEventListener("click", () => createProject(button.dataset.service || "tv-wall-mounting")));
$$('[data-quick-start]').forEach((form) => form.addEventListener("submit", (event) => { event.preventDefault(); const values = Object.fromEntries(new FormData(form)); createProject(values.service || form.dataset.service, values.appointment); }));
$$('[data-favorite]').forEach((button) => button.addEventListener("click", async (event) => {
event.preventDefault();
try { const result = await api(`/api/favorites/${encodeURIComponent(button.dataset.favorite)}`, {method:"POST"}); button.classList.toggle("saved", result.favorited); button.textContent = result.favorited ? "♥ Saved" : "♡ Save provider"; toast(result.favorited ? "Provider saved" : "Provider removed"); }
catch (error) { if (error.status === 401) needLogin(); else toast(error.message); }
}));
const auth = $('[data-auth]');
if (auth) {
const mode = auth.dataset.auth, errorBox = $('.form-error', auth);
const mailPurpose = mode === "verify" ? "registration" : mode === "reset" ? "password-reset" : null;
if (mailPurpose) api(`/api/auth/mail?purpose=${mailPurpose}`).then((mail) => { $('#local-mail').textContent = `Verification email status: ${mail.delivery_status}`; }).catch((error) => $('#local-mail').textContent = error.message);
auth.addEventListener("submit", async (event) => {
event.preventDefault(); errorBox.textContent = ""; const values = Object.fromEntries(new FormData(auth));
try {
if (mode === "register") { await api("/api/auth/signup", {method:"POST", body:values}); location.href = "/verify"; return; }
if (mode === "verify") await api("/api/auth/verify", {method:"POST", body:values});
if (mode === "login") await api("/api/auth/login", {method:"POST", body:values});
if (mode === "forgot") { await api("/api/auth/forgot", {method:"POST", body:values}); location.href = "/reset-password"; return; }
if (mode === "reset") { await api("/api/auth/reset", {method:"POST", body:values}); toast("Password updated locally"); setTimeout(() => location.href = "/account", 500); return; }
const service = localStorage.getItem("amazon-home-services-pending-service"); const appointment = localStorage.getItem("amazon-home-services-pending-appointment") || "";
localStorage.removeItem("amazon-home-services-pending-service"); localStorage.removeItem("amazon-home-services-pending-appointment");
if (service) return createProject(service, appointment);
const next = new URLSearchParams(location.search).get("next") || localStorage.getItem("amazon-home-services-return") || "/account"; localStorage.removeItem("amazon-home-services-return"); location.href = next;
} catch (error) { errorBox.textContent = error.message; }
});
}
$('[data-logout]')?.addEventListener("click", async () => { await api("/api/auth/logout", {method:"POST"}); location.href = "/"; });
const estimate = $('[data-estimate]');
if (estimate) estimate.addEventListener("submit", async (event) => {
event.preventDefault(); const values = Object.fromEntries(new FormData(estimate)); values.service = estimate.dataset.service;
try { const result = await api("/api/estimates", {method:"POST", body:values}); $('[data-estimate-result]').innerHTML = `
Saved local estimate ${cash(result.low_cents)}–${cash(result.high_cents)} ${h(result.unit)} Start this project
`; $('[data-start-estimate]').onclick = () => createProject(values.service); }
catch (error) { if (error.status === 401) needLogin(location.pathname + "#estimate"); else toast(error.message); }
});
async function loadAccount() {
const profile = $('[data-profile]'); const projects = $('[data-project-list]'); if (!profile && !projects) return;
try {
const me = await api("/api/me"); const p = me.profile;
if (profile) {
profile.innerHTML = `Full name Email Phone Street address City State ZIP code View modeHomeowner Provider demo Save profile `;
profile.elements.role.value = p.role; profile.addEventListener("submit", async (event) => { event.preventDefault(); try { await api("/api/profile", {method:"POST", body:Object.fromEntries(new FormData(profile))}); toast("Profile and service address saved"); } catch (error) { toast(error.message); } });
}
if (projects) {
const data = await api("/api/projects"); projects.innerHTML = data.projects.length ? `` : `No appointments yet Start with a service, package and preferred in-home date.
Book TV wall mounting `;
$('[data-empty-start]', projects)?.addEventListener("click", () => createProject("tv-wall-mounting"));
}
} catch (error) { if (error.status === 401) needLogin(); else toast(error.message); }
}
loadAccount();
async function loadSaved() {
const target = $('[data-saved]'); if (!target) return;
try { const {favorites} = await api("/api/favorites"); target.innerHTML = favorites.length ? favorites.map((p) => `${h(p.name.split(" ").slice(0,2).map(x=>x[0]).join(""))} ★ ${h(p.rating)} · ${h(p.review_count)} reviews
${h(p.bio)}
`).join("") : `No saved providers Use the heart on a profile or search result.
Find pros `; $$('[data-remove]', target).forEach((b) => b.onclick = async () => { await api(`/api/favorites/${b.dataset.remove}`, {method:"POST"}); loadSaved(); }); }
catch (error) { target.textContent = error.message; }
}
loadSaved();
async function loadSettings() {
const form = $('[data-settings]'); if (!form) return;
try { const data = await api('/api/settings'); const s=data.settings; ['analytics','personalized','email_updates','sms_updates','reminders'].forEach(k=>form.elements[k].checked=!!s[k]); $('[data-session-list]').innerHTML=data.sessions.map(x=>`${h(x.label)} ${h(x.last_seen)} · ${x.current?'Current session':'Local session'} `).join(''); form.onsubmit=async event=>{event.preventDefault(); const body={}; ['analytics','personalized','email_updates','sms_updates','reminders'].forEach(k=>body[k]=form.elements[k].checked); await api('/api/settings',{method:'POST',body}); toast('Privacy and notification preferences saved');}; $('[data-revoke-sessions]').onclick=async()=>{const r=await api('/api/sessions/revoke',{method:'POST'}); toast(r.message);}; } catch(error) { $('.form-error',form).textContent=error.message; }
}
loadSettings();
const waitlist=$('[data-waitlist]');
if(waitlist) waitlist.onsubmit=async event=>{event.preventDefault(); const box=$('.form-error',waitlist); box.textContent=''; try{const r=await api('/api/waitlist',{method:'POST',body:Object.fromEntries(new FormData(waitlist))}); $('[data-waitlist-result]').innerHTML=`Local waitlist saved ${h(r.waitlist_id)} No external notification is created.
`;}catch(error){box.textContent=error.message;}};
const projectRoot = $('[data-project]');
if (projectRoot) {
const projectId = projectRoot.dataset.projectId; let state = null; let activeStep = 1; let quoteSort = "price";
const scopeDefaults = {issue:"mount-tv", tv_size:"medium", package:"concealed-cable", wall_type:"drywall", attendees:"2", equipment:"TV is unpacked and the original stand is available.", description:"Mount one 55-inch TV in the living room, center it above the media console, and conceal the cable with a paintable local-demo cover."};
const renderProgress = () => { const labels = ["Package & equipment", "Service address", "In-home date", "Technician options", "Review & payment", "Track & manage"]; $('[data-project-progress]').innerHTML = labels.map((label, index) => `${index+1} ${label} `).join(""); };
async function load() { state = (await api(`/api/projects/${projectId}`)).project; activeStep = state.status === "draft" ? Math.min(state.current_step || 1, 4) : state.status === "matched" ? 4 : state.status === "awaiting_deposit" ? 5 : 6; return state; }
const value = (group, key, fallback = "") => state[group]?.[key] ?? fallback;
const errors = (error) => error.data?.problems?.map((p) => `${p.field}: ${p.message}`).join(" · ") || error.message;
function draft() {
if (activeStep === 1) projectRoot.innerHTML = ``;
if (activeStep === 2) projectRoot.innerHTML = `Step 2 of 4
Where is the work needed? Providers are matched with a deterministic local ZIP/radius check.
Street address City State ZIP code Parking/accessStreet access Doorman building Driveway
✓ 8 synthetic providers serve ZIP 11201 · No travel fee for the selected demo area
Back Save & continue
`;
if (activeStep === 3) { const appointment = localStorage.getItem(`amazon-home-services-appointment-${projectId}`) || ""; projectRoot.innerHTML = `Step 3 of 4
Choose an in-home date and time In-home date Arrival windowMorning · 8 AM–12 PM Afternoon · 12–4 PM Evening · 4–7 PM Timing flexibilityExact date preferred Within one week I'm flexible AccessCustomer will be home Doorman/access instructions saved
Back Save & continue
`; }
if (activeStep === 4) projectRoot.innerHTML = `Step 4 of 4
Review package, address and in-home date Package & equipment Edit ${h(JSON.stringify(state.scope,null,2))} Service address Edit ${h(JSON.stringify(state.location,null,2))} In-home date Edit ${h(JSON.stringify(state.schedule,null,2))} Local-only appointment request Submitting prepares synthetic technician options in this database. It does not contact Amazon or a real professional.
Back See technician options
`;
renderProgress(); bindDraft();
}
function bindDraft() {
const form = $('[data-step]', projectRoot);
if (form) {
const step = form.dataset.step; const data = state[step] || {};
Object.entries(data).forEach(([key, val]) => { const el = form.elements[key]; if (!el) return; if (el.type === "checkbox") el.checked = !!val; else el.value = val; });
$('[data-back]', form)?.addEventListener("click", () => { activeStep--; draft(); });
form.addEventListener("submit", async (event) => { event.preventDefault(); const values = Object.fromEntries(new FormData(form)); $$('input[type=checkbox]', form).forEach((el) => values[el.name] = el.checked); try { const nextStep = {scope:2,location:3,schedule:4}[step]; await api(`/api/projects/${projectId}/steps/${step}`, {method:"PUT", body:values}); await load(); activeStep = nextStep; draft(); toast("Project step saved"); } catch (error) { $('.form-error', form).textContent = errors(error); } });
}
$$('[data-edit]', projectRoot).forEach((button) => button.onclick = () => { activeStep = Number(button.dataset.edit); draft(); });
$('[data-back]', projectRoot)?.addEventListener("click", () => { activeStep = Math.max(1, activeStep - 1); draft(); });
$('[data-match]', projectRoot)?.addEventListener("click", async () => { try { const result = await api(`/api/projects/${projectId}/match`, {method:"POST"}); await load(); if (!result.matched) noMatch(); else matched(); toast(result.matched ? `${result.matched} local quotes prepared` : "No availability for those choices"); } catch (error) { $('.form-error', projectRoot).textContent = errors(error); } });
}
function noMatch() { projectRoot.innerHTML = `⌕ No providers are available for this combination Your scope, address and time are still saved. Change the date or widen the location to try again.
`; $('[data-retry-date]').onclick = async () => { await api(`/api/projects/${projectId}/steps/schedule`, {method:"PUT", body:{date:"2026-08-20", time_window:"morning", flexibility:"week", urgency:"standard"}}).catch(()=>{}); location.reload(); }; renderProgress(); }
function matched() {
const quotes = [...state.quotes].sort((a,b) => quoteSort === "rating" ? b.rating-a.rating : quoteSort === "fastest" ? a.eta_days-b.eta_days : a.amount_cents-b.amount_cents);
projectRoot.innerHTML = `${h(state.confirmation_code)} · Local matches ready
Compare ${quotes.length} quotes Prices, timing and notes are synthetic.
Sort quotesLowest price Highest rating Fastest completion ${quotes.map((q,index) => `
${index===0?'Best value ':''}★ ${h(q.rating)}
${cash(q.amount_cents)} ${cash(q.deposit_cents)} local deposit
Available ${h(q.available_at)}
Duration ${q.eta_days} day${q.eta_days===1?'':'s'} ${h(q.note)}
Choose this pro Message provider `).join("")}
Provider messages ${state.messages.length ? state.messages.map(m=>`
${m.sender==='homeowner'?'You':h(m.provider_name)} ${h(m.body)}
`).join('') : '
No messages yet. Ask a matched provider about their quote.
'}
× Message Stored locally; no real business receives it.
Message Send local message `;
$('[data-quote-sort]').value = quoteSort; $('[data-quote-sort]').onchange = (event) => { quoteSort = event.target.value; matched(); };
$$('[data-hire]', projectRoot).forEach((button) => button.onclick = async () => { await api(`/api/projects/${projectId}/hire`, {method:"POST", body:{quote_id:button.dataset.hire}}); await load(); payment(); });
$$('[data-message-open]', projectRoot).forEach((button) => button.onclick = () => { const dialog = $('[data-message-dialog]'); dialog.querySelector('[name=provider_id]').value = button.dataset.messageOpen; $('[data-provider-label]').textContent = button.dataset.providerName; dialog.showModal(); });
$('[data-message-form]')?.addEventListener("submit", async (event) => { event.preventDefault(); const values = Object.fromEntries(new FormData(event.currentTarget)); await api(`/api/projects/${projectId}/messages`, {method:"POST", body:values}); $('[data-message-dialog]').close(); await load(); matched(); toast("Local message added"); }); renderProgress();
}
function payment() {
const selected = state.quotes.find(q => q.quote_id === state.selected_quote_id);
projectRoot.innerHTML = `Local booking deposit
Confirm ${h(selected?.provider_name || "selected provider")} Appointment ${h(state.appointment_at)}
Project quote ${cash((state.deposit_cents||0)+(state.final_cents||0))}
Deposit due now ${cash(state.deposit_cents)}
Remaining after completion ${cash(state.final_cents)}
Generated local-sandbox payment No card number is accepted and no external processor is called.
Choose a test outcome ScenarioSimulated approval Simulated decline Simulated retry I understand this creates no real charge
Pay ${cash(state.deposit_cents)} locally `;
$('[data-payment]').onsubmit = async (event) => { event.preventDefault(); const form = event.currentTarget; const values = Object.fromEntries(new FormData(form)); try { await api(`/api/projects/${projectId}/payment`, {method:"POST", body:{kind:"deposit",scenario:values.scenario}}); await load(); manage(); toast("Local deposit approved"); } catch (error) { $('.form-error', form).textContent = `${error.message} Choose approval to recover; no booking state was lost.`; } }; renderProgress();
}
function timeline() { return `${state.events.map(e => `
${h(e.kind.replaceAll('-',' '))} ${h(e.label)}
`).join('')}
`; }
function manage() {
const active = ["booked","rescheduled"].includes(state.status); const cancelled = state.status === "cancelled_refunded"; const completed = ["work_completed","paid_complete","reviewed"].includes(state.status);
const technician = state.technician || {name:"Assignment pending",team:"Local service team",vehicle:"—",eta:"—"};
projectRoot.innerHTML = `${h(state.status.replaceAll('_',' '))}
${cancelled?'Appointment cancelled':completed?'Service completion':'Appointment confirmed'} ${h(state.confirmation_code)} ${cancelled?`Synthetic refund eligibility: ${cash(state.refund_cents)}`:`In-home appointment: ${h(state.appointment_at)}`}
Technician & arrival tracking
${h(technician.name)} · ${h(technician.team)} Vehicle: ${h(technician.vehicle)} · ${active?`Estimated arrival ${h(technician.eta)}`:'Tracking history retained locally'}
Assigned Preparing ${active?'Arrival window active':'Service updated'}
Status timeline ${timeline()}Manage this appointment ${active?`New in-home appointmentAug 18 · 9 AM Aug 19 · 1 PM Aug 20 · 10 AM Reschedule Enable local reminder Share appointment locally Mark installation complete Cancel & view refund `:''}Contact provider / local support ${completed ? finalAndReview() : ''}
×
`;
$('[data-reschedule]')?.addEventListener("submit", async (event) => { event.preventDefault(); await api(`/api/projects/${projectId}/reschedule`, {method:"POST", body:Object.fromEntries(new FormData(event.currentTarget))}); await load(); manage(); toast("Appointment rescheduled"); });
$('[data-complete]')?.addEventListener("click", async () => { await api(`/api/projects/${projectId}/complete`, {method:"POST"}); await load(); manage(); toast("Completion approved locally"); });
$('[data-reminder]')?.addEventListener("click", async () => { await api(`/api/projects/${projectId}/reminder`, {method:"POST"}); await load(); manage(); toast("Local appointment reminder enabled"); });
$('[data-share]')?.addEventListener("click", () => openDialog(`Share this appointment locally No email is sent and no Amazon account is modified.
Recipient PermissionView only Manage locally Create local access `, () => { $('[data-share-form]').onsubmit = async (event) => { event.preventDefault(); const form=event.currentTarget; const result=await api(`/api/projects/${projectId}/share`,{method:"POST",body:Object.fromEntries(new FormData(form))}); toast(`Local ${result.permission} access saved`); $('[data-action-dialog]').close(); await load(); manage(); }; }));
$('[data-cancel]')?.addEventListener("click", () => openDialog(`Cancel this local booking Eligible deposit: ${cash(state.deposit_cents)}. A synthetic refund confirmation will be created.
ReasonSchedule changed Project scope changed Other Confirm cancellation `, () => { $('[data-cancel-form]').onsubmit = async (event) => { event.preventDefault(); const result = await api(`/api/projects/${projectId}/cancel`, {method:"POST", body:Object.fromEntries(new FormData(event.currentTarget))}); toast(`Cancelled: ${result.confirmation}`); $('[data-action-dialog]').close(); await load(); manage(); }; }));
$('[data-support]')?.addEventListener("click", () => openDialog(`Local support & dispute No external case is filed.
ReasonQuestion about quote Work quality Local payment Details Open local case `, () => { $('[data-support-form]').onsubmit = async (event) => { event.preventDefault(); const result = await api(`/api/projects/${projectId}/support`, {method:"POST", body:Object.fromEntries(new FormData(event.currentTarget))}); toast(`Local case ${result.case_id} opened`); $('[data-action-dialog]').close(); await load(); manage(); }; }));
bindFinal(); renderProgress();
}
function openDialog(content, ready) { const dialog = $('[data-action-dialog]'); $('[data-dialog-content]').innerHTML = content; dialog.showModal(); ready?.(); }
function finalAndReview() { return `Final local payment Remaining: ${cash(state.final_cents)}
Optional tipNo tip $10 $20 $50 Test outcomeSimulated approval Simulated decline Simulated retry
${state.status==='paid_complete'||state.status==='reviewed'?'Final payment approved':`Pay ${cash(state.final_cents)} locally`} Review technician Service typeTV Wall Mounting Furniture Assembly Appliance Installation Rating★★★★★ · 5 stars ★★★★☆ · 4 stars ★★★☆☆ · 3 stars ReviewCareful installation and clear arrival updates. Show on this local technician profile
${state.status==='reviewed'?'Update local review':'Submit local review'} `; }
function bindFinal() {
$('[data-final-payment]')?.addEventListener("submit", async (event) => { event.preventDefault(); const form = event.currentTarget; const values = Object.fromEntries(new FormData(form)); try { await api(`/api/projects/${projectId}/payment`, {method:"POST", body:{kind:"final",scenario:values.scenario,tip_cents:Number(values.tip_cents)}}); await load(); manage(); toast("Final payment and tip approved locally"); } catch(error) { $('.form-error', form).textContent = `${error.message} State preserved for retry.`; } });
$('[data-review]')?.addEventListener("submit", async (event) => { event.preventDefault(); const form = event.currentTarget; const values = Object.fromEntries(new FormData(form)); values.rating = Number(values.rating); values.public = form.elements.public.checked; try { const result = await api(`/api/projects/${projectId}/review`, {method:"POST", body:values}); await load(); manage(); toast(`${result.rating}-star ${result.service_type} review saved locally`); } catch(error) { $('.form-error', form).textContent = error.message; } });
}
load().then(() => { if (state.status === "draft") draft(); else if (state.status === "no_match") noMatch(); else if (state.status === "matched") matched(); else if (state.status === "awaiting_deposit") payment(); else manage(); }).catch((error) => projectRoot.innerHTML = ``);
}
async function loadProviderLeads() {
const target = $('[data-provider-leads]'); if (!target) return;
try { const data = await api("/api/provider/leads"); target.innerHTML = `${h(data.provider)}
${data.leads.length} local assignments Local synthetic technician workspace ${data.leads.length ? `${data.leads.map(lead => `
${h(lead.title)} ${h(lead.project_id)} · ${cash(lead.amount_cents)}
${h(lead.status.replaceAll('_',' '))} Assignment statusAssigned Route scheduled En route / in progress Completed locally Update tracking `).join('')}
` : `No HomeTech assignments yet Match a TV wall mounting appointment to populate this workspace.
Book TV mounting `}`; $('[data-start-provider-demo]')?.addEventListener("click",()=>createProject("tv-wall-mounting")); $$('[data-update-lead]').forEach(button => button.onclick = async () => { const select = $(`[data-lead-status="${button.dataset.updateLead}"]`); await api(`/api/provider/leads/${button.dataset.updateLead}`, {method:"POST", body:{status:select.value}}); toast(`Assignment set to ${select.value}`); }); }
catch(error) { target.textContent = error.message; }
}
loadProviderLeads();
})();