/* global React, window */
const { useState, useEffect, useRef } = React;

/**
 * Hydrochemolytic Technology (HCT) — accurate mechanism animation.
 *
 * Chemistry faithfully depicted:
 *   1. Long saturated hydrocarbon chain (polyolefin-like -CH2-CH2-) is the feedstock.
 *   2. Water is the reaction MEDIUM (shown as dispersed H2O molecules in background).
 *   3. A renewable hydrogen-donor co-agent (methanol, CH3OH) — NOT water — supplies the
 *      hydrogen equivalents that cap the broken ends. This is the core HCT novelty.
 *   4. A metal-based catalyst (simple metal compound, in-situ) coordinates to a C-C bond
 *      and enables SELECTIVE cleavage at moderate temperature (240-390°C).
 *   5. Both fragment ends are capped with -H, yielding two SATURATED shorter chains
 *      (~97% saturation; no -OH, no olefins).
 *   6. The spent donor departs as its oxidized form (formaldehyde CH2O / later CO2).
 *
 * Sources confirmed:
 *   - Aduro research page (hydrogen equivalents from methanol/ethanol/glycerol/cellulose)
 *   - Canadian Plastics Magazine, Ofer Vicus interview (240-390°C operating range)
 *   - Slack Capital equity research (water = medium, H-donor added separately, ~97% saturated)
 *   - Yahoo Finance (in-situ metal catalyst, selective C-C bond breaking)
 */
function MoleculeViz() {
  const [t, setT] = useState(0);
  const raf = useRef(null);
  const start = useRef(null);

  useEffect(() => {
    const tick = (now) => {
      if (!start.current) start.current = now;
      const elapsed = (now - start.current) / 1000;
      setT(elapsed % 10); // 10-second loop
      raf.current = requestAnimationFrame(tick);
    };
    raf.current = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf.current);
  }, []);

  // Four phases — each ~2.5s
  //  0.0–2.5  setup      : chain, catalyst dispersed, donor + water in medium
  //  2.5–4.5  engage     : catalyst docks to a C–C bond; donor approaches
  //  4.5–6.5  transfer   : C–C cleaves; donor transfers 2H to the two broken ends
  //  6.5–10.0 products   : two saturated chains drift apart; donor leaves oxidized
  const phase =
    t < 2.5 ? "setup" :
    t < 4.5 ? "engage" :
    t < 6.5 ? "transfer" :
    "products";

  const W = 600, H = 600;
  const cy = H / 2;
  const chainN = 12;
  const chainSpacing = 34;
  const chainStartX = (W - (chainN - 1) * chainSpacing) / 2;

  // Phase progress (0..1 each)
  const pEngage   = Math.min(1, Math.max(0, (t - 2.5) / 2.0));
  const pTransfer = Math.min(1, Math.max(0, (t - 4.5) / 2.0));
  const pProducts = Math.min(1, Math.max(0, (t - 6.5) / 3.5));

  const breakIdx = 6; // break between carbon 5 and 6
  const ease = (x) => 1 - Math.pow(1 - x, 3);

  // Catalyst (metal center, Ni-like) — comes in from below, docks under the break bond
  // Stays docked from engage → transfer → departs during products
  const catalystStart = { x: W / 2, y: H - 60 };
  const catalystDock  = { x: (chainStartX + (breakIdx - 0.5) * chainSpacing), y: cy + 26 };
  let catalystX, catalystY, catalystOpacity = 1;
  if (phase === "setup") {
    catalystX = catalystStart.x + Math.sin(t * 1.2) * 30;
    catalystY = catalystStart.y + Math.cos(t * 1.1) * 20;
  } else if (phase === "engage") {
    catalystX = catalystStart.x + (catalystDock.x - catalystStart.x) * ease(pEngage);
    catalystY = catalystStart.y + (catalystDock.y - catalystStart.y) * ease(pEngage);
  } else if (phase === "transfer") {
    catalystX = catalystDock.x;
    catalystY = catalystDock.y + Math.sin(t * 10) * 1.5;
  } else {
    // departs downward
    catalystX = catalystDock.x;
    catalystY = catalystDock.y + pProducts * 80;
    catalystOpacity = 1 - pProducts * 0.7;
  }

  // Donor: methanol CH3OH — approaches from above, positions near cleavage site,
  // donates 2 H atoms during transfer phase, departs as formaldehyde (loses 2 H)
  const donorStart = { x: W / 2 + 20, y: 50 };
  const donorDock  = { x: catalystDock.x, y: cy - 38 };
  let donorX, donorY, donorOpacity = 1;
  if (phase === "setup") {
    donorX = donorStart.x + Math.sin(t * 0.9) * 40;
    donorY = donorStart.y + Math.cos(t * 1.3) * 15;
  } else if (phase === "engage") {
    donorX = donorStart.x + (donorDock.x - donorStart.x) * ease(pEngage);
    donorY = donorStart.y + (donorDock.y - donorStart.y) * ease(pEngage);
  } else if (phase === "transfer") {
    donorX = donorDock.x + Math.sin(t * 8) * 2;
    donorY = donorDock.y;
  } else {
    // departs upward, now oxidized (formaldehyde H2C=O)
    donorX = donorDock.x + (pProducts * 40);
    donorY = donorDock.y - pProducts * 90;
    donorOpacity = 1 - pProducts * 0.5;
  }

  // During transfer, render the two H atoms traveling from donor to the two broken chain ends
  const hTransferProgress = pTransfer;

  return (
    <div className="molecule-stage">
      <svg viewBox={`0 0 ${W} ${H}`} width="100%" height="100%" style={{ display: 'block' }}>
        <defs>
          <radialGradient id="carbonGrad" cx="35%" cy="35%">
            <stop offset="0%" stopColor="#4e5a66" />
            <stop offset="100%" stopColor="#2b333c" />
          </radialGradient>
          <radialGradient id="hydrogenGrad" cx="35%" cy="35%">
            <stop offset="0%" stopColor="#ffffff" />
            <stop offset="100%" stopColor="#c9ccd0" />
          </radialGradient>
          <radialGradient id="oxyGrad" cx="35%" cy="35%">
            <stop offset="0%" stopColor="#e58a3a" />
            <stop offset="100%" stopColor="#a0461a" />
          </radialGradient>
          <radialGradient id="metalGrad" cx="35%" cy="35%">
            <stop offset="0%" stopColor="#d5b97a" />
            <stop offset="100%" stopColor="#8a6a28" />
          </radialGradient>
          <radialGradient id="waterGlow" cx="50%" cy="50%">
            <stop offset="0%" stopColor="rgba(30,96,145,0.18)" />
            <stop offset="100%" stopColor="rgba(30,96,145,0)" />
          </radialGradient>
          <radialGradient id="catBond" cx="50%" cy="50%">
            <stop offset="0%" stopColor="rgba(168,116,32,0.5)" />
            <stop offset="100%" stopColor="rgba(168,116,32,0)" />
          </radialGradient>
        </defs>

        {/* Background grid dots — very subtle */}
        {Array.from({ length: 20 }).map((_, i) =>
          Array.from({ length: 20 }).map((_, j) => (
            <circle key={`${i}-${j}`} cx={i * 30 + 15} cy={j * 30 + 15} r="0.5" fill="#d8d6cd" />
          ))
        )}

        {/* Ambient water medium — drifting H2O molecules in background (unreactive context) */}
        {[
          { x: 70, y: 100, d: 0 },
          { x: 520, y: 140, d: 1.5 },
          { x: 120, y: 460, d: 3 },
          { x: 480, y: 500, d: 4.2 },
          { x: 90, y: 280, d: 2.1 },
          { x: 540, y: 340, d: 0.8 },
          { x: 280, y: 80, d: 3.6 },
          { x: 320, y: 530, d: 5 },
        ].map((w, i) => {
          const drift = Math.sin(t * 0.6 + w.d) * 8;
          return (
            <g key={`h2o-${i}`} transform={`translate(${w.x + drift}, ${w.y + Math.cos(t * 0.5 + w.d) * 6})`} opacity="0.5">
              <circle r="14" fill="url(#waterGlow)" />
              <circle cx="0" cy="0" r="5" fill="url(#oxyGrad)" opacity="0.55" />
              <circle cx="-5" cy="-4" r="2.4" fill="url(#hydrogenGrad)" opacity="0.55" />
              <circle cx="5" cy="-4" r="2.4" fill="url(#hydrogenGrad)" opacity="0.55" />
            </g>
          );
        })}

        {/* "Water medium" label — faint, top-left */}
        <text x="24" y="36" fontFamily="JetBrains Mono" fontSize="9" fill="#8a8f95" letterSpacing="0.5">
          H₂O · reaction medium
        </text>

        {/* POLYMER CHAIN — renders as single chain when intact, as two fragments after transfer */}
        {Array.from({ length: chainN }).map((_, i) => {
          const isLeft = i < breakIdx;
          // Drift apart only in products phase
          const driftX = phase === "products"
            ? (isLeft ? -1 : 1) * ease(pProducts) * 85
            : 0;
          const x = chainStartX + i * chainSpacing + driftX;
          const y = cy + Math.sin(i * 0.8 + t * 0.3) * 2;

          const bondToNext = i < chainN - 1;
          const isBreakBond = i === breakIdx - 1;

          // Bond rendering
          let bondEl = null;
          if (bondToNext && !isBreakBond) {
            bondEl = (
              <line
                x1={x} y1={y}
                x2={chainStartX + (i + 1) * chainSpacing + driftX}
                y2={cy + Math.sin((i + 1) * 0.8 + t * 0.3) * 2}
                stroke="#3e4247"
                strokeWidth="2.8"
              />
            );
          } else if (bondToNext && isBreakBond) {
            // Breaking bond
            if (phase === "setup") {
              bondEl = (
                <line x1={x} y1={y}
                      x2={chainStartX + (i + 1) * chainSpacing}
                      y2={cy + Math.sin((i + 1) * 0.8 + t * 0.3) * 2}
                      stroke="#3e4247" strokeWidth="2.8" />
              );
            } else if (phase === "engage") {
              // activated: subtle pulse as catalyst coordinates
              const pulse = 2.8 + Math.sin(t * 10) * 0.8 * pEngage;
              bondEl = (
                <line x1={x} y1={y}
                      x2={chainStartX + (i + 1) * chainSpacing}
                      y2={cy + Math.sin((i + 1) * 0.8 + t * 0.3) * 2}
                      stroke={`rgb(${62 + pEngage * 100}, ${66 + pEngage * 40}, ${71 - pEngage * 20})`}
                      strokeWidth={pulse} />
              );
            } else if (phase === "transfer") {
              // Bond fades out as scission progresses
              bondEl = (
                <line x1={x} y1={y}
                      x2={chainStartX + (i + 1) * chainSpacing}
                      y2={cy + Math.sin((i + 1) * 0.8 + t * 0.3) * 2}
                      stroke="#a87420"
                      strokeWidth={2.8 - pTransfer * 2.8}
                      strokeDasharray="3 3"
                      opacity={1 - pTransfer} />
              );
            }
            // In products phase: no bond (broken)
          }

          return (
            <g key={i}>
              {bondEl}

              {/* Existing 2 H atoms per carbon (up/down) */}
              <line x1={x} y1={y} x2={x} y2={y - 16} stroke="#8a8f95" strokeWidth="1.5" />
              <circle cx={x} cy={y - 20} r="5" fill="url(#hydrogenGrad)" stroke="#b5b9bd" strokeWidth="0.5" />
              <line x1={x} y1={y} x2={x} y2={y + 16} stroke="#8a8f95" strokeWidth="1.5" />
              <circle cx={x} cy={y + 20} r="5" fill="url(#hydrogenGrad)" stroke="#b5b9bd" strokeWidth="0.5" />

              {/* Carbon */}
              <circle cx={x} cy={y} r="10" fill="url(#carbonGrad)" stroke="#1a1d1f" strokeWidth="1" />

              {/* NEW H caps: added during transfer, fully bonded in products.
                  Both broken ends get -H (saturated product). */}
              {(phase === "transfer" || phase === "products") && i === breakIdx - 1 && (
                <g opacity={phase === "transfer" ? hTransferProgress : 1}>
                  <line x1={x} y1={y} x2={x + 11 + (phase === "products" ? 0 : 0)} y2={y - 2}
                        stroke="#8a8f95" strokeWidth="1.5" />
                  <circle cx={x + 14} cy={y - 4} r="5"
                          fill="url(#hydrogenGrad)" stroke="#b5b9bd" strokeWidth="0.5" />
                </g>
              )}
              {(phase === "transfer" || phase === "products") && i === breakIdx && (
                <g opacity={phase === "transfer" ? hTransferProgress : 1}>
                  <line x1={x} y1={y} x2={x - 11} y2={y - 2}
                        stroke="#8a8f95" strokeWidth="1.5" />
                  <circle cx={x - 14} cy={y - 4} r="5"
                          fill="url(#hydrogenGrad)" stroke="#b5b9bd" strokeWidth="0.5" />
                </g>
              )}
            </g>
          );
        })}

        {/* CATALYST — metal center (in-situ, Ni/Fe-like simple metal compound) */}
        <g transform={`translate(${catalystX}, ${catalystY})`} opacity={catalystOpacity}>
          {/* Coordination halo when docked */}
          {(phase === "engage" || phase === "transfer") && (
            <circle r={22 + Math.sin(t * 8) * 2} fill="url(#catBond)" />
          )}
          <circle r="12" fill="url(#metalGrad)" stroke="#5a4418" strokeWidth="1" />
          <text x="0" y="4" textAnchor="middle" fontSize="10" fontFamily="JetBrains Mono"
                fontWeight="600" fill="#fff" style={{ pointerEvents: 'none' }}>M</text>

          {/* Dashed coordination bonds to the two carbons being cleaved — only when docked */}
          {(phase === "engage" || phase === "transfer") && (
            <>
              <line x1="-17" y1="-15" x2="-6" y2="-5"
                    stroke="#a87420" strokeWidth="1"
                    strokeDasharray="3 2" opacity={pEngage} />
              <line x1="17" y1="-15" x2="6" y2="-5"
                    stroke="#a87420" strokeWidth="1"
                    strokeDasharray="3 2" opacity={pEngage} />
            </>
          )}
        </g>

        {/* CATALYST LABEL (static, points to a reference position) */}
        {phase === "setup" && (
          <text x={catalystX + 22} y={catalystY + 4} fontFamily="JetBrains Mono"
                fontSize="10" fill="#8a6a28">M · metal catalyst</text>
        )}

        {/* HYDROGEN DONOR — methanol CH3OH before transfer, becomes formaldehyde H2C=O after */}
        {/* Methanol: central C, one O-H, three H's. Simplified to readable schematic. */}
        <g transform={`translate(${donorX}, ${donorY})`} opacity={donorOpacity}>
          {phase !== "products" ? (
            // Methanol CH3OH
            <>
              <circle r="22" fill="url(#waterGlow)" opacity="0.6" />
              {/* Central carbon */}
              <circle cx="0" cy="0" r="8" fill="url(#carbonGrad)" stroke="#1a1d1f" strokeWidth="0.8" />
              <text x="0" y="3" textAnchor="middle" fontSize="8" fontFamily="JetBrains Mono" fill="#fff" style={{ pointerEvents: 'none' }}>C</text>

              {/* Three H's on carbon — two donated during transfer */}
              {/* H1 (donated during transfer to LEFT chain end) */}
              {phase !== "transfer" || hTransferProgress < 0.3 ? (
                <>
                  <line x1="0" y1="0" x2="-9" y2="-6" stroke="#8a8f95" strokeWidth="1.2" />
                  <circle cx="-11" cy="-7" r="4" fill="url(#hydrogenGrad)" stroke="#b5b9bd" strokeWidth="0.5" />
                </>
              ) : null}
              {/* H2 (donated to RIGHT chain end) */}
              {phase !== "transfer" || hTransferProgress < 0.3 ? (
                <>
                  <line x1="0" y1="0" x2="9" y2="-6" stroke="#8a8f95" strokeWidth="1.2" />
                  <circle cx="11" cy="-7" r="4" fill="url(#hydrogenGrad)" stroke="#b5b9bd" strokeWidth="0.5" />
                </>
              ) : null}
              {/* H3 (stays) */}
              <line x1="0" y1="0" x2="0" y2="11" stroke="#8a8f95" strokeWidth="1.2" />
              <circle cx="0" cy="14" r="4" fill="url(#hydrogenGrad)" stroke="#b5b9bd" strokeWidth="0.5" />
              {/* O-H */}
              <line x1="0" y1="0" x2="-11" y2="7" stroke="#8a8f95" strokeWidth="1.2" />
              <circle cx="-13" cy="9" r="6" fill="url(#oxyGrad)" />
              <text x="-13" y="12" textAnchor="middle" fontSize="7" fontFamily="JetBrains Mono" fontWeight="600" fill="#fff" style={{ pointerEvents: 'none' }}>O</text>
              <line x1="-13" y1="9" x2="-22" y2="12" stroke="#8a8f95" strokeWidth="1" />
              <circle cx="-24" cy="13" r="3.5" fill="url(#hydrogenGrad)" stroke="#b5b9bd" strokeWidth="0.5" />
            </>
          ) : (
            // Oxidized byproduct: formaldehyde H2C=O (methanol minus 2H)
            <>
              <circle r="18" fill="url(#waterGlow)" opacity="0.4" />
              <circle cx="0" cy="0" r="7" fill="url(#carbonGrad)" stroke="#1a1d1f" strokeWidth="0.8" />
              <text x="0" y="3" textAnchor="middle" fontSize="7" fontFamily="JetBrains Mono" fill="#fff" style={{ pointerEvents: 'none' }}>C</text>
              {/* Double bond to O */}
              <line x1="4" y1="-2" x2="13" y2="-6" stroke="#8a8f95" strokeWidth="1.2" />
              <line x1="6" y1="1" x2="15" y2="-3" stroke="#8a8f95" strokeWidth="1.2" />
              <circle cx="16" cy="-5" r="6" fill="url(#oxyGrad)" />
              <text x="16" y="-2" textAnchor="middle" fontSize="7" fontFamily="JetBrains Mono" fontWeight="600" fill="#fff" style={{ pointerEvents: 'none' }}>O</text>
              {/* 2 remaining H's */}
              <line x1="-3" y1="-3" x2="-9" y2="-9" stroke="#8a8f95" strokeWidth="1" />
              <circle cx="-11" cy="-11" r="3.5" fill="url(#hydrogenGrad)" stroke="#b5b9bd" strokeWidth="0.5" />
              <line x1="-3" y1="3" x2="-9" y2="9" stroke="#8a8f95" strokeWidth="1" />
              <circle cx="-11" cy="11" r="3.5" fill="url(#hydrogenGrad)" stroke="#b5b9bd" strokeWidth="0.5" />
            </>
          )}
        </g>

        {/* DONOR LABEL — annotated only during setup */}
        {phase === "setup" && (
          <text x={donorX + 34} y={donorY + 4} fontFamily="JetBrains Mono" fontSize="10" fill="#3e4247">
            CH₃OH · H-donor
          </text>
        )}
        {phase === "products" && (
          <text x={donorX + 24} y={donorY + 4} fontFamily="JetBrains Mono" fontSize="9" fill="#8a8f95">
            H₂C=O · spent
          </text>
        )}

        {/* H-TRANSFER arrows during transfer phase — two H atoms moving from donor to the two chain ends */}
        {phase === "transfer" && hTransferProgress > 0.3 && hTransferProgress < 0.95 && (() => {
          const p = (hTransferProgress - 0.3) / 0.65;
          const leftTarget = {
            x: chainStartX + (breakIdx - 1) * chainSpacing + 14,
            y: cy - 4
          };
          const rightTarget = {
            x: chainStartX + breakIdx * chainSpacing - 14,
            y: cy - 4
          };
          const hLeftStart = { x: donorX - 11, y: donorY - 7 };
          const hRightStart = { x: donorX + 11, y: donorY - 7 };
          const lx = hLeftStart.x + (leftTarget.x - hLeftStart.x) * p;
          const ly = hLeftStart.y + (leftTarget.y - hLeftStart.y) * p;
          const rx = hRightStart.x + (rightTarget.x - hRightStart.x) * p;
          const ry = hRightStart.y + (rightTarget.y - hRightStart.y) * p;
          return (
            <g>
              <circle cx={lx} cy={ly} r="4" fill="url(#hydrogenGrad)" stroke="#b5b9bd" strokeWidth="0.5" opacity={1 - p * 0.3} />
              <circle cx={rx} cy={ry} r="4" fill="url(#hydrogenGrad)" stroke="#b5b9bd" strokeWidth="0.5" opacity={1 - p * 0.3} />
              {/* motion trails */}
              <line x1={hLeftStart.x} y1={hLeftStart.y} x2={lx} y2={ly}
                    stroke="#1e6091" strokeWidth="1" strokeDasharray="2 3" opacity="0.4" />
              <line x1={hRightStart.x} y1={hRightStart.y} x2={rx} y2={ry}
                    stroke="#1e6091" strokeWidth="1" strokeDasharray="2 3" opacity="0.4" />
            </g>
          );
        })()}

        {/* Phase label */}
        <g transform={`translate(24, ${H - 44})`}>
          <text fontFamily="JetBrains Mono" fontSize="10" fill="#656a70" letterSpacing="0.8" fontWeight="500">
            {phase === "setup"     && "01 · FEEDSTOCK + H-DONOR IN AQUEOUS MEDIUM"}
            {phase === "engage"    && "02 · METAL CATALYST COORDINATES TO C–C BOND"}
            {phase === "transfer"  && "03 · SELECTIVE SCISSION + H-TRANSFER FROM DONOR"}
            {phase === "products"  && "04 · TWO SATURATED CHAINS · SPENT DONOR (H₂C=O)"}
          </text>
          <text fontFamily="JetBrains Mono" fontSize="9" fill="#8a8f95" letterSpacing="0.5" y="16">
            {phase === "setup"     && "Water transfers heat & transports co-agents"}
            {phase === "engage"    && "Mild conditions: 240–390 °C, no H₂ gas required"}
            {phase === "transfer"  && "Donor supplies H equivalents in situ"}
            {phase === "products"  && "~97% saturated hydrocarbons · no further H₂ needed"}
          </text>
        </g>

        {/* Conditions indicator */}
        <g transform={`translate(${W - 170}, ${H - 44})`}>
          <text fontFamily="JetBrains Mono" fontSize="10" fill="#656a70" letterSpacing="0.8">
            240–390 °C
          </text>
          <text fontFamily="JetBrains Mono" fontSize="9" fill="#8a8f95" letterSpacing="0.5" y="16">
            &lt;2% char · no H₂
          </text>
        </g>
      </svg>
    </div>
  );
}

window.MoleculeViz = MoleculeViz;
