// case-study.jsx — Case study: Automated Sales Desk.
// Standalone page. Reuses SoptixLogo / Eyebrow / Button / LangSwitcher from
// components.jsx and the cs.* keys from i18n.jsx. Adding a second case study
// means a new html shell + a new key block; the sections below are generic.
const { useState: useStateC, useEffect: useEffectC, useRef: useRefC } = React;

const CAL_URL = "https://cal.com/soptix-khw4jx/30min";

function prefersReduceC() {
  return !!(window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches);
}

// Fires once when an element scrolls into view. Returns [ref, inView].
function useInViewC(opts) {
  const ref = useRefC(null);
  const [inView, setInView] = useStateC(false);
  useEffectC(() => {
    const el = ref.current;
    if (!el) return;
    if (!("IntersectionObserver" in window)) { setInView(true); return; }
    const obs = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) { setInView(true); obs.unobserve(e.target); }
      });
    }, opts || { threshold: 0.25 });
    obs.observe(el);
    return () => obs.disconnect();
  }, []);
  return [ref, inView];
}

// Same scroll-reveal the homepage uses.
function useScrollRevealC() {
  useEffectC(() => {
    const els = document.querySelectorAll(".reveal");
    if (!("IntersectionObserver" in window)) {
      els.forEach((el) => el.classList.add("in"));
      return;
    }
    const obs = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) { e.target.classList.add("in"); obs.unobserve(e.target); }
      });
    }, { threshold: 0.1, rootMargin: "0px 0px -40px 0px" });
    els.forEach((el) => obs.observe(el));
    return () => obs.disconnect();
  }, []);
}

// ────────────────────────────────────────────────────────────
// Chrome
// ────────────────────────────────────────────────────────────
function CSHeader({ t, lang, setLang }) {
  return (
    <header style={{
      position: "sticky", top: 0, zIndex: 50,
      borderBottom: "1px solid var(--slate)",
      background: "rgba(13,13,13,0.86)",
      backdropFilter: "blur(16px) saturate(140%)",
      WebkitBackdropFilter: "blur(16px) saturate(140%)",
    }}>
      <div className="cs-wrap" style={{
        padding: "18px 40px",
        display: "flex", alignItems: "center", justifyContent: "space-between", gap: 24,
      }}>
        <a href="/" aria-label="Soptix" style={{ display: "flex", alignItems: "center" }}>
          <SoptixLogo height={20} />
        </a>
        <div style={{ display: "flex", alignItems: "center", gap: 20 }}>
          <LangSwitcher lang={lang} setLang={setLang} />
          <span className="hide-sm">
            <Button href={CAL_URL} external>{t("cs.cta.button")}</Button>
          </span>
        </div>
      </div>
    </header>
  );
}

function CSFooter({ t }) {
  return (
    <footer style={{ borderTop: "1px solid var(--slate)" }}>
      <div className="cs-wrap" style={{
        padding: "34px 40px",
        display: "flex", alignItems: "center", justifyContent: "space-between",
        gap: 16, flexWrap: "wrap",
        fontFamily: "'JetBrains Mono', monospace",
        fontSize: 10.5, letterSpacing: "0.14em",
        textTransform: "uppercase", color: "var(--mist-faint)",
      }}>
        <span>{t("footer.copy")}</span>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 8 }}>
          <span style={{ width: 6, height: 6, background: "var(--blue)", transform: "rotate(45deg)", display: "inline-block" }} />
          {t("footer.built")}
        </span>
      </div>
    </footer>
  );
}

// ────────────────────────────────────────────────────────────
// Building blocks
// ────────────────────────────────────────────────────────────

// Grid whose 1px gap over a slate background draws the dividers, so the rules
// stay correct however many columns survive the responsive collapse.
function RuledGrid({ cols, children }) {
  return (
    <div className={"cs-g" + cols} style={{
      gap: 1, background: "var(--slate)", border: "1px solid var(--slate)",
    }}>{children}</div>
  );
}

function CSSection({ eyebrow, title, sub, bg, children }) {
  return (
    <section style={{
      padding: "104px 0",
      borderTop: "1px solid var(--slate)",
      background: bg || "transparent",
    }}>
      <div className="cs-wrap" style={{ padding: "0 40px" }}>
        {(eyebrow || title) && (
          <div style={{ marginBottom: 56, maxWidth: 780 }}>
            {eyebrow && <div style={{ marginBottom: 20 }}><Eyebrow>{eyebrow}</Eyebrow></div>}
            {title && (
              <h2 style={{
                fontFamily: "'Space Grotesk', sans-serif",
                fontWeight: 600,
                fontSize: "clamp(28px, 3.6vw, 46px)",
                lineHeight: 1.08,
                letterSpacing: "-0.02em",
                color: "var(--mist)",
                margin: 0,
                textWrap: "balance",
              }}>{title}</h2>
            )}
            {sub && (
              <p style={{
                fontFamily: "'Space Grotesk', sans-serif",
                fontSize: 16, lineHeight: 1.6, color: "var(--mist-dim)",
                margin: "20px 0 0", maxWidth: 660, textWrap: "pretty",
              }}>{sub}</p>
            )}
          </div>
        )}
        {children}
      </div>
    </section>
  );
}

// Numbered cell used by the situation and architecture grids.
function PointCell({ n, label, h, p }) {
  const [hover, setHover] = useStateC(false);
  return (
    <div
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        background: hover ? "var(--graphite)" : "var(--obsidian)",
        transition: "background 0.2s ease",
        padding: "34px 28px 32px",
        display: "flex", flexDirection: "column",
      }}>
      <div style={{
        fontFamily: "'JetBrains Mono', monospace",
        fontSize: 10.5, letterSpacing: "0.18em",
        color: hover ? "var(--blue)" : "var(--mist-faint)",
        transition: "color 0.2s", marginBottom: 26,
      }}>{label} / {n}</div>
      <h3 style={{
        fontFamily: "'Space Grotesk', sans-serif",
        fontWeight: 600, fontSize: 19, lineHeight: 1.25,
        color: "var(--mist)", margin: "0 0 12px", textWrap: "balance",
      }}>{h}</h3>
      <p style={{
        fontFamily: "'Space Grotesk', sans-serif",
        fontSize: 14.5, lineHeight: 1.62, color: "var(--mist-dim)",
        margin: 0, textWrap: "pretty",
      }}>{p}</p>
    </div>
  );
}

function MonoLabel({ children, style }) {
  return (
    <div style={{
      fontFamily: "'JetBrains Mono', monospace",
      fontSize: 10, letterSpacing: "0.18em", textTransform: "uppercase",
      color: "var(--mist-faint)", ...style,
    }}>{children}</div>
  );
}

// ────────────────────────────────────────────────────────────
// Hero
// ────────────────────────────────────────────────────────────
function CSHero({ t }) {
  const meta = ["client", "problem", "result", "window"];

  return (
    <section style={{ padding: "88px 0 104px", position: "relative", overflow: "hidden" }}>
      <div aria-hidden="true" style={{ position: "absolute", inset: 0, pointerEvents: "none", opacity: 0.55 }}>
        <svg width="100%" height="100%" preserveAspectRatio="none">
          <defs>
            <pattern id="csGrid" x="0" y="0" width="120" height="120" patternUnits="userSpaceOnUse">
              <path d="M0 0 L120 120 M120 0 L0 120" stroke="rgba(79,124,255,0.06)" strokeWidth="1" />
            </pattern>
          </defs>
          <rect width="100%" height="100%" fill="url(#csGrid)" />
        </svg>
      </div>

      <div className="cs-wrap" style={{ padding: "0 40px", position: "relative" }}>
        <Eyebrow>{t("cs.eyebrow")}</Eyebrow>
        <h1 style={{
          fontFamily: "'Space Grotesk', sans-serif",
          fontWeight: 600,
          fontSize: "clamp(42px, 6vw, 80px)",
          lineHeight: 1.02,
          letterSpacing: "-0.03em",
          color: "var(--mist)",
          margin: "26px 0 22px",
          maxWidth: 960,
          textWrap: "balance",
        }}>{t("cs.h1")}</h1>
        <p style={{
          fontFamily: "'Space Grotesk', sans-serif",
          fontWeight: 500,
          fontSize: "clamp(21px, 2.5vw, 30px)",
          lineHeight: 1.2,
          letterSpacing: "-0.015em",
          color: "var(--mist)",
          margin: "0 0 30px",
          maxWidth: 820,
          textWrap: "pretty",
        }}>
          {/* Break between the two sentences, never mid-phrase. */}
          {t("cs.subtitle.a")}<br />
          <span style={{ color: "var(--mist-faint)" }}>{t("cs.subtitle.b")}</span>
        </p>
        <p style={{
          fontFamily: "'Space Grotesk', sans-serif",
          fontSize: 18, lineHeight: 1.6, color: "var(--mist-dim)",
          margin: "0 0 56px", maxWidth: 680, textWrap: "pretty",
        }}>{t("cs.sub")}</p>

        {/* Engagement facts */}
        <dl className="cs-g2" style={{ gap: "26px 48px", margin: "0 0 64px", maxWidth: 940 }}>
          {meta.map((k) => (
            <div key={k} style={{ margin: 0 }}>
              <dt><MonoLabel style={{ marginBottom: 8 }}>{t("cs.meta." + k + ".k")}</MonoLabel></dt>
              <dd style={{
                fontFamily: "'Space Grotesk', sans-serif",
                fontSize: 15, lineHeight: 1.5, color: "var(--mist)", margin: 0,
              }}>{t("cs.meta." + k + ".v")}</dd>
            </div>
          ))}
        </dl>
      </div>

      {/* Headline numbers */}
      <div className="cs-wrap" style={{ padding: "0 40px", position: "relative" }}>
        <RuledGrid cols={4}>
          {[1, 2, 3, 4].map((i) => (
            <div key={i} style={{ background: "var(--obsidian)", padding: "30px 24px 28px" }}>
              <div style={{
                fontFamily: "'Space Grotesk', sans-serif",
                fontWeight: 600, fontSize: "clamp(30px, 3.4vw, 42px)",
                lineHeight: 1, letterSpacing: "-0.025em",
                color: "var(--blue)", marginBottom: 12,
              }}>{t("cs.kpi." + i + ".v")}</div>
              <div style={{
                fontFamily: "'Space Grotesk', sans-serif",
                fontSize: 13.5, lineHeight: 1.45, color: "var(--mist-dim)",
              }}>{t("cs.kpi." + i + ".k")}</div>
            </div>
          ))}
        </RuledGrid>
      </div>
    </section>
  );
}

// ────────────────────────────────────────────────────────────
// Architecture diagram — the four layers, drawn as the copy describes them:
// channels into a normalizing layer, one agent reading a client-owned catalog,
// one write path out to the CRM. Deliberately vendor-free.
// ────────────────────────────────────────────────────────────
const DIAG_CHANNELS = ["cs.diag.wa", "cs.diag.ig", "cs.diag.fb"];

function DiagBox({ lit, accent, className, hKey, subKey, t }) {
  return (
    <div className={"dg-box" + (className ? " " + className : "")} style={{
      borderColor: lit ? (accent ? "var(--blue)" : "rgba(79,124,255,0.4)") : "var(--slate)",
      opacity: lit ? 1 : 0.45,
    }}>
      <div className="dg-h">{t(hKey)}</div>
      <div className="dg-sub">{t(subKey)}</div>
    </div>
  );
}

function DiagArrow({ lit }) {
  return (
    <div className="dg-arrow" aria-hidden="true"
      style={{ color: lit ? "var(--blue)" : "var(--mist-faint)", transition: "color 0.45s ease" }}>↓</div>
  );
}

function ArchitectureDiagram({ t }) {
  const [ref, inView] = useInViewC({ threshold: 0.2 });
  const reduce = prefersReduceC();
  const [step, setStep] = useStateC(reduce ? 4 : 0);

  // Build the stack top down once it scrolls into view.
  useEffectC(() => {
    if (!inView || reduce) return;
    let i = 0;
    const id = setInterval(() => { i += 1; setStep(i); if (i >= 4) clearInterval(id); }, 460);
    return () => clearInterval(id);
  }, [inView, reduce]);

  const on = (s) => step >= s;

  return (
    <div ref={ref} style={{
      position: "relative", border: "1px solid var(--slate)",
      background: "var(--graphite)", overflow: "hidden",
    }}>
      <CSCornerLabels label={t("cs.diag.label")} />
      <div className="dg">
        <div className="dg-row">
          {DIAG_CHANNELS.map((k) => (
            <div key={k} className="dg-box dg-chan" style={{
              borderColor: on(1) ? "rgba(79,124,255,0.4)" : "var(--slate)",
              opacity: on(1) ? 1 : 0.45,
            }}>
              <div className="dg-name">{t(k)}</div>
            </div>
          ))}
        </div>

        <DiagArrow lit={on(2)} />
        <DiagBox lit={on(2)} className="dg-wide" hKey="cs.diag.layer.h" subKey="cs.diag.layer.sub" t={t} />

        <DiagArrow lit={on(3)} />
        <div className="dg-pair">
          <DiagBox lit={on(3)} accent hKey="cs.diag.agent.h" subKey="cs.diag.agent.sub" t={t} />
          <div className="dg-link" aria-hidden="true"
            style={{ color: on(3) ? "var(--blue)" : "var(--mist-faint)", transition: "color 0.45s ease" }}>
            <span>↔</span>
          </div>
          <DiagBox lit={on(3)} hKey="cs.diag.catalog.h" subKey="cs.diag.catalog.sub" t={t} />
        </div>

        <DiagArrow lit={on(4)} />
        <DiagBox lit={on(4)} className="dg-crm" hKey="cs.diag.crm.h" subKey="cs.diag.crm.sub" t={t} />

        <p className="dg-cap">{t("cs.diag.caption")}</p>
      </div>
    </div>
  );
}

function CSCornerLabels({ label }) {
  return (
    <React.Fragment>
      <div style={{
        position: "absolute", top: 0, left: 0, right: 0,
        display: "flex", justifyContent: "space-between",
        padding: "12px 14px",
        fontFamily: "'JetBrains Mono', monospace",
        fontSize: 10, letterSpacing: "0.18em",
        color: "var(--mist-faint)", zIndex: 2, pointerEvents: "none",
      }}>
        <span>{label}</span>
        <span style={{ color: "var(--blue)" }}>●</span>
      </div>
      {["tl", "tr", "bl", "br"].map((pos) => (
        <div key={pos} style={{
          position: "absolute", width: 10, height: 10,
          borderColor: "var(--blue)", borderStyle: "solid", borderWidth: 0,
          zIndex: 2, pointerEvents: "none",
          ...(pos === "tl" && { top: 6, left: 6, borderTopWidth: 1, borderLeftWidth: 1 }),
          ...(pos === "tr" && { top: 6, right: 6, borderTopWidth: 1, borderRightWidth: 1 }),
          ...(pos === "bl" && { bottom: 6, left: 6, borderBottomWidth: 1, borderLeftWidth: 1 }),
          ...(pos === "br" && { bottom: 6, right: 6, borderBottomWidth: 1, borderRightWidth: 1 }),
        }} />
      ))}
    </React.Fragment>
  );
}

// ────────────────────────────────────────────────────────────
// Results
// ────────────────────────────────────────────────────────────
function MetricTable({ t }) {
  return (
    <div style={{ border: "1px solid var(--slate)" }}>
      {[1, 2, 3, 4, 5].map((i, idx) => (
        <div key={i} style={{
          display: "flex", justifyContent: "space-between", alignItems: "baseline", gap: 24,
          padding: "19px 26px",
          borderTop: idx === 0 ? "none" : "1px solid var(--slate)",
        }}>
          <span style={{
            fontFamily: "'Space Grotesk', sans-serif",
            fontSize: 15.5, lineHeight: 1.4, color: "var(--mist-dim)",
          }}>{t("cs.table." + i + ".k")}</span>
          <span style={{
            fontFamily: "'JetBrains Mono', monospace",
            fontSize: 16, color: "var(--mist)", letterSpacing: "0.02em", whiteSpace: "nowrap",
          }}>{t("cs.table." + i + ".v")}</span>
        </div>
      ))}
    </div>
  );
}

function DerivedCell({ v, k, p }) {
  return (
    <div style={{ background: "var(--obsidian)", padding: "32px 28px" }}>
      <div style={{
        fontFamily: "'Space Grotesk', sans-serif",
        fontWeight: 600, fontSize: 34, lineHeight: 1,
        letterSpacing: "-0.025em", color: "var(--mist)", marginBottom: 10,
      }}>{v}</div>
      <div style={{
        fontFamily: "'JetBrains Mono', monospace",
        fontSize: 10, letterSpacing: "0.14em", textTransform: "uppercase",
        color: "var(--blue)", marginBottom: 16, lineHeight: 1.5,
      }}>{k}</div>
      <p style={{
        fontFamily: "'Space Grotesk', sans-serif",
        fontSize: 14, lineHeight: 1.6, color: "var(--mist-dim)", margin: 0, textWrap: "pretty",
      }}>{p}</p>
    </div>
  );
}

// ────────────────────────────────────────────────────────────
// Page
// ────────────────────────────────────────────────────────────
function CaseStudyApp() {
  const { lang, setLang, t } = useLang();
  useScrollRevealC();

  return (
    <React.Fragment>
      <CSHeader t={t} lang={lang} setLang={setLang} />
      <main>
        <CSHero t={t} />

        <div className="reveal">
          <CSSection eyebrow={t("cs.problem.eyebrow")} title={t("cs.problem.title")} sub={t("cs.problem.sub")}>
            <RuledGrid cols={3}>
              {[1, 2, 3].map((i) => (
                <PointCell key={i} n={"0" + i} label={t("cs.problem.eyebrow").toUpperCase()}
                  h={t("cs.problem." + i + ".h")} p={t("cs.problem." + i + ".p")} />
              ))}
            </RuledGrid>
          </CSSection>
        </div>

        <div className="reveal">
          <CSSection bg="var(--graphite)" eyebrow={t("cs.build.eyebrow")}
            title={t("cs.build.title")} sub={t("cs.build.sub")}>
            <ArchitectureDiagram t={t} />
            <div style={{ marginTop: 40 }}>
              <RuledGrid cols={2}>
                {[1, 2, 3, 4].map((i) => (
                  <PointCell key={i} n={"0" + i} label="LAYER"
                    h={t("cs.build." + i + ".h")} p={t("cs.build." + i + ".p")} />
                ))}
              </RuledGrid>
            </div>
          </CSSection>
        </div>

        <div className="reveal">
          <CSSection eyebrow={t("cs.results.eyebrow")} title={t("cs.results.title")} sub={t("cs.results.sub")}>
            <MetricTable t={t} />
            <MonoLabel style={{ margin: "56px 0 20px" }}>{t("cs.derived.h")}</MonoLabel>
            <RuledGrid cols={2}>
              {[1, 2, 3, 4].map((i) => (
                <DerivedCell key={i} v={t("cs.derived." + i + ".v")}
                  k={t("cs.derived." + i + ".k")} p={t("cs.derived." + i + ".p")} />
              ))}
            </RuledGrid>
          </CSSection>
        </div>

        <div className="reveal">
          <section style={{ padding: "104px 0", borderTop: "1px solid var(--slate)", textAlign: "center" }}>
            <div className="cs-wrap" style={{ padding: "0 40px" }}>
              <div style={{ display: "flex", justifyContent: "center", marginBottom: 26 }}>
                <Eyebrow>{t("cs.cta.eyebrow")}</Eyebrow>
              </div>
              <h2 style={{
                fontFamily: "'Space Grotesk', sans-serif",
                fontWeight: 600, fontSize: "clamp(34px, 4.8vw, 60px)",
                lineHeight: 1.04, letterSpacing: "-0.02em",
                color: "var(--mist)", margin: "0 0 24px", textWrap: "balance",
              }}>
                {t("cs.cta.h.a")}
                <span style={{ color: "var(--blue)" }}>{t("cs.cta.h.b")}</span>
                {t("cs.cta.h.c")}
              </h2>
              <p style={{
                fontFamily: "'Space Grotesk', sans-serif",
                fontSize: 17, lineHeight: 1.6, color: "var(--mist-dim)",
                margin: "0 auto 40px", maxWidth: 580, textWrap: "pretty",
              }}>{t("cs.cta.p")}</p>
              <Button href={CAL_URL} size="lg" arrow external>{t("cs.cta.button")}</Button>
            </div>
          </section>
        </div>
      </main>
      <CSFooter t={t} />
    </React.Fragment>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<CaseStudyApp />);
