
document.addEventListener("DOMContentLoaded", () => {
  const toggle = document.querySelector(".nav-toggle");
  const menu = document.querySelector(".nav-menu");
  if (toggle && menu) {
    toggle.addEventListener("click", () => {
      const open = menu.classList.toggle("open");
      toggle.setAttribute("aria-expanded", open ? "true" : "false");
    });
  }

  const revealItems = document.querySelectorAll(".card, .product-card, .stat-card, .step-card, .team-card, .section-head, .cta-panel");
  if ("IntersectionObserver" in window) {
    const observer = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          entry.target.style.transform = "translateY(0)";
          entry.target.style.opacity = "1";
          observer.unobserve(entry.target);
        }
      });
    }, { threshold: 0.08 });
    revealItems.forEach(el => {
      el.style.opacity = "0";
      el.style.transform = "translateY(14px)";
      el.style.transition = "opacity .5s ease, transform .5s ease";
      observer.observe(el);
    });
  }

  const verifyForm = document.querySelector("#verifyForm");
  if (verifyForm) {
    const employees = {
      "CJ-MD-001": {
        name: "Md Aktaruzzaman",
        designation: "Founder & Managing Director",
        department: "Ownership & Leadership",
        id: "CJ-MD-001",
        status: "Verified / Active"
      },
      "CJ-MP-002": {
        name: "Md Al-Amin",
        designation: "Managing Partner & Co-Founder",
        department: "Ownership & Leadership",
        id: "CJ-MP-002",
        status: "Verified / Active"
      }
    };

    const params = new URLSearchParams(window.location.search);
    const initial = params.get("id");
    const input = document.querySelector("#employeeId");
    if (initial && input) input.value = initial.toUpperCase();

    const render = (data) => {
      const box = document.querySelector("#verifyResult");
      if (!box) return;
      if (!data) {
        box.innerHTML = `<div class="notice"><strong>Not Found</strong><br>No active COLORJET employee record matched this ID. Please check the ID and try again.</div>`;
        box.classList.add("active");
        return;
      }
      box.innerHTML = `
        <div class="glass-card" style="padding:22px">
          <span class="verified-badge">Verified / Active</span>
          <h3 style="margin-top:16px">${data.name}</h3>
          <p><strong>Designation:</strong> ${data.designation}</p>
          <p><strong>Department:</strong> ${data.department}</p>
          <p><strong>Employee ID:</strong> ${data.id}</p>
          <p><strong>Company:</strong> COLORJET Bangladesh</p>
        </div>`;
      box.classList.add("active");
    };

    if (initial) render(employees[initial.toUpperCase()] || null);

    verifyForm.addEventListener("submit", (e) => {
      e.preventDefault();
      const value = (input.value || "").trim().toUpperCase();
      render(employees[value] || null);
    });
  }

  const inquiryForms = document.querySelectorAll("[data-inquiry-form]");
  inquiryForms.forEach(form => {
    form.addEventListener("submit", e => {
      e.preventDefault();
      const fd = new FormData(form);
      const name = fd.get("name") || "";
      const phone = fd.get("phone") || "";
      const product = fd.get("product") || "";
      const message = fd.get("message") || "";
      const text = `Hello COLORJET Bangladesh,%0AName: ${encodeURIComponent(name)}%0APhone: ${encodeURIComponent(phone)}%0AInterested Product: ${encodeURIComponent(product)}%0AMessage: ${encodeURIComponent(message)}`;
      window.open(`https://wa.me/8801954100710?text=${text}`, "_blank");
    });
  });
});

document.addEventListener('DOMContentLoaded', ()=>{
  const body=document.body;
  const savedLang=localStorage.getItem('colorjet_lang') || 'en';
  body.classList.toggle('lang-bn', savedLang==='bn');
  body.classList.toggle('lang-en', savedLang!=='bn');
  const syncLangButtons=()=>{document.querySelectorAll('[data-lang]').forEach(btn=>{btn.classList.toggle('active', btn.getAttribute('data-lang')=== (body.classList.contains('lang-bn')?'bn':'en'));});};
  syncLangButtons();
  document.querySelectorAll('[data-lang]').forEach(btn=>{btn.addEventListener('click', ()=>{const lang=btn.getAttribute('data-lang');body.classList.toggle('lang-bn', lang==='bn');body.classList.toggle('lang-en', lang!=='bn');localStorage.setItem('colorjet_lang', lang);syncLangButtons();});});
  document.querySelectorAll('.mega-toggle').forEach(toggle=>{toggle.addEventListener('click', (e)=>{if(window.innerWidth<=850){e.preventDefault();toggle.closest('.has-mega').classList.toggle('open');}});});
});

document.addEventListener("DOMContentLoaded", () => {
  document.querySelectorAll("[data-counter]").forEach(el => {
    const target = Number(el.dataset.counter || 0);
    const suffix = el.dataset.suffix || "";
    let started = false;
    const animate = () => {
      if (started) return;
      started = true;
      const start = performance.now();
      const run = now => {
        const p = Math.min((now - start) / 1200, 1);
        el.textContent = Math.floor(target * (1 - Math.pow(1-p, 3))).toLocaleString() + suffix;
        if (p < 1) requestAnimationFrame(run);
      };
      requestAnimationFrame(run);
    };
    if ("IntersectionObserver" in window) {
      const obs = new IntersectionObserver(entries => entries.forEach(e => { if(e.isIntersecting){ animate(); obs.disconnect(); } }), {threshold:.35});
      obs.observe(el);
    } else animate();
  });

  const modal = document.getElementById("inquiryModal");
  const productInput = document.getElementById("modalProduct");
  const productTitle = document.getElementById("modalTitleProduct");

  document.querySelectorAll("[data-open-inquiry]").forEach(btn => {
    btn.addEventListener("click", e => {
      e.preventDefault();
      const p = btn.getAttribute("data-product") || document.querySelector("h1")?.innerText?.split("\n")[0] || "COLORJET Product";
      if(productInput) productInput.value = p;
      if(productTitle) productTitle.textContent = p;
      modal?.classList.add("open");
    });
  });
  document.querySelectorAll("[data-close-modal]").forEach(btn => btn.addEventListener("click", () => modal?.classList.remove("open")));
  modal?.addEventListener("click", e => { if(e.target === modal) modal.classList.remove("open"); });

  document.querySelectorAll("[data-smart-inquiry-form]").forEach(form => {
    form.addEventListener("submit", e => {
      e.preventDefault();
      const fd = new FormData(form);
      const text = `Hello COLORJET Bangladesh,%0AI want inquiry for: ${encodeURIComponent(fd.get("product") || "General Inquiry")}%0AName: ${encodeURIComponent(fd.get("name") || "")}%0APhone: ${encodeURIComponent(fd.get("phone") || "")}%0ABusiness Type: ${encodeURIComponent(fd.get("business") || "")}%0AMessage: ${encodeURIComponent(fd.get("message") || "")}`;
      window.open(`https://wa.me/8801954100710?text=${text}`, "_blank");
    });
  });

  document.querySelectorAll(".smart-whatsapp").forEach(btn => {
    btn.addEventListener("click", e => {
      e.preventDefault();
      const p = document.querySelector("h1")?.innerText?.split("\n")[0]?.trim() || "COLORJET Product Inquiry";
      window.open(`https://wa.me/8801954100710?text=Hello COLORJET Bangladesh,%0AI want to know more about: ${encodeURIComponent(p)}`, "_blank");
    });
  });
});

document.addEventListener("DOMContentLoaded", () => {
  document.querySelectorAll("[data-faq-toggle]").forEach(btn => {
    btn.addEventListener("click", () => btn.closest(".faq-item")?.classList.toggle("open"));
  });

  const searchInput = document.querySelector("[data-product-search]");
  const categoryFilter = document.querySelector("[data-category-filter]");
  const techFilter = document.querySelector("[data-tech-filter]");
  const resetBtn = document.querySelector("[data-reset-products]");
  const cards = Array.from(document.querySelectorAll("[data-product-card]"));

  function filterProducts(){
    const q = (searchInput?.value || "").toLowerCase().trim();
    const cat = categoryFilter?.value || "";
    const tech = techFilter?.value || "";
    cards.forEach(card => {
      const text = (card.dataset.search || card.innerText || "").toLowerCase();
      const c = card.dataset.category || "";
      const t = card.dataset.tech || "";
      const ok = (!q || text.includes(q)) && (!cat || c === cat) && (!tech || t.includes(tech));
      card.classList.toggle("product-hidden", !ok);
    });
  }
  [searchInput, categoryFilter, techFilter].forEach(el => el && el.addEventListener("input", filterProducts));
  resetBtn && resetBtn.addEventListener("click", () => {
    if(searchInput) searchInput.value = "";
    if(categoryFilter) categoryFilter.value = "";
    if(techFilter) techFilter.value = "";
    filterProducts();
  });
});

document.addEventListener("DOMContentLoaded", () => {
  // Quote Builder
  const quoteForm = document.querySelector("[data-quote-builder]");
  if (quoteForm) {
    const preview = document.querySelector("[data-quote-preview]");
    const updateQuote = () => {
      const fd = new FormData(quoteForm);
      const lines = [
        "COLORJET Bangladesh - Product Inquiry / Quotation Request",
        "--------------------------------------------------------",
        `Customer Name: ${fd.get("name") || ""}`,
        `Phone: ${fd.get("phone") || ""}`,
        `Business Type: ${fd.get("business") || ""}`,
        `Interested Product: ${fd.get("product") || ""}`,
        `Quantity: ${fd.get("quantity") || ""}`,
        `Location: ${fd.get("location") || ""}`,
        "",
        "Requirement:",
        `${fd.get("message") || ""}`,
        "",
        "Distributor in Bangladesh: COLORJET Bangladesh",
        "Hotline: +8809677610610",
        "WhatsApp: +8801954100710"
      ];
      if (preview) preview.textContent = lines.join("\n");
    };
    quoteForm.addEventListener("input", updateQuote);
    updateQuote();

    quoteForm.addEventListener("submit", e => {
      e.preventDefault();
      const fd = new FormData(quoteForm);
      const text = encodeURIComponent(preview?.textContent || "COLORJET Bangladesh quotation request");
      window.open(`https://wa.me/8801954100710?text=${text}`, "_blank");
    });
  }

  document.querySelectorAll("[data-print-quote]").forEach(btn => btn.addEventListener("click", () => window.print()));

  // Copy templates
  document.querySelectorAll("[data-copy-target]").forEach(btn => {
    btn.addEventListener("click", async () => {
      const id = btn.getAttribute("data-copy-target");
      const text = document.getElementById(id)?.innerText || "";
      try {
        await navigator.clipboard.writeText(text);
        btn.textContent = "Copied";
        setTimeout(() => btn.textContent = "Copy", 1200);
      } catch(e) {
        alert("Copy failed. Please select and copy manually.");
      }
    });
  });

  // Employee Verification Demo
  const verifyForm = document.querySelector("[data-verify-form]");
  if (verifyForm) {
    const result = document.querySelector("[data-verify-result]");
    const notFound = document.querySelector("[data-not-found]");
    const employees = {
      "CJ-MD-001": {name:"Md Aktaruzzaman", designation:"Founder & Managing Director", department:"Leadership", status:"Verified / Active"},
      "CJ-MP-002": {name:"Md Al-Amin", designation:"Managing Partner & Co-Founder", department:"Leadership", status:"Verified / Active"},
      "CJ-TECH-001": {name:"COLORJET Technical Team", designation:"Engineer / Technician", department:"Technical Support", status:"Verified / Active"}
    };
    const render = emp => {
      result.querySelector("[data-v-name]").textContent = emp.name;
      result.querySelector("[data-v-desig]").textContent = emp.designation;
      result.querySelector("[data-v-dept]").textContent = emp.department;
      result.querySelector("[data-v-status]").textContent = emp.status;
      result.classList.add("active");
      if(notFound) notFound.style.display = "none";
    };
    verifyForm.addEventListener("submit", e => {
      e.preventDefault();
      const id = (new FormData(verifyForm).get("employee_id") || "").trim().toUpperCase();
      const emp = employees[id];
      if (emp) render(emp);
      else {
        result.classList.remove("active");
        if(notFound) notFound.style.display = "block";
      }
    });
    const params = new URLSearchParams(location.search);
    const auto = params.get("id");
    if (auto && employees[auto.toUpperCase()]) {
      verifyForm.querySelector("[name='employee_id']").value = auto.toUpperCase();
      render(employees[auto.toUpperCase()]);
    }
  }

  // PWA registration
  if ("serviceWorker" in navigator) {
    navigator.serviceWorker.register("/sw.js").catch(() => {});
  }
});

document.addEventListener("DOMContentLoaded", () => {
  document.querySelectorAll("[data-lead-form]").forEach(form => {
    form.addEventListener("submit", e => {
      e.preventDefault();
      const fd = new FormData(form);
      const type = form.getAttribute("data-lead-form") || "Lead";
      const lines = [`COLORJET Bangladesh - ${type}`, "--------------------------------"];
      for (const [k, v] of fd.entries()) lines.push(`${k}: ${v}`);
      lines.push("", "Hotline: +8809677610610");
      const text = encodeURIComponent(lines.join("\n"));
      window.open(`https://wa.me/8801954100710?text=${text}`, "_blank");
    });
  });

  document.querySelectorAll("[data-download-json]").forEach(btn => {
    btn.addEventListener("click", () => {
      const data = btn.getAttribute("data-download-json") || "{}";
      const filename = btn.getAttribute("data-filename") || "colorjet-data.json";
      const blob = new Blob([data], {type:"application/json"});
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url; a.download = filename; a.click();
      URL.revokeObjectURL(url);
    });
  });
});

document.addEventListener("DOMContentLoaded", () => {
  // Lead capture log in localStorage for static website
  function saveLead(type, data) {
    const key = "colorjet_leads";
    const leads = JSON.parse(localStorage.getItem(key) || "[]");
    leads.unshift({type, date:new Date().toISOString(), data});
    localStorage.setItem(key, JSON.stringify(leads.slice(0, 200)));
  }

  document.querySelectorAll("[data-lead-form], [data-smart-inquiry-form], [data-quote-builder]").forEach(form => {
    form.addEventListener("submit", () => {
      const fd = new FormData(form);
      const data = {};
      for (const [k, v] of fd.entries()) data[k] = v;
      saveLead(form.getAttribute("data-lead-form") || form.getAttribute("data-quote-builder") || "Inquiry", data);
    }, {capture:true});
  });

  // Lead dashboard
  const leadTable = document.querySelector("[data-lead-table]");
  if (leadTable) {
    const leads = JSON.parse(localStorage.getItem("colorjet_leads") || "[]");
    const rows = leads.map((l, i) => `<tr><td>${i+1}</td><td>${l.type}</td><td>${new Date(l.date).toLocaleString()}</td><td><pre>${JSON.stringify(l.data, null, 2)}</pre></td></tr>`).join("");
    leadTable.innerHTML = rows || `<tr><td colspan="4">No lead saved in this browser yet.</td></tr>`;
  }

  document.querySelectorAll("[data-export-leads]").forEach(btn => {
    btn.addEventListener("click", () => {
      const leads = localStorage.getItem("colorjet_leads") || "[]";
      const blob = new Blob([leads], {type:"application/json"});
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url; a.download = "colorjet-leads.json"; a.click();
      URL.revokeObjectURL(url);
    });
  });

  document.querySelectorAll("[data-clear-leads]").forEach(btn => {
    btn.addEventListener("click", () => {
      if(confirm("Clear saved leads from this browser?")) {
        localStorage.removeItem("colorjet_leads");
        location.reload();
      }
    });
  });

  // Product compare builder
  const compareRoot = document.querySelector("[data-compare-root]");
  if (compareRoot) {
    const products = JSON.parse(compareRoot.getAttribute("data-products") || "[]");
    const selects = compareRoot.querySelectorAll("select");
    const output = compareRoot.querySelector("[data-compare-output]");
    function renderCompare(){
      const selected = Array.from(selects).map(s => products.find(p => p.slug === s.value)).filter(Boolean);
      if (!selected.length) { output.innerHTML = "<p>Select products to compare.</p>"; return; }
      output.innerHTML = selected.map(p => `
        <article class="compare-card">
          <span class="badge-v7">${p.category}</span>
          <h3>${p.name}</h3>
          <p>${p.description}</p>
          <p><strong>Technology:</strong> ${p.technology || ""}</p>
          <p><strong>Applications:</strong> ${(p.applications || []).slice(0,4).join(", ")}</p>
          <a class="btn btn-glass" href="products/items/${p.slug}.html">View Details</a>
        </article>
      `).join("");
    }
    selects.forEach(s => s.addEventListener("change", renderCompare));
    renderCompare();
  }

  // CMS demo editor
  const cmsForm = document.querySelector("[data-cms-form]");
  if (cmsForm) {
    const out = document.querySelector("[data-cms-output]");
    cmsForm.addEventListener("input", () => {
      const data = {};
      new FormData(cmsForm).forEach((v,k)=> data[k]=v);
      out.textContent = JSON.stringify(data, null, 2);
    });
    cmsForm.dispatchEvent(new Event("input"));
  }
});

document.addEventListener("DOMContentLoaded", () => {
  async function submitLeadToServer(type, data) {
    try {
      await fetch("/api/submit-lead.php", {
        method: "POST",
        headers: {"Content-Type": "application/json"},
        body: JSON.stringify({type, data, page: location.pathname, source: "colorjetbd.com"})
      });
    } catch (e) {
      // Static preview or server without PHP: silently keep WhatsApp/localStorage flow working.
    }
  }

  document.querySelectorAll("[data-lead-form], [data-smart-inquiry-form], [data-quote-builder], [data-verify-form]").forEach(form => {
    form.addEventListener("submit", () => {
      const fd = new FormData(form);
      const data = {};
      for (const [k, v] of fd.entries()) data[k] = v;
      const type = form.getAttribute("data-lead-form") || form.getAttribute("data-quote-builder") || "Website Inquiry";
      submitLeadToServer(type, data);
    }, {capture:true});
  });
});

document.addEventListener("DOMContentLoaded", () => {
  document.querySelectorAll("[data-demo-counter]").forEach(el => {
    const target = Number(el.dataset.demoCounter || 0);
    let start = null;
    const suffix = el.dataset.suffix || "";
    function step(ts){
      if(!start) start = ts;
      const p = Math.min((ts - start) / 1000, 1);
      el.textContent = Math.floor(target * (1 - Math.pow(1-p, 3))).toLocaleString() + suffix;
      if(p < 1) requestAnimationFrame(step);
    }
    requestAnimationFrame(step);
  });
});

document.addEventListener("DOMContentLoaded", () => {
  if (!document.querySelector(".lang-toggle-panel")) {
    const panel = document.createElement("div");
    panel.className = "lang-toggle-panel no-print";
    panel.innerHTML = `<button type="button" data-set-lang="en">EN</button><button type="button" data-set-lang="bn">BN</button>`;
    document.body.appendChild(panel);
  }

  const savedLang = localStorage.getItem("colorjet_lang");
  if (savedLang === "bn" || savedLang === "en") {
    document.body.classList.remove("lang-en","lang-bn");
    document.body.classList.add("lang-" + savedLang);
  }

  document.querySelectorAll("[data-set-lang]").forEach(btn => {
    btn.addEventListener("click", () => {
      const lang = btn.getAttribute("data-set-lang");
      document.body.classList.remove("lang-en","lang-bn");
      document.body.classList.add("lang-" + lang);
      localStorage.setItem("colorjet_lang", lang);
    });
  });

  document.querySelectorAll("[data-copy-text]").forEach(btn => {
    btn.addEventListener("click", async () => {
      const target = document.querySelector(btn.getAttribute("data-copy-text"));
      const text = target?.innerText || "";
      try {
        await navigator.clipboard.writeText(text);
        const old = btn.textContent;
        btn.textContent = "Copied";
        setTimeout(()=>btn.textContent=old, 1200);
      } catch(e) {}
    });
  });
});

document.addEventListener("DOMContentLoaded", () => {
  document.querySelectorAll("[data-page-search]").forEach(input => {
    const targets = Array.from(document.querySelectorAll("[data-search-item]"));
    input.addEventListener("input", () => {
      const q = input.value.toLowerCase().trim();
      targets.forEach(item => {
        const text = (item.innerText || "").toLowerCase();
        item.classList.toggle("hidden-by-search", q && !text.includes(q));
      });
    });
  });

  // Add skip link for keyboard users
  if (!document.querySelector(".skip-link")) {
    const a = document.createElement("a");
    a.className = "skip-link";
    a.href = "#main-content";
    a.textContent = "Skip to content";
    a.style.cssText = "position:absolute;left:-999px;top:10px;background:#2F5BFF;color:#fff;padding:10px 14px;border-radius:10px;z-index:9999";
    a.addEventListener("focus", () => a.style.left = "10px");
    a.addEventListener("blur", () => a.style.left = "-999px");
    document.body.prepend(a);
  }
});

document.addEventListener("DOMContentLoaded", () => {
  document.querySelectorAll("[data-final-copy]").forEach(btn => {
    btn.addEventListener("click", async () => {
      const target = document.querySelector(btn.getAttribute("data-final-copy"));
      const text = target?.innerText || "";
      try {
        await navigator.clipboard.writeText(text);
        const old = btn.textContent;
        btn.textContent = "Copied";
        setTimeout(()=>btn.textContent=old, 1200);
      } catch(e) {}
    });
  });
});

document.addEventListener("DOMContentLoaded", () => {
  window.colorjetTrack = function(eventName, eventData = {}) {
    try {
      const events = JSON.parse(localStorage.getItem("colorjet_events") || "[]");
      events.unshift({eventName, eventData, page: location.pathname, date: new Date().toISOString()});
      localStorage.setItem("colorjet_events", JSON.stringify(events.slice(0, 300)));
    } catch(e) {}
    if (typeof gtag === "function") gtag("event", eventName, eventData);
    if (typeof fbq === "function") fbq("trackCustom", eventName, eventData);
  };
  document.querySelectorAll("a[href*='wa.me']").forEach(link => link.addEventListener("click", () => window.colorjetTrack("WhatsApp_Click", {href: link.href})));
  document.querySelectorAll("a[href^='tel:']").forEach(link => link.addEventListener("click", () => window.colorjetTrack("Call_Click", {href: link.href})));
  document.querySelectorAll("[data-utm-builder]").forEach(form => {
    const output = document.querySelector("[data-utm-output]");
    const build = () => {
      const fd = new FormData(form);
      const base = fd.get("url") || "https://www.colorjetbd.com/";
      const params = new URLSearchParams();
      ["utm_source","utm_medium","utm_campaign","utm_content","utm_term"].forEach(k => { const v = fd.get(k); if(v) params.set(k,v); });
      if(output) output.textContent = base + (base.includes("?") ? "&" : "?") + params.toString();
    };
    form.addEventListener("input", build); build();
  });
});

document.addEventListener("DOMContentLoaded", () => {
  document.querySelectorAll("[data-handover-form]").forEach(form => {
    const preview = document.querySelector("[data-handover-preview]");
    const build = () => {
      const fd = new FormData(form);
      const lines = [
        "COLORJET Website Deployment Note",
        "Domain: " + (fd.get("domain") || ""),
        "Hosting: " + (fd.get("hosting") || ""),
        "Upload Path: " + (fd.get("path") || ""),
        "Admin URL: " + (fd.get("admin_url") || ""),
        "Backup Status: " + (fd.get("backup") || ""),
        "Launch Date: " + (fd.get("launch_date") || ""),
        "Responsible Person: " + (fd.get("responsible") || ""),
        "",
        "Final Checks:",
        "- Admin password changed",
        "- Sitemap submitted",
        "- Forms tested",
        "- Mobile view tested",
        "- Old website backup saved"
      ];
      if (preview) preview.textContent = lines.join("\n");
    };
    form.addEventListener("input", build);
    build();
  });

  document.querySelectorAll("[data-copy-preview]").forEach(btn => {
    btn.addEventListener("click", async () => {
      const target = document.querySelector(btn.getAttribute("data-copy-preview"));
      try {
        await navigator.clipboard.writeText(target?.textContent || "");
        const old = btn.textContent;
        btn.textContent = "Copied";
        setTimeout(() => btn.textContent = old, 1200);
      } catch(e) {}
    });
  });
});
