/* MCA, Case Studies CMS
 *
 * - CaseStudiesPage  → /case-studies (index)
 * - CaseStudyPage    → /case-studies/<slug> (detail)
 *
 * Results-led, no dates. Reuses the dark editorial theme (body.blog-dark)
 * and adds a richer, more modern card system (.csx-*) than a standard list.
 */

const {
  useState: useStateC,
  useMemo: useMemoC,
  useEffect: useEffectC,
} = React;

/* ============================================================
 * HERO BACKGROUND, drifting glass crystals (Three.js / WebGL)
 * Faceted refractive forms (gem, cube, ring) rotate slowly with
 * teal refraction + glowing edges. Soft parallax on mouse.
 * Falls back to the CSS beams if WebGL/THREE is unavailable.
 * ============================================================ */
function CaseField() {
  const mountRef = React.useRef(null);

  React.useEffect(() => {
    const THREE = window.THREE;
    const mount = mountRef.current;
    if (!THREE || !mount) return;

    const reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    let W = mount.clientWidth || 1;
    let H = mount.clientHeight || 1;

    let renderer;
    try {
      renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true, powerPreference: "high-performance", preserveDrawingBuffer: true });
    } catch (e) { return; }
    renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 1.6));
    renderer.setSize(W, H);
    renderer.outputEncoding = THREE.sRGBEncoding;
    renderer.toneMapping = THREE.ACESFilmicToneMapping;
    renderer.toneMappingExposure = 1.15;
    mount.appendChild(renderer.domElement);
    renderer.domElement.style.width = "100%";
    renderer.domElement.style.height = "100%";
    renderer.domElement.style.display = "block";

    const scene = new THREE.Scene();
    const camera = new THREE.PerspectiveCamera(42, W / H, 0.1, 100);
    camera.position.set(0, 0, 11);

    // --- procedural environment (dark teal → ink) for reflections/refraction
    const envCanvas = document.createElement("canvas");
    envCanvas.width = 32; envCanvas.height = 256;
    const ectx = envCanvas.getContext("2d");
    const grad = ectx.createLinearGradient(0, 0, 0, 256);
    grad.addColorStop(0.0, "#0e4a4f");
    grad.addColorStop(0.35, "#0d2c38");
    grad.addColorStop(0.7, "#08151d");
    grad.addColorStop(1.0, "#02060a");
    ectx.fillStyle = grad; ectx.fillRect(0, 0, 32, 256);
    // a soft bright band = key highlight on the glass
    const hi = ectx.createRadialGradient(16, 70, 0, 16, 70, 60);
    hi.addColorStop(0, "rgba(140,240,235,0.9)");
    hi.addColorStop(1, "rgba(140,240,235,0)");
    ectx.fillStyle = hi; ectx.fillRect(0, 0, 32, 256);
    const envTex = new THREE.CanvasTexture(envCanvas);
    envTex.mapping = THREE.EquirectangularReflectionMapping;
    const pmrem = new THREE.PMREMGenerator(renderer);
    const envRT = pmrem.fromEquirectangular(envTex);
    scene.environment = envRT.texture;

    // --- glass material
    function makeGlass() {
      return new THREE.MeshPhysicalMaterial({
        color: new THREE.Color("#9fe4e0"),
        metalness: 0,
        roughness: 0.06,
        transmission: 1,
        thickness: 1.6,
        ior: 1.45,
        clearcoat: 1,
        clearcoatRoughness: 0.12,
        envMapIntensity: 1.5,
        attenuationColor: new THREE.Color("#1d7c7e"),
        attenuationDistance: 3.2,
        transparent: true,
      });
    }
    function edgeLines(geo, opacity) {
      return new THREE.LineSegments(
        new THREE.EdgesGeometry(geo, 18),
        new THREE.LineBasicMaterial({
          color: 0x6ff0e8, transparent: true, opacity: opacity,
          blending: THREE.AdditiveBlending, depthWrite: false,
        })
      );
    }

    const shapes = [];
    function addShape(geo, pos, scale, rotSpeed, edgeOp) {
      const mesh = new THREE.Mesh(geo, makeGlass());
      mesh.position.set(pos[0], pos[1], pos[2]);
      mesh.scale.setScalar(scale);
      mesh.add(edgeLines(geo, edgeOp));
      scene.add(mesh);
      shapes.push({ mesh, rotSpeed, basePos: pos.slice() });
    }

    // Gem (faceted icosahedron), upper right
    addShape(new THREE.IcosahedronGeometry(2.0, 1), [4.4, 1.6, -1], 1.05,
      { x: 0.0009, y: 0.0016, z: 0.0004 }, 0.46);
    // Crystal cube, lower left
    addShape(new THREE.BoxGeometry(2.4, 2.4, 2.4), [-4.8, -2.0, -0.5], 0.95,
      { x: 0.0014, y: 0.0011, z: 0.0006 }, 0.42);
    // Octahedron accent, far upper-left, small + dim
    addShape(new THREE.OctahedronGeometry(1.3, 0), [-4.2, 2.6, -3], 0.9,
      { x: 0.0008, y: 0.0018, z: 0.0 }, 0.32);

    // --- soft dust (bokeh) points
    const dustGeo = new THREE.BufferGeometry();
    const COUNT = 90;
    const arr = new Float32Array(COUNT * 3);
    for (let i = 0; i < COUNT; i++) {
      arr[i * 3] = (Math.random() - 0.5) * 22;
      arr[i * 3 + 1] = (Math.random() - 0.5) * 13;
      arr[i * 3 + 2] = (Math.random() - 0.5) * 6 - 2;
    }
    dustGeo.setAttribute("position", new THREE.BufferAttribute(arr, 3));
    const dustTex = (() => {
      const c = document.createElement("canvas"); c.width = c.height = 64;
      const x = c.getContext("2d");
      const g = x.createRadialGradient(32, 32, 0, 32, 32, 32);
      g.addColorStop(0, "rgba(180,245,240,0.9)");
      g.addColorStop(1, "rgba(180,245,240,0)");
      x.fillStyle = g; x.fillRect(0, 0, 64, 64);
      return new THREE.CanvasTexture(c);
    })();
    const dust = new THREE.Points(dustGeo, new THREE.PointsMaterial({
      size: 0.16, map: dustTex, transparent: true, opacity: 0.5,
      depthWrite: false, blending: THREE.AdditiveBlending,
    }));
    scene.add(dust);

    // --- lights
    scene.add(new THREE.AmbientLight(0x14313a, 1.0));
    const key = new THREE.DirectionalLight(0xa8fff8, 2.2);
    key.position.set(-6, 8, 6); scene.add(key);
    const teal = new THREE.PointLight(0x00d5cf, 60, 40); teal.position.set(6, -2, 5); scene.add(teal);
    const rim = new THREE.PointLight(0x2a6fdb, 30, 40); rim.position.set(-8, -4, 3); scene.add(rim);

    const parallax = { x: 0, y: 0, tx: 0, ty: 0 };
    function onMove(e) {
      parallax.tx = (e.clientX / window.innerWidth - 0.5) * 1.1;
      parallax.ty = (e.clientY / window.innerHeight - 0.5) * 0.7;
    }

    let raf = 0, t = 0;
    function frame() {
      try {
      t += 0.016;
      parallax.x += (parallax.tx - parallax.x) * 0.04;
      parallax.y += (parallax.ty - parallax.y) * 0.04;
      for (const s of shapes) {
        s.mesh.rotation.x += s.rotSpeed.x;
        s.mesh.rotation.y += s.rotSpeed.y;
        s.mesh.rotation.z += s.rotSpeed.z;
        // gentle bob
        s.mesh.position.y = s.basePos[1] + Math.sin(t * 0.4 + s.basePos[0]) * 0.22;
      }
      dust.rotation.y += 0.0004;
      camera.position.x += (parallax.x - camera.position.x) * 0.05;
      camera.position.y += (-parallax.y - camera.position.y) * 0.05;
      camera.lookAt(0, 0, 0);
      renderer.render(scene, camera);
      raf = requestAnimationFrame(frame);
      } catch (err) { cancelAnimationFrame(raf); }
    }

    function resize() {
      W = mount.clientWidth || 1; H = mount.clientHeight || 1;
      renderer.setSize(W, H);
      camera.aspect = W / H;
      camera.updateProjectionMatrix();
    }
    window.addEventListener("resize", resize);

    // initial synchronous render so first paint isn't blank even before rAF
    function renderOnce() {
      for (const s of shapes) {
        s.mesh.rotation.x += s.rotSpeed.x * 8;
        s.mesh.rotation.y += s.rotSpeed.y * 8;
      }
      renderer.render(scene, camera);
    }

    if (reduce) {
      renderer.render(scene, camera);
    } else {
      renderOnce();
      window.addEventListener("mousemove", onMove);
      raf = requestAnimationFrame(frame);
    }

    return () => {
      cancelAnimationFrame(raf);
      window.removeEventListener("resize", resize);
      window.removeEventListener("mousemove", onMove);
      envRT.dispose(); pmrem.dispose(); envTex.dispose();
      scene.traverse((o) => {
        if (o.geometry) o.geometry.dispose();
        if (o.material) {
          if (Array.isArray(o.material)) o.material.forEach((m) => m.dispose());
          else o.material.dispose();
        }
      });
      renderer.dispose();
      if (renderer.domElement && renderer.domElement.parentNode) {
        renderer.domElement.parentNode.removeChild(renderer.domElement);
      }
    };
  }, []);

  return <div ref={mountRef} className="csx-field" aria-hidden="true"></div>;
}

/* ============================================================
 * INDEX  (/case-studies)
 * ============================================================ */
function CaseStudiesPage({ navigate }) {
  const cases = window.CASE_STUDIES || [];
  const sectors = window.CASE_SECTORS || ["All"];
  const featured = cases.find((c) => c.featured) || cases[0];

  const [filter, setFilter] = useStateC("All");

  const rest = useMemoC(
    () =>
      cases
        .filter((c) => c !== featured)
        .filter((c) => filter === "All" || c.sector === filter),
    [cases, featured, filter]
  );

  const go = (slug) => navigate("/case-studies/" + slug);

  return (
    <React.Fragment>
      {/* Hero, centered, animated trajectory field */}
      <section className="csx-hero">
        <div className="csx-hero__bg" aria-hidden="true">
          <div className="csx-hero__grid"></div>
          <div className="csx-hero__beam csx-hero__beam--1"></div>
          <div className="csx-hero__beam csx-hero__beam--2"></div>
          <div className="csx-hero__noise"></div>
          <div className="csx-hero__vignette"></div>
        </div>
        <div className="csx-hero__inner">
          <div className="csx-hero__eyebrow">
            <span className="csx-hero__eyebrow-dot"></span>
            CASE STUDIES
          </div>
          <h1 className="csx-hero__title">
            <span className="csx-hero__line">Critical Moments,</span>
            <span className="csx-hero__line csx-hero__title-accent">Turned Into Lasting Growth.</span>
          </h1>
          <p className="csx-hero__sub">
            How MCA stepped into pivotal moments for leading protocols, across launches,
            token generation, interoperability, and institutional capital, and turned them
            into sustainable, compounding growth.
          </p>
          <div className="csx-hero__stats">
            <div className="csx-hero__stat">
              <span className="csx-hero__stat-num">80+</span>
              <span className="csx-hero__stat-label">Successful client launches</span>
            </div>
            <div className="csx-hero__stat-div" aria-hidden="true"></div>
            <div className="csx-hero__stat">
              <span className="csx-hero__stat-num">$50B+</span>
              <span className="csx-hero__stat-label">Peak enterprise value created for clients</span>
            </div>
            <div className="csx-hero__stat-div" aria-hidden="true"></div>
            <div className="csx-hero__stat">
              <span className="csx-hero__stat-num">10M+</span>
              <span className="csx-hero__stat-label">Client social media growth</span>
            </div>
          </div>
        </div>
        <div className="csx-hero__fade" aria-hidden="true"></div>
      </section>

      {/* Featured */}
      {featured && (
        <section className="section section--tight">
          <div className="container">
            <div className="section-num" style={{ marginBottom: 20 }}>FEATURED CASE STUDY</div>
            <article
              className="csx-feature"
              style={{ "--accent": featured.accent }}
              onClick={() => go(featured.slug)}
            >
              <div className="csx-feature__media">
                <img src={featured.logo} alt={featured.client} loading="lazy" />
                <div className="csx-feature__media-glow" aria-hidden="true"></div>
              </div>
              <div className="csx-feature__body">
                <div className="csx-feature__tag">{featured.chain}</div>
                <h2 className="csx-feature__title">{featured.title}</h2>
                <p className="csx-feature__summary">{featured.summary}</p>
                <span className="csx-feature__cta">
                  Read case study <ArrowUpRight />
                </span>
              </div>
            </article>
          </div>
        </section>
      )}

      {/* Grid */}
      <section className="section csx-grid-section">
        <div className="container">
          {rest.length === 0 ? (
            <div className="blog-empty">
              <div className="blog-empty__title">Nothing in this category yet.</div>
              <div className="blog-empty__sub">Try a different sector.</div>
            </div>
          ) : (
            <div className="csx-grid">
              {rest.map((c) => (
                <article
                  key={c.slug}
                  className="csx-card"
                  style={{ "--accent": c.accent }}
                  onClick={() => go(c.slug)}
                >
                  <div className="csx-card__media">
                    <img src={c.logo} alt={c.client} loading="lazy" />
                    <span className="csx-card__sector">{c.sector}</span>
                  </div>
                  <div className="csx-card__body">
                    <h3 className="csx-card__title">{c.title}</h3>
                    <p className="csx-card__summary">{c.summary}</p>
                    <div className="csx-card__foot">
                      <span className="csx-card__cta">
                        Read case <ArrowUpRight size={12} />
                      </span>
                    </div>
                  </div>
                </article>
              ))}
            </div>
          )}
        </div>
      </section>

      <FinalCTA navigate={navigate} />
    </React.Fragment>
  );
}

/* ============================================================
 * DETAIL  (/case-studies/<slug>)
 * ============================================================ */
function CaseStudyPage({ slug, navigate }) {
  const cases = window.CASE_STUDIES || [];
  const cs = cases.find((c) => c.slug === slug);

  useEffectC(() => {
    document.title = cs ? `${cs.client} · Case Study · MCA` : "Case study not found · MCA";
    return () => { document.title = "MCA · MultiChain Advisors"; };
  }, [cs]);

  if (!cs) {
    return (
      <section className="page-hero">
        <div className="page-hero__inner" style={{ textAlign: "center" }}>
          <div className="page-hero__crumb">CASE STUDY · 404</div>
          <h1 className="page-hero__title" style={{ margin: "0 auto" }}>Case study not found.</h1>
          <p className="page-hero__sub" style={{ margin: "24px auto 0" }}>
            The case study you're looking for doesn't exist or has moved.
          </p>
          <div style={{ marginTop: 32 }}>
            <Button variant="primary" onClick={() => navigate("/case-studies")} withArrow>
              Back to case studies
            </Button>
          </div>
        </div>
      </section>
    );
  }

  const related = cases.filter((c) => c.slug !== cs.slug).slice(0, 3);

  return (
    <article className="art2 csx-detail" style={{ "--accent": cs.accent }}>
      {/* Terminal-style breadcrumb */}
      <div className="art2-crumb">
        <div className="container">
          <div className="art2-crumb__row">
            <span className="art2-crumb__back" onClick={() => navigate("/case-studies")}>
              <i className="art2-crumb__back-arrow" aria-hidden="true"></i>
              <span>../case-studies</span>
            </span>
            <span className="art2-crumb__sep">/</span>
            <span className="art2-crumb__path">./{cs.slug}</span>
          </div>
        </div>
      </div>

      {/* Header */}
      <header className="art2-head">
        <div className="container">
          <div className="art2-head__inner">
            <h1 className="art2-head__title">{cs.title}</h1>
            <p className="art2-head__lede">{cs.summary}</p>
            <div className="csx-chips" style={{ marginTop: 28 }}>
              {cs.services.map((s) => (
                <span key={s} className="csx-chip">{s}</span>
              ))}
            </div>
          </div>
        </div>
      </header>

      {/* Hero image */}
      <figure className="art2-hero-img csx-detail__hero">
        <div className="art2-hero-img__wrap">
          <img src={cs.logo} alt={cs.client} />
        </div>
      </figure>

      {/* Body */}
      <section className="art2-body-section">
        <div className="art2-body">
          {cs.body.map((b, i) => (
            <React.Fragment key={i}>
              <h2>{b.heading}</h2>
              <p>{b.text}</p>
            </React.Fragment>
          ))}

          {cs.quote && (
            <blockquote className="csx-quote">
              <p>{cs.quote.text}</p>
            </blockquote>
          )}

          {/* Quiet CTA */}
          <div className="art2-cta">
            <div className="art2-cta__copy">
              <div className="art2-cta__eyebrow">WORK WITH MCA</div>
              <h3 className="art2-cta__title">Ready for your moment?</h3>
              <p className="art2-cta__sub">
                Book a free 30-minute call. We'll map your goals to the right move across
                growth, capital, and AI, the same playbook behind the work above.
              </p>
            </div>
            <button className="art2-cta__btn" onClick={() => window.open("https://form.typeform.com/to/j6nKhXw5", "_blank", "noopener")}>
              Schedule a call
              <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
                <path d="M3 11L11 3M11 3H5M11 3V9" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            </button>
          </div>
        </div>
      </section>

      {/* Related */}
      {related.length > 0 && (
        <section className="art2-related">
          <div className="art2-related__head">
            <div className="art2-related__eyebrow">MORE CASE STUDIES</div>
            <h2 className="art2-related__title">Other critical moments.</h2>
          </div>
          <div className="csx-rel-grid">
            {related.map((c) => (
              <article
                key={c.slug}
                className="csx-card"
                style={{ "--accent": c.accent }}
                onClick={() => navigate("/case-studies/" + c.slug)}
              >
                <div className="csx-card__media">
                  <img src={c.logo} alt={c.client} loading="lazy" />
                  <span className="csx-card__sector">{c.sector}</span>
                </div>
                <div className="csx-card__body">
                  <h3 className="csx-card__title">{c.title}</h3>
                  <span className="csx-card__cta">
                    Read case <ArrowUpRight size={12} />
                  </span>
                </div>
              </article>
            ))}
          </div>
          <div className="art2-related__more">
            <span className="art2-related__more-link" onClick={() => navigate("/case-studies")}>
              View all case studies
              <svg width="12" height="12" viewBox="0 0 14 14" fill="none">
                <path d="M3 11L11 3M11 3H5M11 3V9" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            </span>
          </div>
        </section>
      )}
    </article>
  );
}

Object.assign(window, { CaseStudiesPage, CaseStudyPage, CaseField });
