/* global React */
const { useState: useStateLC } = React;

/* ============================================================
   <Lifecycle> — five-phase interactive rail.
   Pick a phase to see what Lithora does at that stage.
   This is the "Adobe for the mineral lifecycle" frame.
============================================================ */

const PHASES = [
  {
    n: "01",
    name: "Prospect",
    short: "Surface what's there.",
    headline: "Where to look,",
    headlineEm: "before anyone else.",
    body: "Train discovery models on a century of jurisdictional history. We project a probability surface across H3 hexes and rank every target, so your geologists spend their week on the right rock, not the wrong region.",
    features: [
      { k: "ML",    t: <span><strong>Discovery-trained models</strong> per commodity, per craton.</span> },
      { k: "ASM",   t: <span><strong>Artisanal-mining signal</strong>: the oldest reliable cue, ingested live.</span> },
      { k: "GEO",   t: <span><strong>Geophysics fusion</strong>: magnetics, radiometrics, gravity stacked into one surface.</span> },
    ],
    art: "prospect",
  },
  {
    n: "02",
    name: "Explore",
    short: "Confirm in the field.",
    headline: "From hex to hole",
    headlineEm: "in one workflow.",
    body: "Plan campaigns, dispatch crews, and capture drillhole + assay data with offline-first field apps. Everything streams back to the same geo-spatial layer the prospectivity model lives in.",
    features: [
      { k: "FIELD", t: <span><strong>Offline-first capture</strong>: drillhole logs, assays, core photos.</span> },
      { k: "QA",    t: <span><strong>Real-time QA/QC</strong> flags duplicate, blank, and standard breaches.</span> },
      { k: "3D",    t: <span><strong>Block-model preview</strong> as data arrives. No more end-of-campaign surprises.</span> },
    ],
    art: "explore",
  },
  {
    n: "03",
    name: "Develop",
    short: "Plan what gets built.",
    headline: "The pit, the road,",
    headlineEm: "the plant.",
    body: "Score every target against terrain, infrastructure, water, and access. Optimize haul routes, processing siting, and capex sequencing, before permits are filed and before contractors are hired.",
    features: [
      { k: "LOG",   t: <span><strong>Logistics scoring</strong>: terrain, slope, road class, port distance.</span> },
      { k: "CAPEX", t: <span><strong>Capex stack-rank</strong> across competing targets in your portfolio.</span> },
      { k: "WATER", t: <span><strong>Water budgets</strong> modelled per scenario, per watershed.</span> },
    ],
    art: "develop",
  },
  {
    n: "04",
    name: "Operate",
    short: "Run the asset.",
    headline: "Live ground truth",
    headlineEm: "for every shift.",
    body: "Operational intelligence on top of the same model. Reconciliation between block model and mill, fleet utilization, grade-control short-interval feedback, and a market overlay for selling decisions.",
    features: [
      { k: "RECON", t: <span><strong>Reconcile</strong> mined grade vs. modelled grade, daily.</span> },
      { k: "MKT",   t: <span><strong>Market overlay</strong>: LME tape, freight, FX in the same console.</span> },
      { k: "FLT",   t: <span><strong>Fleet & energy</strong> KPIs alongside geology, not bolted on.</span> },
    ],
    art: "operate",
  },
  {
    n: "05",
    name: "Restore",
    short: "Hand it back.",
    headline: "Closure is",
    headlineEm: "a first-class step.",
    body: "Watershed restoration, biodiversity baselining, and community-impact tracking. Closure plans aren't an afterthought document; they're modelled from day one, against the same hexes and the same data layer.",
    features: [
      { k: "WS",    t: <span><strong>Watershed restoration</strong> tracked against pre-disturbance baseline.</span> },
      { k: "BIO",   t: <span><strong>Biodiversity</strong> deltas via species-distribution remote sensing.</span> },
      { k: "COM",   t: <span><strong>Stakeholder ledger</strong>: every commitment, every payout, dated.</span> },
    ],
    art: "restore",
  },
];

function PhaseArt({ kind }) {
  // Lightweight inline SVG illustrations — abstract, on-brand, no stock.
  const W = 480, H = 320;
  if (kind === "prospect") {
    // mini hex heatmap
    const hexes = [];
    for (let r = 0; r < 7; r++) for (let c = 0; c < 10; c++) {
      const dx0 = c - 5, dy0 = r - 3;
      const d = Math.sqrt(dx0*dx0 + dy0*dy0);
      const v = Math.max(0, 1 - d / 4) * 0.9 + Math.sin(c*1.3+r*0.5)*0.04;
      const fill =
        v < 0.2 ? "rgba(125,144,128,0.06)" :
        v < 0.4 ? "rgba(125,144,128,0.22)" :
        v < 0.6 ? "rgba(154,147,122,0.45)" :
        v < 0.8 ? "rgba(200,164,90,0.62)" :
                  "rgba(184,92,74,0.78)";
      hexes.push({ c, r, fill });
    }
    const s = 24;
    const dxh = s * Math.sqrt(3);
    const dyh = s * 1.5;
    return (
      <svg width="100%" height="100%" viewBox={`0 0 ${W} ${H}`}>
        <rect width={W} height={H} fill="#07090c" />
        {hexes.map((h, i) => {
          const cx = 30 + h.c * dxh + ((h.r % 2) ? dxh/2 : 0);
          const cy = 30 + h.r * dyh;
          const pts = [];
          for (let i = 0; i < 6; i++) {
            const a = (Math.PI/3)*i + Math.PI/6;
            pts.push([cx + s*0.86*Math.cos(a), cy + s*0.86*Math.sin(a)]);
          }
          return <path key={i} d={"M"+pts.map(p=>p.join(",")).join("L")+"Z"} fill={h.fill} stroke="rgba(255,255,255,0.04)" />;
        })}
      </svg>
    );
  }
  if (kind === "explore") {
    // drillhole / borehole illustration
    const cols = [60, 140, 220, 300, 380];
    return (
      <svg width="100%" height="100%" viewBox={`0 0 ${W} ${H}`}>
        <rect width={W} height={H} fill="#07090c" />
        <rect y={60} width={W} height={1} fill="rgba(255,255,255,0.08)" />
        <text x={20} y={50} fontFamily="Geist Mono" fontSize="9" fill="rgba(255,255,255,0.35)" letterSpacing="0.14em">SURFACE · 0m</text>
        {cols.map((x, i) => (
          <g key={i}>
            <line x1={x} y1={60} x2={x} y2={260} stroke="rgba(255,255,255,0.18)" strokeWidth="1.4" />
            {/* core sections */}
            {[
              { y: 70,  h: 30, fill: "rgba(125,144,128,0.4)" },
              { y: 100, h: 22, fill: "rgba(154,147,122,0.6)" },
              { y: 122, h: 18, fill: "rgba(200,164,90,0.75)" },
              { y: 140, h: 32, fill: "rgba(184,92,74,0.7)" },
              { y: 172, h: 24, fill: "rgba(125,144,128,0.55)" },
              { y: 196, h: 38, fill: "rgba(60,70,80,0.6)" },
              { y: 234, h: 26, fill: "rgba(154,147,122,0.4)" },
            ].map((seg, j) => (
              <rect key={j} x={x - 5} y={seg.y + (i*3)%6} width={10} height={seg.h} fill={seg.fill} />
            ))}
            <text x={x - 16} y={278} fontFamily="Geist Mono" fontSize="9" fill="rgba(255,255,255,0.45)">DH-{(i+1)*7}</text>
          </g>
        ))}
        <text x={20} y={290} fontFamily="Geist Mono" fontSize="9" fill="rgba(255,255,255,0.35)" letterSpacing="0.14em">240m TD</text>
      </svg>
    );
  }
  if (kind === "develop") {
    // network/route diagram
    const nodes = [
      { x: 80,  y: 110, r: 10, l: "Pit"  },
      { x: 200, y: 60,  r: 6, l: "Wp 1" },
      { x: 280, y: 130, r: 8, l: "Plant" },
      { x: 380, y: 80,  r: 6, l: "Wp 2" },
      { x: 420, y: 220, r: 12, l: "Port" },
      { x: 140, y: 220, r: 6, l: "Comm" },
    ];
    const edges = [[0,1],[1,2],[0,2],[2,3],[3,4],[2,4],[0,5]];
    return (
      <svg width="100%" height="100%" viewBox={`0 0 ${W} ${H}`}>
        <rect width={W} height={H} fill="#07090c" />
        {/* contour */}
        {[60, 100, 140, 180, 220].map((y, i) => (
          <path key={i} d={`M0 ${y} C 120 ${y - 10}, 280 ${y + 14}, ${W} ${y - 4}`}
                fill="none" stroke="rgba(125,144,128,0.10)" strokeWidth="0.8" />
        ))}
        {edges.map(([a, b], i) => (
          <line key={i} x1={nodes[a].x} y1={nodes[a].y} x2={nodes[b].x} y2={nodes[b].y}
                stroke="rgba(200,164,90,0.4)" strokeWidth="1" strokeDasharray="2 3" />
        ))}
        {nodes.map((n, i) => (
          <g key={i}>
            <circle cx={n.x} cy={n.y} r={n.r + 6} fill="none" stroke="rgba(255,255,255,0.06)" />
            <circle cx={n.x} cy={n.y} r={n.r} fill="rgba(154,147,122,0.45)" stroke="#fff" strokeWidth="1" />
            <text x={n.x + n.r + 6} y={n.y + 3} fontFamily="Geist Mono" fontSize="10" fill="rgba(255,255,255,0.75)">{n.l}</text>
          </g>
        ))}
      </svg>
    );
  }
  if (kind === "operate") {
    // Sparkline + KPI panel
    const points = [];
    for (let i = 0; i < 40; i++) {
      points.push([20 + i * 11, 200 - 30 - Math.sin(i*0.5) * 20 - i * 0.8 - (i % 7) * 4]);
    }
    const path = "M " + points.map(p => p.join(" ")).join(" L ");
    return (
      <svg width="100%" height="100%" viewBox={`0 0 ${W} ${H}`}>
        <rect width={W} height={H} fill="#07090c" />
        <text x={20} y={40} fontFamily="Geist Mono" fontSize="10" fill="rgba(255,255,255,0.4)" letterSpacing="0.14em">RECONCILIATION · 30D</text>
        <text x={20} y={80} fontFamily="Instrument Serif" fontSize="42" fill="#fff">97.4%</text>
        <text x={140} y={78} fontFamily="Geist Mono" fontSize="11" fill="rgba(125,144,128,0.9)">↑ 1.2 pts</text>
        <path d={path} fill="none" stroke="rgba(200,164,90,0.85)" strokeWidth="1.6" />
        <path d={path + ` L ${points[points.length-1][0]} 230 L 20 230 Z`} fill="rgba(200,164,90,0.1)" />
        {/* horizontal grid */}
        {[110, 150, 190, 230].map((y, i) => (
          <line key={i} x1="20" y1={y} x2={W - 20} y2={y} stroke="rgba(255,255,255,0.05)" />
        ))}
        <text x={20} y={290} fontFamily="Geist Mono" fontSize="9" fill="rgba(255,255,255,0.35)" letterSpacing="0.14em">BLOCK ↔ MILL · 30 SHIFTS</text>
      </svg>
    );
  }
  // restore
  // Concentric watershed rings
  return (
    <svg width="100%" height="100%" viewBox={`0 0 ${W} ${H}`}>
      <rect width={W} height={H} fill="#07090c" />
      <g transform={`translate(${W/2}, ${H/2})`}>
        {[140, 110, 80, 50, 26].map((r, i) => (
          <circle key={i} cx="0" cy="0" r={r}
                  fill="none"
                  stroke={`rgba(125,144,128,${0.10 + i * 0.10})`}
                  strokeWidth="1" strokeDasharray={i === 2 ? "3 4" : "0"} />
        ))}
        <circle cx="0" cy="0" r="4" fill="#fff" />
      </g>
      <text x={20} y={40} fontFamily="Geist Mono" fontSize="10" fill="rgba(255,255,255,0.4)" letterSpacing="0.14em">WATERSHED · BASELINE 0.93</text>
      <text x={20} y={290} fontFamily="Geist Mono" fontSize="9" fill="rgba(255,255,255,0.35)" letterSpacing="0.14em">RECOVERY INDEX · 5km RADIUS</text>
      {/* legend dots */}
      <g transform={`translate(${W - 130}, 60)`}>
        {["Year 0","Year 3","Year 5","Year 8","Closure"].map((l, i) => (
          <g key={i} transform={`translate(0, ${i * 20})`}>
            <circle cx="0" cy="0" r="4" fill={`rgba(125,144,128,${0.20 + i * 0.16})`} />
            <text x="10" y="3" fontFamily="Geist Mono" fontSize="10" fill="rgba(255,255,255,0.55)">{l}</text>
          </g>
        ))}
      </g>
    </svg>
  );
}

function Lifecycle() {
  const [idx, setIdx] = useStateLC(0);
  const p = PHASES[idx];

  return (
    <section className="section" id="lifecycle" data-screen-label="06 Lifecycle">
      <SectionHead
        num="§ 04 · LIFECYCLE"
        eyebrow="The full arc"
        h2={<>From prospect<br/>to restoration.</>}
        lead="Most platforms cover one slice. Lithora is built end-to-end. Every phase reads from the same geo-spatial truth, so a decision made in the field shows up in your closure plan ten years later."
      />

      <div className="reveal">
        <div className="lifecycle-rail">
          {PHASES.map((ph, i) => (
            <button
              key={ph.n}
              className={"phase" + (i === idx ? " on" : "")}
              onClick={() => setIdx(i)}
              type="button"
            >
              <div className="phase-num">PHASE · {ph.n}</div>
              <div className="phase-name">{ph.name}</div>
              <div className="phase-desc">{ph.short}</div>
            </button>
          ))}
        </div>

        <div className="phase-detail" key={p.n}>
          <div className="phase-detail-l">
            <h3 className="phase-detail-h">
              <TypeReveal text={p.headline + " " + p.headlineEm} speed={26} />
            </h3>
            <p className="phase-detail-p">{p.body}</p>
            <div className="phase-features">
              {p.features.map((f, i) => (
                <div className="phase-feature" key={i}>
                  <span className="phase-feature-glyph">{f.k}</span>
                  <span className="phase-feature-text">{f.t}</span>
                </div>
              ))}
            </div>
          </div>
          <div className="phase-art">
            <PhaseArt kind={p.art} />
          </div>
        </div>
      </div>
    </section>
  );
}

window.Lifecycle = Lifecycle;
