/* United Wolfram website — app shell with hash-based SEO routing and AEO meta management. */
const _DS = window.UnitedWolframDesignSystem_d15b43;
const { NavBar, Footer, Hero, Button } = _DS;

const NAV = ["Products", "Industry Solutions", "Research", "Enquiry", "Contact"];

const NAV_MENUS = {
  Products: {
    type: "products",
    columns: window.UW_DATA.productLines.map((g) => ({
      title: g.group,
      items: g.items,
    })),
    featured: [
      {
        label: "Tungsten Metal Powder",
        desc: "High-purity. Multiple grain sizes. Computerised QC.",
        image: "https://unitedwolfram.com/wp-content/uploads/2014/01/tungsten-metal-1-1.5-micron_320x237-400x400.jpg",
      },
      {
        label: "Tungsten Carbide Powder",
        desc: "Near-diamond hardness. Standard & custom WC grades.",
        image: "https://unitedwolfram.com/wp-content/uploads/2014/01/tungsten-carbide-0.5-2-micron-400x400.jpg",
      },
    ],
    footerLink: "View all 18 products →",
  },
  "Industry Solutions": {
    type: "industries",
    intro: {
      stat: "16+",
      statLabel: "Industries served worldwide",
      body: "Aerospace to semiconductor. One quality-assured tungsten and cobalt source from Gujarat, India.",
    },
    items: window.UW_DATA.industries,
  },
};

/* ─── HASH ROUTING ──────────────────────────────────────────────────
   URL shape:  /#/products/tungsten-metal-powder
               /#/industry-solutions/aerospace
               /#/contact
   The hash keeps it SPA-friendly while giving every view a shareable,
   SEO-addressable path segment that matches the clean URL architecture
   defined in SEO_AEO_AUDIT.md.                                      */
function parseHash() {
  const h = (window.location.hash || "").replace(/^#\/?/, "");
  const parts = h.split("/").filter(Boolean);
  if (!parts.length) return { route: "home", sub: null };
  const [top, sub] = parts;
  return { route: top || "home", sub: sub || null };
}

function pushHash(path) {
  window.location.hash = "/" + path;
}

function HeroRotator() {
  const heroes = window.UW_DATA.heroes;
  const [i, setI] = React.useState(0);
  React.useEffect(() => {
    const t = setInterval(() => setI((n) => (n + 1) % heroes.length), 6000);
    return () => clearInterval(t);
  }, []);
  /* All slides stay mounted, stacked, and crossfade on opacity — the
     Apple treatment. Slide 0 is in normal flow so the stack keeps its
     height; the rest overlay it. Keeping every slide mounted also
     pre-decodes the photos, so no flash on first rotation. */
  return (
    <div style={{ position: "relative", overflow: "hidden" }}>
      {heroes.map((h, n) => (
        <div
          key={n}
          aria-hidden={n !== i}
          style={{
            position: n === 0 ? "relative" : "absolute",
            inset: n === 0 ? undefined : 0,
            opacity: n === i ? 1 : 0,
            zIndex: n === i ? 1 : 0,
            pointerEvents: n === i ? "auto" : "none",
            transition: "opacity 1200ms var(--ease-standard)",
            willChange: "opacity",
          }}
        >
          <Hero
            image={h.image}
            eyebrow={h.eyebrow}
            title={h.title}
            subtitle={h.subtitle}
            primaryAction={{ label: "Explore products", href: "#/products" }}
            secondaryAction={{ label: "Corporate overview", href: "#about" }}
          />
        </div>
      ))}
      <div style={{ position: "absolute", bottom: "26px", left: "50%", transform: "translateX(-50%)", display: "flex", gap: "10px", zIndex: 2 }}>
        {heroes.map((_, n) => (
          <button
            key={n}
            aria-label={"Slide " + (n + 1)}
            onClick={() => setI(n)}
            style={{
              width: n === i ? "26px" : "9px", height: "9px",
              borderRadius: "var(--radius-pill)", border: "none", cursor: "pointer",
              background: n === i ? "#fff" : "rgba(255,255,255,0.5)",
              transition: "all var(--dur-base) var(--ease-out)",
            }}
          />
        ))}
      </div>
    </div>
  );
}

function HomeView({ go }) {
  React.useEffect(() => {
    window.UW_SEO.updatePageMeta(
      window.UW_DATA.siteMeta.defaultTitle,
      window.UW_DATA.siteMeta.defaultDescription,
      "/"
    );
    window.UW_SEO.cleanPageSchemas();
  }, []);
  return (
    <React.Fragment>
      <HeroRotator />
      <window.FeaturedProducts onOpen={(slug) => go("products/" + (slug || ""))} />
      <CorporateOverview />
      <IndustriesSection onOpen={(ind) => go("industry-solutions/" + ind.toLowerCase().replace(/[\s&]+/g, "-"))} />
      <ValuesSection />
      <ContactSection />
    </React.Fragment>
  );
}

function ProductsView({ go }) {
  React.useEffect(() => {
    window.UW_SEO.updatePageMeta(
      "Tungsten & Cobalt Products — United Wolfram",
      "Browse 30+ tungsten and cobalt powder grades: Ammonium Paratungstate, Tungsten Metal Powder, Tungsten Carbide, Cobalt compounds. Automated QC. Export worldwide.",
      "/products/"
    );
    window.UW_SEO.cleanPageSchemas();
    window.UW_SEO.injectBreadcrumb([
      { name: "Home", path: "/" },
      { name: "Products", path: "/products/" },
    ]);
  }, []);
  return (
    <React.Fragment>
      <Hero
        tone="dark"
        eyebrow="Products"
        title="Tungsten &amp; cobalt, in every grade."
        subtitle="A complete portfolio of specialty and fine chemicals — engineered powders for cemented carbides, diamond tools and beyond. 30+ product grades. Fully automated QC. Export worldwide."
        minHeight="46vh"
      />
      <window.ProductCatalog onSelect={(slug) => go("products/" + slug)} />
      <window.FeaturedProducts onOpen={(slug) => go("products/" + (slug || ""))} />
    </React.Fragment>
  );
}

function ResearchView() {
  React.useEffect(() => {
    window.UW_SEO.updatePageMeta(
      "Tungsten Research & Development — United Wolfram",
      "United Wolfram's R&D programme advances tungsten powder metallurgy, custom grade development and process innovation for next-generation applications.",
      "/research/"
    );
    window.UW_SEO.cleanPageSchemas();
  }, []);
  return (
    <React.Fragment>
      <Hero
        tone="dark"
        eyebrow="Research"
        title="Advancing the science of tungsten."
        subtitle="United Wolfram's research programme drives innovation in tungsten powder metallurgy, custom grade development and next-generation material applications."
        minHeight="42vh"
      />
      <section data-reveal="" style={{ maxWidth: "var(--container-wide)", margin: "0 auto", padding: "var(--space-12) var(--gutter)" }}>
        <p style={{ fontFamily: "var(--font-text)", fontSize: "var(--size-body-lg)", lineHeight: "var(--leading-body)", color: "var(--text-secondary)", maxWidth: "700px" }}>
          At United Wolfram, research and development is embedded in every stage of the production process. Our team continuously refines grain-size distribution, purity levels, and chemical composition to meet the evolving needs of customers in aerospace, semiconductor, medical and advanced manufacturing sectors.
        </p>
        <p style={{ fontFamily: "var(--font-text)", fontSize: "var(--size-body)", lineHeight: "var(--leading-body)", color: "var(--text-secondary)", maxWidth: "700px", marginTop: "var(--space-5)" }}>
          Custom grades developed on request. Contact our technical team to discuss application-specific requirements.
        </p>
      </section>
    </React.Fragment>
  );
}

function EnquiryView() {
  React.useEffect(() => {
    window.UW_SEO.updatePageMeta(
      "Product Enquiry — United Wolfram",
      "Request a product enquiry, samples, technical data sheets or pricing from United Wolfram. Headquartered in Gujarat, India. Serving customers worldwide.",
      "/enquiry/"
    );
    window.UW_SEO.cleanPageSchemas();
  }, []);
  return (
    <React.Fragment>
      <Hero
        tone="dark"
        eyebrow="Enquiry"
        title="Request a product enquiry."
        subtitle="Samples, technical data sheets, custom grades and pricing — our team responds within one business day."
        minHeight="38vh"
      />
      <window.ContactSection />
    </React.Fragment>
  );
}

function ContactView() {
  React.useEffect(() => {
    window.UW_SEO.updatePageMeta(
      "Contact United Wolfram — Tungsten Powder Enquiries",
      "Contact United Wolfram for product enquiries, technical specifications, samples and pricing. Headquarters: Gujarat, India. Serving customers worldwide.",
      "/contact/"
    );
    window.UW_SEO.cleanPageSchemas();
  }, []);
  return (
    <React.Fragment>
      <Hero
        tone="dark"
        eyebrow="Contact"
        title="Get in touch."
        subtitle="Headquartered in Gujarat, India — serving customers across sixteen industries worldwide. We respond within one business day."
        minHeight="42vh"
      />
      <window.ContactSection />
    </React.Fragment>
  );
}

function App() {
  const [loc, setLoc] = React.useState(parseHash);

  React.useEffect(() => {
    const handler = () => setLoc(parseHash());
    window.addEventListener("hashchange", handler);
    return () => window.removeEventListener("hashchange", handler);
  }, []);

  const go = (path) => {
    pushHash(path);
    window.scrollTo({ top: 0, behavior: "instant" in window ? "instant" : "auto" });
  };

  const { route, sub } = loc;

  /* NAV active label */
  const activeLabel =
    route === "products" ? "Products" :
    route === "industry-solutions" ? "Industry Solutions" :
    route === "research" ? "Research" :
    route === "enquiry" ? "Enquiry" :
    route === "contact" ? "Contact" : undefined;

  /* item = specific entry clicked inside a mega-menu (product name or
     industry name); absent for top-level nav clicks and "view all". */
  const handleNav = (label, item) => {
    if (label === "Products") {
      if (item) {
        const p = window.UW_DATA.allProducts.find((x) => x.name === item);
        if (p) return go("products/" + p.slug);
      }
      go("products");
    } else if (label === "Industry Solutions") {
      if (item) return go("industry-solutions/" + item.toLowerCase().replace(/[^a-z0-9]+/g, "-"));
      go("industry-solutions");
    }
    else if (label === "Research") go("research");
    else if (label === "Enquiry") go("enquiry");
    else if (label === "Contact") go("contact");
  };

  /* Footer links → routes. Falls back to the column's landing page. */
  const handleFooterNav = (colTitle, link) => {
    if (colTitle === "Products") {
      const p = window.UW_DATA.allProducts.find(
        (x) => x.name === link || x.name.indexOf(link.replace(/ \(YTO\)$/, "")) === 0
      );
      return go(p ? "products/" + p.slug : "products");
    }
    if (colTitle === "Industry Solutions") {
      const ind = window.UW_DATA.industries.find((i) => i === link);
      return go(ind ? "industry-solutions/" + ind.toLowerCase().replace(/[^a-z0-9]+/g, "-") : "industry-solutions");
    }
    if (colTitle === "Company") return go(link === "Research" ? "research" : "");
    if (colTitle === "Contact") return go(link === "Enquiry" ? "enquiry" : "contact");
    go("");
  };

  const renderView = () => {
    if (route === "home" || route === "") return <HomeView go={go} />;
    if (route === "products") {
      if (sub) return <window.ProductDetailView slug={sub} onNav={(r) => go(r)} />;
      return <ProductsView go={go} />;
    }
    if (route === "industry-solutions") {
      if (sub) {
        // Find industry name from slug
        const ind = window.UW_DATA.industries.find(
          i => i.toLowerCase().replace(/[\s&]+/g, "-") === sub || i.toLowerCase().replace(/[^a-z0-9]+/g, "-") === sub
        ) || sub;
        return <window.IndustryDetailView industry={ind} onNav={(r) => go(r)} />;
      }
      return <window.IndustrySolutionsView onSelectIndustry={(ind) => go("industry-solutions/" + ind.toLowerCase().replace(/[^a-z0-9]+/g, "-"))} />;
    }
    if (route === "research") return <ResearchView />;
    if (route === "enquiry") return <EnquiryView />;
    if (route === "contact") return <ContactView />;
    return <HomeView go={go} />;
  };

  return (
    <React.Fragment>
      <NavBar
        items={NAV}
        menus={NAV_MENUS}
        active={activeLabel}
        onNavClick={handleNav}
        onLogoClick={() => go("")}
        logoSrc="assets/logo/united-wolfram-logo.png"
        action={<Button size="sm" onClick={() => go("enquiry")}>Enquiry</Button>}
      />
      {renderView()}
      <Footer
        logoSrc="assets/logo/united-wolfram-logo.png"
        onNavigate={handleFooterNav}
      />
      {route !== "home" && route !== "" && (
        <button
          onClick={() => go("")}
          style={{
            position: "fixed", left: "20px", bottom: "20px", zIndex: 200,
            fontFamily: "var(--font-sans)", fontSize: "var(--size-footnote)", fontWeight: 600,
            color: "#fff", background: "var(--brand)", border: "none",
            borderRadius: "var(--radius-pill)", padding: "10px 18px", cursor: "pointer",
            boxShadow: "var(--shadow-brand)",
          }}
        >
          ‹ Home
        </button>
      )}
    </React.Fragment>
  );
}

window.UWApp = App;
