/* Shared helpers for the PHYOMIC.AG website UI kit.
   Photographic placeholders stand in for the editorial photography the
   brand mandates (Queensland paddock, lab, layer shed, vineyard,
   rhizosphere macro). Replace `Media` content with real imagery in prod. */

const DS = window.PHYOMICAGDesignSystem_ac1e0b;

/* A photographic placeholder: a quiet navy field with a faint organic
   texture + a corner caption, so layouts read as full-bleed imagery.
   `play` overlays a Novonesis-style play button for video stand-ins. */
function Media({ label, ratio, tone = "navy", play, children, style }) {
  const tones = {
    navy: "radial-gradient(120% 120% at 20% 10%, #0c3252 0%, #082540 55%, #051a2e 100%)",
    teal: "radial-gradient(120% 120% at 80% 0%, #2AAE74 0%, #1B8B70 45%, #0d5a48 100%)",
    mist: "linear-gradient(160deg, #E8F4EE 0%, #d4ecdf 100%)",
    deep: "radial-gradient(140% 140% at 70% 20%, #15543f 0%, #0a2e36 60%, #082540 100%)",
  };
  const dark = tone !== "mist";
  // Honour the global corner-radius tweak on rounded (non-full-bleed) media.
  const tw = (typeof window !== "undefined" && window.__tw) || {};
  const radiusOverride = (style && style.borderRadius != null && tw.mediaRadius != null)
    ? { borderRadius: tw.mediaRadius } : null;
  return (
    <div style={{
      position: "relative", overflow: "hidden",
      aspectRatio: ratio || undefined, height: ratio ? undefined : "100%",
      width: "100%", background: tones[tone] || tones.navy,
      ...style,
      ...radiusOverride,
    }}
      role={!children && label ? "img" : undefined}
      aria-label={!children && label ? label : undefined}>
      {play && (
        <span style={{ position: "absolute", inset: 0, display: "flex", alignItems: "center", justifyContent: "center" }}>
          <span style={{ width: 76, height: 76, borderRadius: "50%", background: "rgba(255,255,255,0.92)",
            display: "flex", alignItems: "center", justifyContent: "center", boxShadow: "0 8px 30px rgba(8,37,64,0.3)" }}>
            <span style={{ width: 0, height: 0, borderTop: "12px solid transparent", borderBottom: "12px solid transparent",
              borderLeft: "20px solid var(--navy)", marginLeft: 5 }} />
          </span>
        </span>
      )}
      {children}
    </div>
  );
}

/* Slow photographic crossfade: cycles through `images` with a long
   hold and a gentle dissolve. Sits inside a `Media` (object-fit: cover,
   absolutely filling the frame). Respects prefers-reduced-motion. */
function Crossfade({ images = [], alt = "", hold = 4200, fade = 2600, position = "center" }) {
  const [i, setI] = React.useState(0);
  const reduce = typeof window !== "undefined" && window.matchMedia
    && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
  React.useEffect(() => {
    if (reduce || images.length < 2) return;
    const id = setInterval(() => setI((p) => (p + 1) % images.length), hold + fade);
    return () => clearInterval(id);
  }, [images.length, hold, fade, reduce]);
  return (
    <span style={{ position: "absolute", inset: 0, display: "block" }} aria-label={alt} role="img">
      {images.map((src, n) => (
        <img key={src} src={src} alt=""
          style={{
            position: "absolute", inset: 0, width: "100%", height: "100%",
            objectFit: "cover", objectPosition: position,
            opacity: n === i ? 1 : 0,
            transition: reduce ? "none" : `opacity ${fade}ms ease-in-out`,
          }} />
      ))}
    </span>
  );
}

/* Viewport hook: true on phone-width viewports. Single breakpoint —
   the site is a two-state layout (desktop grid / phone stack), not a
   fluid multi-breakpoint system. */
function useNarrow(bp = 860) {
  const q = `(max-width: ${bp}px)`;
  const [narrow, setNarrow] = React.useState(
    () => typeof window !== "undefined" && window.matchMedia ? window.matchMedia(q).matches : false);
  React.useEffect(() => {
    if (!window.matchMedia) return;
    const mq = window.matchMedia(q);
    const on = (e) => setNarrow(e.matches);
    mq.addEventListener("change", on);
    setNarrow(mq.matches);
    return () => mq.removeEventListener("change", on);
  }, [q]);
  return narrow;
}

/* Centered content column */
function Container({ children, style }) {
  const narrow = useNarrow();
  return <div style={{ width: "100%", maxWidth: 1200, marginInline: "auto", paddingInline: narrow ? 20 : 32, ...style }}>{children}</div>;
}

/* Novonesis-style "Learn more →" text link */
function LearnMore({ children = "Learn more", onClick, dark }) {
  return (
    <a onClick={onClick} style={{
      display: "inline-flex", alignItems: "center", gap: 8, cursor: "pointer",
      fontFamily: "var(--font-body)", fontWeight: 600, fontSize: 15,
      color: dark ? "var(--teal-light)" : "var(--teal-deep)",
      paddingBottom: 3, borderBottom: `2px solid ${dark ? "rgba(127,209,171,0.5)" : "rgba(27,139,112,0.35)"}`,
    }}>{children}<span style={{ fontSize: 16 }}>→</span></a>
  );
}

/* Field Note newsletter module: shared across About, Solutions and
   Sustainability. Copy per Supporting Content v2. Cookie-gated in prod. */
function FieldNote({ onNav }) {
  const { Eyebrow, Button, Input } = window.PHYOMICAGDesignSystem_ac1e0b;
  const narrow = useNarrow();
  return (
    <section style={{ background: "var(--teal-mist)", paddingBlock: narrow ? 48 : 80 }}>
      <Container>
        <div style={{ display: "grid", gridTemplateColumns: narrow ? "1fr" : "1fr 1fr", gap: narrow ? 28 : 56, alignItems: "center" }}>
          <div>
            <Eyebrow>The PHYOMIC.AG Field Note</Eyebrow>
            <h2 style={{ fontFamily: "var(--font-display)", fontWeight: 600, fontSize: "clamp(1.75rem,3vw,2.25rem)", lineHeight: 1.2, color: "var(--navy)", margin: "16px 0 0", letterSpacing: "-0.01em" }}>
              Microbiomic agriculture, made readable, straight to your inbox.
            </h2>
          </div>
          <div>
            <p style={{ fontFamily: "var(--font-body)", fontSize: 15.5, lineHeight: 1.65, color: "var(--charcoal)", margin: 0 }}>
              Our monthly briefing for producers, veterinarians, agronomists, distributors and industry-body executives. We break down the science of microbiomic agriculture into clear, on-farm-actionable writing, with the trial data, the dose-response numbers and the regulatory context behind each story. No filler, no jargon, no marketing language.
            </p>
            <div style={{ display: "flex", gap: 12, marginTop: 24, flexWrap: "wrap" }}>
              <div style={{ flex: "1 1 240px" }}><Input type="email" placeholder="you@property.com.au" /></div>
              <Button variant="primary" onClick={() => onNav && onNav("contact")}>Subscribe to the Field Note</Button>
            </div>
            <span style={{ display: "block", fontFamily: "var(--font-body)", fontSize: 12.5, color: "var(--teal-grey)", marginTop: 12 }}>Cookie-gated · GDPR / APP compliant · unsubscribe anytime.</span>
          </div>
        </div>
      </Container>
    </section>
  );
}

Object.assign(window, { DS, Media, Crossfade, Container, LearnMore, FieldNote, useNarrow });
