const CACHE = "jianglai-shell-v396-tenant-isolation";
const SHARE_CACHE = "jianglai-shared-intake-v1";
const SHELL = ["/", "/index.html", "/app_shell.css", "/typography_reliability.css", "/quote_express.css", "/tenant_state.js", "/app_core.js", "/app_runtime.js", "/professional_suite.css", "/professional_suite.js", "/customer_portal.html", "/customer_portal.css", "/customer_portal.js", "/design_system.css", "/usability_layer.css", "/usability_layer.js", "/quote_catalog.js", "/quote_industries.js", "/quote_formula.js", "/quote_cost_defaults.js", "/quote_auto_router.js", "/quote_reference_prices.js", "/quote_book.js", "/quote_accuracy.js", "/quote_product_benchmarks.js", "/quote_market_benchmarks.js", "/quote_accuracy_ui.js", "/quote_reliability.js", "/quote_reliability_ui.js", "/quote_template_constraints.js", "/quote_accuracy.css", "/quote_reliability.css", "/order_purchase.css", "/order_purchase.js", "/vector_engine.js", "/vector_exporters.js", "/vector_studio.css", "/vector_studio.js", "/die_layout.css", "/vendor/shengda_box_engine.js", "/shengda_reference_paths.js", "/die_layout.js", "/dieline_3d.css", "/dieline_3d.js", "/imposition_engine.js", "/imposition_workbench.css", "/imposition_workbench.js", "/vendor/vectortracer/vectortracer_bg.js", "/vendor/vectortracer/vectortracer_bg.wasm", "/vendor/vectortracer/vtracer_loader.js", "/vendor/vtracer1/vtracer_wasm.js", "/vendor/vtracer1/vtracer_wasm_bg.wasm", "/vendor/vtracer1/vtracer_loader.js", "/manifest.webmanifest", "/assets/报价跟单助手-logo.png"];

async function offlineFallback(request) {
  const cached = await caches.match(request, { ignoreSearch: true });
  if (cached) return cached;
  if (request.mode === "navigate") {
    const index = await caches.match("/index.html");
    if (index) return index;
  }
  return new Response("当前离线且该资源尚未缓存", {
    status: 503,
    headers: { "Content-Type": "text/plain; charset=utf-8" }
  });
}

self.addEventListener("install", event => {
  event.waitUntil((async () => {
    const cache = await caches.open(CACHE);
    await cache.addAll(SHELL);
    await self.skipWaiting();
  })());
});

self.addEventListener("activate", event => {
  event.waitUntil((async () => {
    const keys = await caches.keys();
    await Promise.all(keys.filter(key => key !== CACHE && key !== SHARE_CACHE).map(key => caches.delete(key)));
    await self.clients.claim();
  })());
});

self.addEventListener("fetch", event => {
  const url = new URL(event.request.url);
  if (url.origin === self.location.origin && url.pathname === "/share-target" && event.request.method === "POST") {
    event.respondWith((async () => {
      const form = await event.request.formData();
      const files = form.getAll("files").filter(item => item && typeof item.arrayBuffer === "function" && "name" in item).slice(0, 10);
      await caches.delete(SHARE_CACHE);
      const cache = await caches.open(SHARE_CACHE);
      const metadata = {
        title: String(form.get("title") || ""),
        text: String(form.get("text") || ""),
        url: String(form.get("url") || ""),
        files: files.map((file, index) => ({ index, name:file.name, type:file.type, size:file.size }))
      };
      await cache.put("/_shared/meta", new Response(JSON.stringify(metadata), { headers:{ "Content-Type":"application/json" } }));
      await Promise.all(files.map((file, index) => cache.put(`/_shared/file-${index}`, new Response(file, { headers:{ "Content-Type":file.type || "application/octet-stream" } }))));
      return Response.redirect("/?shared=1", 303);
    })());
    return;
  }
  if (url.origin === self.location.origin && url.pathname.startsWith("/_shared/")) {
    event.respondWith(caches.open(SHARE_CACHE).then(cache => cache.match(event.request)).then(hit => hit || new Response("", { status:404 })));
    return;
  }
  if (event.request.method !== "GET") return;
  event.respondWith(fetch(event.request).catch(() => offlineFallback(event.request)));
});

self.addEventListener("message", event => {
  if (event.data?.type === "CLEAR_SHARED_INTAKE") event.waitUntil(caches.delete(SHARE_CACHE));
});

self.addEventListener("notificationclick", event => {
  event.notification.close();
  event.waitUntil(self.clients.matchAll({ type: "window", includeUncontrolled: true }).then(clients => {
    const existing = clients[0];
    if (existing) { existing.focus(); existing.postMessage({ type: "OPEN_REMINDERS" }); return existing; }
    return self.clients.openWindow("/?page=reminders");
  }));
});

self.addEventListener("push", event => {
  let payload = { title: "将莱数字员工", body: "你有一条新的工厂待办提醒" };
  try { payload = { ...payload, ...(event.data?.json() || {}) }; } catch (_) {}
  event.waitUntil(self.registration.showNotification(payload.title, {
    body: payload.body,
    tag: payload.tag || "factory-ai-push",
    data: { url: payload.url || "/?page=reminders" }
  }));
});
