/* About and Contact screens. */

function About({ onNav }) {
  const narrow = window.useNarrow();
  const { SectionHeading, Stat, Quote, Eyebrow } = window.PHYOMICAGDesignSystem_ac1e0b;
  const Media = window.Media, Container = window.Container;

  const leaders = [
    ["Hubertus Regtop", "Founding Scientist", "navy"],
    ["Jeff Flood", "Managing Director", "deep", "assets/jeff-flood.png", "contain"],
    ["James McLaren", "Quality & Compliance Manager", "teal", "assets/james-mclaren.png", "contain"],
    ["Joshua Hughes", "Chief Operations Officer", "navy", "assets/joshua-hughes.png", "contain"],
    ["Maryann Thexton", "Chief Financial Officer", "deep", "assets/maryann-thexton.png"],
    ["Van Tran", "Head of New Product Development", "teal", "assets/van-tran.png"],
  ];

  const commercialTargets = [
    "Deliver enhanced profitability, yield and quality to Australian poultry producers with PHYOMIC.AG natural microbiomic products.",
    "Connect with and educate people to buy and appreciate food produced by farmers using natural production systems.",
    "Enable natural farming to be more productive, more profitable and healthier for farmers and consumers alike.",
    "Reconnect families, food and farmers with the health and vitality of natural living systems.",
  ];
  const scienceTargets = [
    "Zero use of genetically modified microorganisms or toxic chemicals in any commercial product.",
    "Every product released with a written, defensible producer triple-ROI: profitability, yield and quality.",
    "Measurable contribution to returning primary food production systems to nature-based, non-toxic foundations.",
    "Reduce on-farm synthetic-chemical dependency through effective, efficient natural biodiversity and quality-rebuilding products and systems.",
    "Open scientific publishing of all major commercial trial results.",
  ];

  const governance = [
    ["Policies & positions", "We take a clear, written stance on the issues that matter to Australian producers, the broader industry and society, including a strict, written policy against the use of genetically modified microorganisms and toxic chemicals in any of our products. If it is not natural, it is not used.", "/about/governance"],
    ["Corporate governance", "We believe proactive, transparent corporate governance is a precondition for long-term value creation in a science-based business.", null],
    ["Group structure", "PHYOMIC.AG is a subsidiary of The Microbiomics Group (TMG). Human, equine and companion-animal applications of the underlying microbiomic science are extended into their relevant markets through TMG.", null],
    ["Procurement & manufacturing", "Australian manufacturing under international and Australian quality systems, with full lot-to-pack traceability.", "/about/procurement"],
  ];

  return (
    <main>
      {/* Navy hero with the brand's microbial-network field in motion. */}
      <section style={{ position: "relative", height: narrow ? 280 : 400, overflow: "hidden", background: "var(--navy)" }}>
        <window.NetworkField spacing={300} intensity={1.15} seed={19} />
        <div style={{ position: "absolute", inset: 0, display: "flex", alignItems: "flex-end", paddingBottom: 52, zIndex: 1 }}>
          <Container>
            <Eyebrow color="var(--teal-light)">About</Eyebrow>
            <h1 style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: "clamp(2.25rem,4vw,3rem)", lineHeight: 1.12, color: "#fff", margin: "12px 0 0", maxWidth: 900, letterSpacing: "-0.02em" }}>
              Partnering with agribusiness to deliver profitable natural production systems.
            </h1>
          </Container>
        </div>
      </section>

      {/* Intro + key stats */}
      <section style={{ paddingBlock: narrow ? 48 : 80 }}>
        <Container>
          <p style={{ fontFamily: "var(--font-body)", fontSize: 18, lineHeight: 1.6, color: "var(--charcoal)", margin: 0, maxWidth: 820 }}>
            An agricultural and livestock research, science and product-development company. Our commercial products serve poultry producers today; soil and crop, red-meat and aquaculture systems are future opportunities in our pipeline.
          </p>
          <div style={{ display: "grid", gridTemplateColumns: narrow ? "repeat(2, 1fr)" : "repeat(4, 1fr)", gap: narrow ? "28px 20px" : 24, marginTop: narrow ? 36 : 56 }}>
            <Stat value="40+" label="Years of founding research & development" />
            <Stat value="2" label="Products in commercial supply: BroilerXP and LayerXP" />
            <Stat value="100%" label="Natural, non-GM, biology in every product" accent="var(--gold)" />
            <Stat value="0" label="Products released without measurable lifts in profit, yield & quality" />
          </div>
          <p style={{ fontFamily: "var(--font-body)", fontSize: 14.5, color: "var(--teal-grey)", marginTop: 28, borderTop: "1px solid var(--border-subtle)", paddingTop: 18 }}>
            Brisbane HQ · Australian manufacturing · International and Australian quality systems · Experimental research and commercial field-trial results, published.
          </p>
        </Container>
      </section>

      {/* Mission statement */}
      <section style={{ background: "var(--navy)", paddingBlock: narrow ? 52 : 88, borderBottom: "2px solid var(--gold)" }}>
        <Container>
          <div style={{ maxWidth: 900 }}>
            <Eyebrow color="var(--teal-light)">Our mission</Eyebrow>
            <p style={{ fontFamily: "var(--font-display)", fontWeight: 500, fontSize: 27, lineHeight: 1.4, color: "#fff", margin: "22px 0 0", letterSpacing: "-0.01em" }}>
              At PHYOMIC.AG, we are leading the transition to microbiomic agriculture. By combining wild-type nature-based microbiology, patented vitamin and bioactive chemistry, naturally fermented extracts and cellular bioenergetics into practical agri-products, we transform the way primary producers raise poultry, without antibiotics as growth promoters, without GM organisms, without toxic chemicals, and without compromising productivity.
            </p>
          </div>
        </Container>
      </section>

      {/* Who we are + the opportunity */}
      <section style={{ paddingBlock: narrow ? 48 : 80 }}>
        <Container>
          <div style={{ display: "grid", gridTemplateColumns: narrow ? "1fr" : "1.35fr 0.65fr", gap: narrow ? 28 : 56, alignItems: "center" }}>
            <div>
              <span style={{ display: "block", height: 2, width: 56, background: "var(--gold)", marginBottom: 26 }} />
              <h2 style={{ fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 30, color: "var(--navy)", margin: 0, letterSpacing: "-0.01em" }}>Science first, from feed to flock.</h2>
              <p style={{ fontFamily: "var(--font-body)", fontSize: 16, lineHeight: 1.65, color: "var(--charcoal)", marginTop: 18 }}>
                We deliver natural production and profit systems to poultry producers, supporting healthier flocks, better meat and eggs, and a healthier country. We work closely with veterinarians, nutritionists and national distribution channel partners to practically and profitably connect research-science breakthroughs to primary producers.
              </p>
              <p style={{ fontFamily: "var(--font-body)", fontSize: 16, lineHeight: 1.65, color: "var(--charcoal)", marginTop: 16 }}>
                There is still vast untapped potential in natural biological systems, in the gut of a day-old chick and the flock it grows into. Leveraging wild-type microbes, post-fermentation metabolites, patented bioactives and vitamin analogues, and humic carriers, we deliver sustainable biosolutions in sync with the mechanisms of nature, not in opposition to them.
              </p>
            </div>
            <Media tone="deep" ratio="3 / 4" label="Layer flock · free-range range" style={{ borderRadius: 24 }}>
              <img src="assets/layer-flock.jpg" alt="Layer flock on the range" style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover" }} />
            </Media>
          </div>
        </Container>
      </section>

      {/* Brand quote */}
      <section style={{ background: "var(--teal-mist)", paddingBlock: narrow ? 48 : 80 }}>
        <Container>
          <Quote cite="The PHYOMIC.AG approach to agriculture">
            We are not in the business of selling additives. We are in the business of restoring the microbiomic systems that farming has always depended on.
          </Quote>
        </Container>
      </section>

      {/* 2030 targets */}
      <section style={{ paddingBlock: narrow ? 48 : 80 }}>
        <Container>
          <SectionHeading eyebrow="2030 targets" title="What we hold ourselves to." level="h2"
            lead="Two sets of commitments: commercial, and scientific & sustainability. Written, measurable, publishable." />
          <div style={{ display: "grid", gridTemplateColumns: narrow ? "1fr" : "1fr 1fr", gap: narrow ? 36 : 48, marginTop: 44, alignItems: "start" }}>
            {[["Commercial targets", commercialTargets], ["Scientific & sustainability targets", scienceTargets]].map(([label, items]) => (
              <div key={label}>
                <Eyebrow>{label}</Eyebrow>
                <div style={{ marginTop: 20, display: "flex", flexDirection: "column" }}>
                  {items.map((t, n) => (
                    <div key={n} style={{ display: "grid", gridTemplateColumns: "auto 1fr", gap: 18, padding: "18px 0", borderTop: "1px solid var(--border-subtle)" }}>
                      <span style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 20, color: "var(--gold)", fontVariantNumeric: "tabular-nums", lineHeight: 1.3 }}>{String(n + 1).padStart(2, "0")}</span>
                      <span style={{ fontFamily: "var(--font-body)", fontSize: 15.5, lineHeight: 1.55, color: "var(--charcoal)" }}>{t}</span>
                    </div>
                  ))}
                </div>
              </div>
            ))}
          </div>
        </Container>
      </section>

      {/* Leadership team */}
      <section style={{ background: "var(--teal-mist)", paddingBlock: narrow ? 48 : 80 }}>
        <Container>
          <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
            <Eyebrow style={{ fontSize: 16 }}>Leadership</Eyebrow>
            <SectionHeading title="Our People" level="h2" />
          </div>
          <div style={{ display: "grid", gridTemplateColumns: narrow ? "repeat(2, 1fr)" : "repeat(6, 1fr)", gap: 20, marginTop: 40 }}>
            {leaders.map(([n, role, tone, photo, fit]) => (
              <div key={n} style={{ display: "flex", flexDirection: "column", gap: 12 }}>
                <Media tone={tone} ratio="1 / 1" style={{ borderRadius: 12, ...(fit === "contain" ? { background: "#ECE8E1" } : null) }}>
                  {photo ? (
                    <img src={photo} alt={n} style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: fit || "cover", objectPosition: "top center" }} />
                  ) : (
                    <span style={{ position: "absolute", inset: 0, display: "flex", alignItems: "center", justifyContent: "center", fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 26, letterSpacing: "0.04em", color: "rgba(255,255,255,0.9)" }}>
                      {n.split(" ").map((w) => w[0]).join("")}
                    </span>
                  )}
                </Media>
                <div>
                  <div style={{ fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 15, color: "var(--navy)" }}>{n}</div>
                  <div style={{ fontFamily: "var(--font-body)", fontSize: 12.5, color: "var(--teal-grey)" }}>{role}</div>
                </div>
              </div>
            ))}
          </div>
        </Container>
      </section>

      {/* History / legacy */}
      <section style={{ paddingBlock: narrow ? 48 : 80 }}>
        <Container>
          <div style={{ display: "grid", gridTemplateColumns: narrow ? "1fr" : "0.85fr 1.15fr", gap: narrow ? 28 : 56, alignItems: "start" }}>
            <div>
              <Eyebrow>Company history</Eyebrow>
              <div style={{ marginTop: 20, display: "flex", alignItems: "baseline", gap: 16 }}>
                <span style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 64, color: "var(--gold)", lineHeight: 1, letterSpacing: "-0.02em" }}>2025</span>
              </div>
              <p style={{ fontFamily: "var(--font-display)", fontWeight: 500, fontSize: 19, lineHeight: 1.45, color: "var(--navy)", margin: "16px 0 0", letterSpacing: "-0.01em" }}>
                PHYOMIC.AG was formally established on the back of decades of research and development in the agricultural and livestock science division of Agricure Scientific Organics, under The Microbiomics Group.
              </p>
            </div>
            <div>
              <span style={{ display: "block", height: 2, width: 56, background: "var(--gold)", marginBottom: 24 }} />
              <h3 style={{ fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 22, color: "var(--navy)", margin: 0 }}>A new company on forty years of founding science.</h3>
              <p style={{ fontFamily: "var(--font-body)", fontSize: 15.5, lineHeight: 1.65, color: "var(--charcoal)", marginTop: 16 }}>
                Our scientific lineage stands on the work of leading minds in microbiology, biochemistry, physiology, organic chemistry, metabolomics, veterinary science, agronomy and food science. From the outset our approach has been to investigate, comprehend and harness the incredibly diverse and effective living systems of nature to optimise soil, plant and animal health, to improve yield, simplify production systems and deliver greater profitability.
              </p>
              <p style={{ fontFamily: "var(--font-body)", fontSize: 15.5, lineHeight: 1.65, color: "var(--charcoal)", marginTop: 14 }}>
                This approach has resulted in multiple novel and patented ingredient manufacturing methods that directly influence and optimise soil, plant and animal microbiomes. Thriving biodiverse microbiomes naturally switch on plant and animal genetics, immune systems and growth systems, working synergistically with nature. For our scientific team, this values-based approach remains the foundational reference for everything we do.
              </p>
            </div>
          </div>
        </Container>
      </section>

      {/* Governance, group structure, procurement */}
      <section style={{ position: "relative", background: "var(--navy)", paddingBlock: narrow ? 48 : 80, borderBottom: "2px solid var(--gold)" }}>
        <Container style={{ position: "relative", zIndex: 1 }}>
          <SectionHeading onDark eyebrow="Governance & structure" title="How we operate." level="h2" />
          <div style={{ display: "grid", gridTemplateColumns: narrow ? "1fr" : "repeat(2, 1fr)", gap: narrow ? 16 : 24, marginTop: 44 }}>
            {governance.map(([h, d, href]) => (
              <div key={h} style={{ display: "flex", flexDirection: "column", gap: 14, background: "rgba(255,255,255,0.05)", border: "1px solid rgba(255,255,255,0.14)", borderRadius: "var(--radius-card)", padding: 28 }}>
                <span style={{ display: "block", height: 2, width: 44, background: "var(--gold)" }} />
                <h3 style={{ fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 20, color: "#fff", margin: 0 }}>{h}</h3>
                <p style={{ fontFamily: "var(--font-body)", fontSize: 14.5, lineHeight: 1.6, color: "rgba(255,255,255,0.72)", margin: 0, flex: 1 }}>{d}</p>
                {href && <a onClick={() => onNav(href === "/about/procurement" ? "article:procurement" : "article:board")} style={{ cursor: "pointer", fontFamily: "var(--font-body)", fontWeight: 600, fontSize: 13.5, color: "var(--teal-light)", letterSpacing: "0.02em", display: "inline-flex", alignItems: "center", gap: 6 }}>Read more <span style={{ fontSize: 15 }}>→</span></a>}
              </div>
            ))}
          </div>
        </Container>
      </section>
    </main>
  );
}

const TURNSTILE_SITE_KEY = "0x4AAAAAAEbRsvutcoyWIlqp";

function Contact({ onNav }) {
  const narrow = window.useNarrow();
  const { SectionHeading, Field, Input, Select, Textarea, Button } = window.PHYOMICAGDesignSystem_ac1e0b;
  const Container = window.Container, Media = window.Media;
  const [sent, setSent] = React.useState(false);
  const [sending, setSending] = React.useState(false);
  const [error, setError] = React.useState("");
  const [values, setValues] = React.useState({ name: "", company: "", email: "", country: "", message: "", website: "" });
  const turnstileRef = React.useRef(null);
  const widgetId = React.useRef(null);

  const set = (key) => (e) => setValues((v) => ({ ...v, [key]: e.target.value }));

  /* The Contact page only exists once React renders it on navigation, well
     after the Turnstile script's own auto-render scan has already run — so
     auto-render never finds this container. Render it explicitly instead,
     polling briefly for the async-loaded turnstile script to be ready. */
  React.useEffect(() => {
    let cancelled = false;
    let tries = 0;
    const tryRender = () => {
      if (cancelled || !turnstileRef.current) return;
      if (window.turnstile && window.turnstile.render) {
        widgetId.current = window.turnstile.render(turnstileRef.current, {
          sitekey: TURNSTILE_SITE_KEY,
          theme: "light",
        });
      } else if (tries++ < 100) {
        setTimeout(tryRender, 100);
      }
    };
    tryRender();
    return () => {
      cancelled = true;
      if (widgetId.current && window.turnstile && window.turnstile.remove) {
        window.turnstile.remove(widgetId.current);
      }
    };
  }, []);

  /* Real submit → POST /api/contact, a Cloudflare Pages Function that
     honeypot-checks, verifies Turnstile, rate-limits, and emails the
     enquiry to the team. */
  const submit = async (e) => {
    e.preventDefault();
    setError("");
    if (!values.email.trim()) {
      setError("Please enter your work email.");
      return;
    }
    const turnstileToken = (window.turnstile && widgetId.current != null)
      ? window.turnstile.getResponse(widgetId.current) : "";
    setSending(true);
    try {
      const res = await fetch("/api/contact", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name: values.name.trim(),
          company: values.company.trim(),
          email: values.email.trim(),
          country: values.country.trim(),
          message: values.message.trim(),
          website: values.website, // honeypot — real visitors never fill this in
          turnstileToken,
        }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) throw new Error(data.error || "Something went wrong. Please try again.");
      setSent(true);
    } catch (err) {
      setError((err && err.message) || "Something went wrong. Please try again.");
      if (window.turnstile && widgetId.current != null) window.turnstile.reset(widgetId.current);
    } finally {
      setSending(false);
    }
  };

  const methods = [
    ["General enquiries", "info@phyomic.ag", ""],
    ["Headquarters", "PHYOMIC.AG · Brisbane, Queensland, Australia", "Australian manufacturing under international and Australian quality systems"],
  ];

  return (
    <main style={{ paddingBlock: narrow ? 48 : 80, minHeight: "60vh", background: "var(--teal-mist)" }}>
      <Container>
        <div style={{ display: "grid", gridTemplateColumns: narrow ? "1fr" : "1fr 1fr", gap: narrow ? 40 : 64, alignItems: "start" }}>
          <div>
            <SectionHeading eyebrow="Contact" title="Talk to the team that built the product." level="h2"
              lead="We are a focused, science-led Australian company." />

            <div style={{ marginTop: 32, display: "flex", flexDirection: "column", gap: 2, background: "#fff", borderRadius: "var(--radius-card)", boxShadow: "var(--shadow-card)", overflow: "hidden" }}>
              {methods.map(([label, value, note], n) => (
                <div key={label} style={{ padding: "18px 24px", borderTop: n ? "1px solid var(--border-subtle)" : "none" }}>
                  <div style={{ fontFamily: "var(--font-body)", fontWeight: 600, fontSize: 12, color: "var(--teal-grey)", textTransform: "uppercase", letterSpacing: "0.1em" }}>{label}</div>
                  <div style={{ fontFamily: "var(--font-body)", fontSize: 16, color: "var(--navy)", marginTop: 4 }}>{value}</div>
                  {note && <div style={{ fontFamily: "var(--font-body)", fontSize: 13.5, lineHeight: 1.5, color: "var(--charcoal)", marginTop: 4 }}>{note}</div>}
                </div>
              ))}
            </div>
          </div>
          <div style={{ background: "#fff", border: "1px solid var(--border-subtle)", borderRadius: "var(--radius-card)", padding: 32, boxShadow: "var(--shadow-card)" }}>
            {sent ? (
              <div style={{ display: "flex", flexDirection: "column", gap: 12, paddingBlock: 24 }}>
                <span style={{ height: 2, width: 48, background: "var(--gold)" }} />
                <h3 style={{ fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 22, color: "var(--navy)", margin: 0 }}>Thanks, we'll be in touch.</h3>
                <p style={{ fontFamily: "var(--font-body)", fontSize: 15, color: "var(--charcoal)", margin: 0 }}>Your enquiry is addressed to info@phyomic.ag. The team aims to respond within one Australian business day.</p>
              </div>
            ) : (
              <form onSubmit={submit} style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
                <Field label="Full name" htmlFor="cn" style={{ gridColumn: "1 / -1" }}><Input id="cn" placeholder="Jane Citizen" value={values.name} onChange={set("name")} autoComplete="name" /></Field>
                <Field label="Organisation" htmlFor="co" style={{ gridColumn: "1 / -1" }}><Input id="co" placeholder="Business name" value={values.company} onChange={set("company")} autoComplete="organization" /></Field>
                <Field label="Work email" htmlFor="ce" required><Input id="ce" type="email" placeholder="jane@property.com.au" value={values.email} onChange={set("email")} autoComplete="email" /></Field>
                <Field label="Country" htmlFor="cc"><Input id="cc" placeholder="Australia" value={values.country} onChange={set("country")} autoComplete="country-name" /></Field>
                <Field label="Enquiry detail" htmlFor="cm" style={{ gridColumn: "1 / -1" }} hint="Protected by honeypot + Cloudflare Turnstile.">
                  <Textarea id="cm" rows={3} placeholder="Tell us about your operation and the outcome you're chasing." value={values.message} onChange={set("message")} />
                </Field>

                {/* Honeypot — hidden from real visitors via off-screen positioning, not display:none (some bots skip display:none fields). */}
                <div aria-hidden="true" style={{ position: "absolute", left: "-9999px", top: "auto", width: 1, height: 1, overflow: "hidden" }}>
                  <label htmlFor="website">Leave this field blank</label>
                  <input id="website" name="website" type="text" tabIndex={-1} autoComplete="off" value={values.website} onChange={set("website")} />
                </div>

                <div style={{ gridColumn: "1 / -1" }} ref={turnstileRef}></div>

                {error && <span style={{ gridColumn: "1 / -1", fontFamily: "var(--font-body)", fontSize: 13.5, color: "#B23B3B" }}>{error}</span>}

                <div style={{ gridColumn: "1 / -1" }}>
                  <Button as="button" type="submit" variant="primary" fullWidth disabled={sending}>{sending ? "Sending…" : "Send enquiry"}</Button>
                  <span style={{ display: "block", fontFamily: "var(--font-body)", fontSize: 12.5, color: "var(--teal-grey)", marginTop: 10 }}>
                    Goes to info@phyomic.ag
                  </span>
                </div>
              </form>
            )}
          </div>
        </div>
      </Container>
    </main>
  );
}

Object.assign(window, { About, Contact });
