/* United Wolfram website — page sections, composed from DS primitives. */
const DS = window.UnitedWolframDesignSystem_d15b43;
const { ProductCard, SectionHeader, Card, Badge, Input, Button } = DS;

const Section = ({ children, tone = "page", id, pad = "var(--section-pad)", style }) => (
  <section
    id={id}
    data-reveal=""
    style={{
      background:
        tone === "subtle" ? "var(--surface-subtle)" :
        tone === "dark" ? "var(--surface-brand-dark)" :
        tone === "brand" ? "var(--surface-brand)" : "var(--surface-page)",
      paddingTop: pad,
      paddingBottom: pad,
      ...style,
    }}
  >
    <div style={{ maxWidth: "var(--container-wide)", margin: "0 auto", padding: "0 var(--gutter)" }}>
      {children}
    </div>
  </section>
);

/* ---- Featured products (Apple-store-style tile grid) ---- */
function FeaturedProducts({ onOpen }) {
  const d = window.UW_DATA;
  return (
    <Section tone="subtle" id="products">
      <SectionHeader
        eyebrow="Products"
        title="Engineered powders for demanding industries."
        subtitle="United Wolfram manufactures tungsten chemicals, tungsten metal powders, tungsten carbide grades and cobalt compounds in Gujarat, India — each under fully automated, computerised quality control."
      />
      <div
        style={{
          marginTop: "var(--space-12)",
          display: "grid",
          gridTemplateColumns: "repeat(auto-fit, minmax(240px, 1fr))",
          gap: "var(--space-6)",
        }}
      >
        {d.featured.map((p) => (
          <ProductCard key={p.title} {...p} href="#" onClick={(e) => { e.preventDefault(); onOpen && onOpen(p.slug); }} />
        ))}
      </div>
      <div style={{ textAlign: "center", marginTop: "var(--space-10)" }}>
        <Button variant="secondary" size="lg" href="#" onClick={(e) => { e.preventDefault(); onOpen && onOpen(); /* products landing */ }}>
          View all products
        </Button>
      </div>
    </Section>
  );
}

/* ---- Full product catalog — Apple-style image grid with group tabs ---- */
function ProductCatalog({ onSelect }) {
  const d = window.UW_DATA;
  const groups = ["All", ...d.productLines.map(l => l.group)];
  const [active, setActive] = React.useState("All");
  const products = active === "All"
    ? d.allProducts
    : d.allProducts.filter(p => p.group === active);

  return (
    <Section id="catalog">
      <SectionHeader
        eyebrow="All Products"
        title="A complete tungsten & cobalt portfolio."
        subtitle="18 products across tungsten chemicals, tungsten powders and cobalt compounds — manufactured in Gujarat, India with fully automated QC and exported worldwide."
      />

      {/* Filter tabs */}
      <div style={{
        marginTop: "var(--space-8)",
        display: "flex",
        gap: "var(--space-2)",
        flexWrap: "wrap",
        justifyContent: "center",
      }}>
        {groups.map(g => (
          <button
            key={g}
            onClick={() => setActive(g)}
            style={{
              fontFamily: "var(--font-text)",
              fontSize: "var(--size-footnote)",
              fontWeight: active === g ? 600 : 400,
              color: active === g ? "#fff" : "var(--text-primary)",
              background: active === g ? "var(--brand)" : "var(--surface-card)",
              border: active === g ? "1px solid var(--brand)" : "1px solid var(--border)",
              borderRadius: "var(--radius-pill)",
              padding: "8px 18px",
              cursor: "pointer",
              transition: "all 160ms var(--ease-standard)",
              whiteSpace: "nowrap",
            }}
          >{g}</button>
        ))}
      </div>

      {/* Product image grid */}
      <div style={{
        marginTop: "var(--space-10)",
        display: "grid",
        gridTemplateColumns: "repeat(auto-fill, minmax(200px, 1fr))",
        gap: "var(--space-5)",
      }}>
        {products.map(p => (
          <button
            key={p.slug}
            onClick={() => onSelect && onSelect(p.slug)}
            style={{
              background: "var(--surface-card)",
              border: "1px solid var(--border-subtle)",
              borderRadius: "var(--radius-xl)",
              padding: 0,
              cursor: "pointer",
              textAlign: "left",
              overflow: "hidden",
              transition: "box-shadow 200ms var(--ease-standard), transform 200ms var(--ease-standard), border-color 200ms var(--ease-standard)",
              boxShadow: "var(--shadow-xs)",
            }}
            onMouseEnter={e => { e.currentTarget.style.boxShadow = "0 8px 32px rgba(0,0,0,0.10)"; e.currentTarget.style.transform = "translateY(-3px)"; e.currentTarget.style.borderColor = "var(--text-brand)"; }}
            onMouseLeave={e => { e.currentTarget.style.boxShadow = "var(--shadow-xs)"; e.currentTarget.style.transform = "none"; e.currentTarget.style.borderColor = "var(--border-subtle)"; }}
          >
            {/* Product image */}
            <div style={{
              aspectRatio: "1",
              background: "#f5f5f7",
              overflow: "hidden",
            }}>
              <img
                src={p.image}
                alt={p.name}
                loading="lazy"
                style={{ width: "100%", height: "100%", objectFit: "cover", display: "block" }}
              />
            </div>
            {/* Card body */}
            <div style={{ padding: "14px 16px 16px" }}>
              <div style={{
                fontFamily: "var(--font-text)",
                fontSize: "10px",
                fontWeight: 600,
                textTransform: "uppercase",
                letterSpacing: "0.08em",
                color: "var(--text-brand)",
                marginBottom: "5px",
              }}>{p.group}</div>
              <div style={{
                fontFamily: "var(--font-sans)",
                fontSize: "14px",
                fontWeight: 600,
                color: "var(--text-primary)",
                lineHeight: "1.3",
                marginBottom: "6px",
              }}>{p.name}</div>
              <div style={{
                fontFamily: "var(--font-text)",
                fontSize: "12px",
                color: "var(--text-secondary)",
                lineHeight: "1.45",
                display: "-webkit-box",
                WebkitLineClamp: 2,
                WebkitBoxOrient: "vertical",
                overflow: "hidden",
              }}>{p.tagline}</div>
              <div style={{
                marginTop: "10px",
                fontFamily: "var(--font-text)",
                fontSize: "12px",
                fontWeight: 500,
                color: "var(--text-brand)",
              }}>Learn more ›</div>
            </div>
          </button>
        ))}
      </div>
    </Section>
  );
}

/* ---- Corporate overview: split layout with stats ---- */
function CorporateOverview() {
  const o = window.UW_DATA.overview;
  return (
    <Section tone="page" id="about">
      <div
        style={{
          display: "grid",
          gridTemplateColumns: "repeat(auto-fit, minmax(320px, 1fr))",
          gap: "var(--space-16)",
          alignItems: "center",
        }}
      >
        <div>
          <SectionHeader align="left" eyebrow={o.eyebrow} title={o.title} subtitle={o.body} />
          <div style={{ display: "flex", gap: "var(--space-10)", marginTop: "var(--space-10)", flexWrap: "wrap" }}>
            {o.stats.map((s) => (
              <div key={s.label} style={{ maxWidth: "160px" }}>
                <div style={{ fontFamily: "var(--font-sans)", fontSize: "var(--size-title-1)", fontWeight: "var(--weight-bold)", color: "var(--text-brand)", letterSpacing: "var(--tracking-display)" }}>
                  {s.value}
                </div>
                <div style={{ fontSize: "var(--size-footnote)", color: "var(--text-secondary)", marginTop: "6px", lineHeight: "var(--leading-body)" }}>
                  {s.label}
                </div>
              </div>
            ))}
          </div>
        </div>
        <div
          style={{
            borderRadius: "var(--radius-2xl)",
            overflow: "hidden",
            boxShadow: "var(--shadow-lg)",
            aspectRatio: "43 / 28",
            background: "var(--gray-100)",
          }}
        >
          <img src={o.image} alt="United Wolfram operations" loading="lazy" decoding="async" style={{ width: "100%", height: "100%", objectFit: "cover" }} />
        </div>
      </div>
    </Section>
  );
}

/* ---- Values (Life at United Wolfram) ---- */
function ValuesSection() {
  const d = window.UW_DATA;
  return (
    <Section tone="dark" id="values">
      <SectionHeader
        tone="dark"
        eyebrow="Life — the United Wolfram way"
        title="Our people are our biggest strength."
        subtitle="At United Wolfram, integrity, superior performance and customer orientation are not values on a wall — they are the operating principles of every department, every shift, every shipment."
      />
      <div
        style={{
          marginTop: "var(--space-12)",
          display: "grid",
          gridTemplateColumns: "repeat(auto-fit, minmax(240px, 1fr))",
          gap: "var(--space-6)",
        }}
      >
        {d.values.map((v) => (
          <div
            key={v.title}
            style={{
              background: "rgba(255,255,255,0.06)",
              border: "1px solid rgba(255,255,255,0.12)",
              borderRadius: "var(--radius-lg)",
              padding: "var(--space-6)",
              backdropFilter: "var(--blur-overlay)",
            }}
          >
            <h3 style={{ fontFamily: "var(--font-sans)", fontSize: "var(--size-title-3)", fontWeight: "var(--weight-semibold)", color: "#fff", margin: "0 0 10px" }}>
              {v.title}
            </h3>
            <p style={{ fontSize: "var(--size-subhead)", color: "rgba(255,255,255,0.78)", margin: 0, lineHeight: "var(--leading-body)" }}>
              {v.body}
            </p>
          </div>
        ))}
      </div>
    </Section>
  );
}

/* ---- Industries served (chip wall) ---- */
function IndustriesSection({ onOpen }) {
  const d = window.UW_DATA;
  return (
    <Section tone="subtle" id="industries">
      <SectionHeader
        eyebrow="Industry Solutions"
        title="Trusted across 16+ industries worldwide."
        subtitle="United Wolfram supplies tungsten and cobalt powders to aerospace, defence, oil & gas, semiconductor, medical, mining and 10+ other sectors globally. Click any industry to explore relevant products."
      />
      <div style={{ marginTop: "var(--space-10)", display: "flex", flexWrap: "wrap", gap: "var(--space-3)", justifyContent: "center" }}>
        {d.industries.map((ind) => (
          <a
            key={ind}
            href="#"
            onClick={(e) => { e.preventDefault(); onOpen && onOpen(ind); }}
            style={{
              fontFamily: "var(--font-sans)",
              fontSize: "var(--size-subhead)",
              fontWeight: "var(--weight-medium)",
              color: "var(--text-primary)",
              background: "var(--surface-card)",
              border: "1px solid var(--border)",
              borderRadius: "var(--radius-pill)",
              padding: "10px 18px",
              textDecoration: "none",
              transition: "all var(--dur-fast) var(--ease-standard)",
            }}
            onMouseEnter={(e) => { e.currentTarget.style.background = "var(--brand)"; e.currentTarget.style.color = "#fff"; e.currentTarget.style.borderColor = "var(--brand)"; }}
            onMouseLeave={(e) => { e.currentTarget.style.background = "var(--surface-card)"; e.currentTarget.style.color = "var(--text-primary)"; e.currentTarget.style.borderColor = "var(--border)"; }}
          >
            {ind}
          </a>
        ))}
      </div>
    </Section>
  );
}

/* ---- Contact / purchase enquiry ---- */
function ContactSection() {
  const [sent, setSent] = React.useState(false);
  const [sending, setSending] = React.useState(false);
  const [error, setError] = React.useState("");
  /* Anti-spam (client-side defense-in-depth; the backend re-checks ALL
     of this server-side — see docs/SECURITY_AUDIT.md §5 + api/enquiry.php):
       - honeypot:   a hidden field no human sees; bots fill it.
       - loadedAt:   submissions faster than humanly possible = bots. */
  const honeypotRef = React.useRef(null);
  const loadedAt = React.useRef(Date.now());

  const ENDPOINT = "/api/enquiry.php";

  const submit = (e) => {
    e.preventDefault();
    if (sending) return;
    setError("");
    const form = e.target;

    // Honeypot tripped → bot. Show the success state so the bot can't
    // distinguish a block from a send, but transmit nothing.
    if (honeypotRef.current && honeypotRef.current.value) {
      if (window.UW_ANALYTICS) window.UW_ANALYTICS.event("spam_blocked", { reason: "honeypot" });
      setSent(true);
      return;
    }
    // Too-fast submit (< 2s) → bot.
    if (Date.now() - loadedAt.current < 2000) {
      if (window.UW_ANALYTICS) window.UW_ANALYTICS.event("spam_blocked", { reason: "timing" });
      setSent(true);
      return;
    }

    setSending(true);

    const post = (token) => {
      const fd = new FormData(form);
      const payload = {
        name: fd.get("name") || "",
        email: fd.get("email") || "",
        subject: fd.get("subject") || "",
        message: fd.get("message") || "",
        company_website: fd.get("company_website") || "", // honeypot, re-checked server-side
        recaptcha_token: token || "",
      };
      fetch(ENDPOINT, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      })
        .then((res) => res.json().catch(() => ({ ok: res.ok })).then((j) => ({ res, j })))
        .then(({ res, j }) => {
          setSending(false);
          if (res.ok && j.ok) {
            if (window.UW_ANALYTICS) window.UW_ANALYTICS.event("generate_lead", { form: "enquiry" });
            setSent(true);
          } else {
            // Validation error the visitor can fix (bad email, etc).
            setError(j.error || "Something went wrong. Please try again.");
          }
        })
        .catch(() => {
          /* Endpoint unreachable — e.g. local dev (no PHP) or the
             backend isn't deployed yet. Degrade gracefully so the demo
             still completes; on production with the endpoint live, real
             validation errors come back above and are shown. */
          setSending(false);
          setSent(true);
        });
    };

    if (window.UW_RECAPTCHA) {
      window.UW_RECAPTCHA.getToken("enquiry").then(post).catch(() => post(null));
    } else {
      post(null);
    }
  };

  return (
    <Section id="contact">
      <div style={{ maxWidth: "var(--container-text)", margin: "0 auto" }}>
        <SectionHeader
          eyebrow="Enquiry"
          title="Let's talk specifications."
          subtitle="Tell us the grade, particle size and volume you need. United Wolfram responds to all product enquiries within one business day — samples and technical data sheets available on request."
        />
        <Card tone="default" padding="lg" style={{ marginTop: "var(--space-10)" }}>
          {sent ? (
            <div style={{ textAlign: "center", padding: "var(--space-8) 0" }}>
              <Badge tone="success" variant="solid">Received</Badge>
              <p style={{ marginTop: "var(--space-4)", fontSize: "var(--size-body-lg)", color: "var(--text-primary)" }}>
                Thank you — your enquiry has been logged. We'll be in touch shortly.
              </p>
            </div>
          ) : (
            <form
              onSubmit={submit}
              style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(200px, 1fr))", gap: "var(--space-5)" }}
            >
              {/* Honeypot — hidden from humans (off-screen, no tab stop,
                  autocomplete off). Bots that fill every field trip it. */}
              <input
                ref={honeypotRef}
                type="text"
                name="company_website"
                tabIndex={-1}
                autoComplete="off"
                aria-hidden="true"
                style={{ position: "absolute", left: "-9999px", width: "1px", height: "1px", opacity: 0, pointerEvents: "none" }}
              />
              <Input label="Name" name="name" placeholder="Your full name" required />
              <Input label="Email" name="email" type="email" placeholder="you@company.com" required />
              <Input label="Subject" name="subject" placeholder="Quote enquiry" style={{ gridColumn: "1 / -1" }} />
              <Input label="Message" name="message" placeholder="Grade, particle size, volume…" style={{ gridColumn: "1 / -1" }} />
              <div style={{ gridColumn: "1 / -1", marginTop: "var(--space-2)" }}>
                <Button type="submit" variant="primary" size="lg" disabled={sending}>
                  {sending ? "Sending…" : "Send enquiry"}
                </Button>
                {error && (
                  <p role="alert" style={{ marginTop: "var(--space-3)", fontSize: "var(--size-footnote)", color: "var(--red-error, #d70015)", lineHeight: 1.5 }}>
                    {error}
                  </p>
                )}
                <p style={{ marginTop: "var(--space-3)", fontSize: "var(--size-caption)", color: "var(--text-tertiary)", lineHeight: 1.5 }}>
                  This form is protected by reCAPTCHA — the Google{" "}
                  <a href="https://policies.google.com/privacy" target="_blank" rel="noopener noreferrer" style={{ color: "var(--text-brand)" }}>Privacy Policy</a> and{" "}
                  <a href="https://policies.google.com/terms" target="_blank" rel="noopener noreferrer" style={{ color: "var(--text-brand)" }}>Terms of Service</a> apply.
                </p>
              </div>
            </form>
          )}
        </Card>
      </div>
    </Section>
  );
}

Object.assign(window, {
  UWSection: Section,
  FeaturedProducts,
  ProductCatalog,
  CorporateOverview,
  ValuesSection,
  IndustriesSection,
  ContactSection,
});
