// Refined sections: Pillars (Observe/Optimize/Control), Use cases, Why Graph,
// CTA, and the floating Design Notes panel. These elevate the page from
// "internal-tool feel" to "mission-critical software for energy systems".

const { useState: useSR, useEffect: useER } = React;

// ---------------- Trust strip ----------------
// A narrow band right under the hero. Operational proof, no marketing fluff.
function TrustStrip() {
  const items = [
    ["PUBLIC NETWORK VIEW", "SG · EXTERNAL"],
    ["ANONYMISED CELLS",    "24"],
    ["STREAMING CLUSTERS",  "12"],
    ["INGEST CADENCE",     "5 min"],
    ["HISTORY WINDOW",     "24 h"],
    ["SIGNAL HEALTH",      "99.97%"],
  ];
  return (
    <section className="trust" data-screen-label="trust">
      <div className="wrap">
        <div className="trust-grid">
          {items.map(([k, v]) => (
            <div className="trust-cell" key={k}>
              <div className="mono trust-k">{k}</div>
              <div className="trust-v">{v}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ---------------- Pillars: Observe / Optimize / Control ----------------
// Three vertical product pillars. Each has a tiny live diagram. The diagrams
// are intentionally simple — the goal is to read at a glance.

function PillarObserve({ accent }) {
  const [t, setT] = useSR(0);
  useER(() => { const id = setInterval(() => setT(x => x + 1), 1100); return () => clearInterval(id); }, []);
  // Sparkline of generation
  const w = 280, h = 90;
  const pts = Array.from({ length: 36 }).map((_, i) => {
    const x = (i / 35) * w;
    const sun = Math.max(0, Math.sin((i / 35) * Math.PI - 0.1));
    const noise = Math.sin(i * 1.6 + t * 0.4) * 0.04;
    return [x, h - 8 - (sun + noise) * (h - 16)];
  });
  const path = pts.map((p, i) => (i ? "L" : "M") + p[0].toFixed(1) + "," + p[1].toFixed(1)).join(" ");
  return (
    <svg viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none" style={{ width: "100%", height: 90 }}>
      <path d={path + ` L ${w},${h} L 0,${h} Z`} fill={accent} fillOpacity="0.12" />
      <path d={path} stroke={accent} strokeWidth="1.2" fill="none" />
      <circle cx={pts[pts.length-1][0]} cy={pts[pts.length-1][1]} r="2.5" fill={accent} />
    </svg>
  );
}

function PillarOptimize({ accent }) {
  // Forecast cone: a center prediction line with a fading band.
  const w = 280, h = 90;
  const center = Array.from({ length: 30 }).map((_, i) => {
    const x = (i / 29) * w;
    const y = h/2 + Math.sin(i * 0.5) * 8 - i * 0.4;
    return [x, y];
  });
  const upper = center.map(([x, y], i) => [x, y - (3 + i * 0.4)]);
  const lower = center.map(([x, y], i) => [x, y + (3 + i * 0.4)]);
  const band = upper.map((p, i) => (i ? "L" : "M") + p[0].toFixed(1) + "," + p[1].toFixed(1)).join(" ")
             + " " + lower.slice().reverse().map((p, i) => "L" + p[0].toFixed(1) + "," + p[1].toFixed(1)).join(" ") + " Z";
  const line = center.map((p, i) => (i ? "L" : "M") + p[0].toFixed(1) + "," + p[1].toFixed(1)).join(" ");
  // Past data dots before the cone start
  const past = Array.from({ length: 6 }).map((_, i) => {
    const x = -((6 - i) * 16);
    const y = h/2 + Math.sin(i * 0.7) * 6;
    return [x, y];
  });
  return (
    <svg viewBox={`-100 0 ${w + 100} ${h}`} preserveAspectRatio="none" style={{ width: "100%", height: 90 }}>
      <line x1="-100" y1={h/2} x2={w} y2={h/2} stroke="rgba(255,255,255,0.06)" strokeDasharray="2 4" />
      <path d={band} fill={accent} fillOpacity="0.16" />
      <path d={line} stroke={accent} strokeWidth="1.2" fill="none" strokeDasharray="3 3" />
      {past.map(([x, y], i) => <circle key={i} cx={x} cy={y} r="1.6" fill="rgba(255,255,255,0.5)" />)}
      <line x1="0" y1="6" x2="0" y2={h-6} stroke="rgba(255,255,255,0.18)" />
      <text x="4" y="14" fontFamily="IBM Plex Mono, monospace" fontSize="9" fill="rgba(255,255,255,0.4)" letterSpacing="1">NOW</text>
    </svg>
  );
}

function PillarControl({ accent }) {
  const [t, setT] = useSR(0);
  useER(() => { const id = setInterval(() => setT(x => x + 1), 700); return () => clearInterval(id); }, []);
  const w = 280, h = 90;
  // A setpoint that the actual line tracks with a small lag
  const setpoint = Array.from({ length: 40 }).map((_, i) => {
    const phase = i / 39;
    return phase < 0.3 ? 0.4 : phase < 0.6 ? 0.75 : 0.5;
  });
  const actual = setpoint.map((s, i) => {
    const lag = i > 2 ? setpoint[i - 2] : s;
    return lag + Math.sin((i + t) * 0.6) * 0.025;
  });
  const yOf = (v) => h - 8 - v * (h - 16);
  const sPath = setpoint.map((v, i) => (i ? "L" : "M") + (i / 39 * w).toFixed(1) + "," + yOf(v).toFixed(1)).join(" ");
  const aPath = actual.map((v, i) => (i ? "L" : "M") + (i / 39 * w).toFixed(1) + "," + yOf(v).toFixed(1)).join(" ");
  return (
    <svg viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none" style={{ width: "100%", height: 90 }}>
      <path d={sPath} stroke="rgba(255,255,255,0.35)" strokeWidth="1" strokeDasharray="3 3" fill="none" />
      <path d={aPath} stroke={accent} strokeWidth="1.4" fill="none" />
    </svg>
  );
}

function Pillars({ accent }) {
  const pillars = [
    {
      n: "01",
      title: "Observe",
      lede: "Telemetry, signal drift, weather, and grid overlays — unified across vendors and rendered as privacy-safe public cells.",
      bullets: ["Multi-vendor ingest", "Anonymised cluster health", "Grid voltage & weather overlay", "5-min resolution, rolling public history"],
      art: PillarObserve,
      meta: ["External map view", "Live in production"],
    },
    {
      n: "02",
      title: "Optimize",
      lede: "Forecasts, performance ratios, and scenario modelling — built on real Singapore field data, not generic libraries.",
      bullets: ["Nowcasting & day-ahead", "PR + soiling models", "EV charge-window optimiser", "Tariff & USEP-aware"],
      art: PillarOptimize,
      meta: ["Solar-to-EV (live)", "Forecasts (Q3 2026)"],
    },
    {
      n: "03",
      title: "Control",
      lede: "Closed-loop control software for inverters, chargers, and batteries, with public-facing views limited to anonymised network state.",
      bullets: ["Protected control APIs", "EV charger orchestration", "Battery dispatch (preview)", "Safety interlocks & audit trail"],
      art: PillarControl,
      meta: ["EV control (live)", "Battery dispatch (Q4 2026)"],
    },
  ];

  return (
    <section className="sec" id="pillars" data-screen-label="pillars">
      <div className="wrap">
        <div className="sec-head">
          <div className="label">02 · WHAT GRAPH DOES</div>
          <div>
            <h2>Three loops on one data spine.</h2>
            <p>Most energy software stops at dashboards. Graph closes the loop — observation feeds forecasts, forecasts inform control, control writes new data back to the spine.</p>
          </div>
        </div>

        <div className="pillar-grid">
          {pillars.map((p) => {
            const Art = p.art;
            return (
              <article className="pillar" key={p.n}>
                <header className="pillar-h">
                  <div className="mono pillar-n">{p.n}</div>
                  <h3 className="pillar-t">{p.title}</h3>
                </header>
                <div className="pillar-art">
                  <div className="mono pillar-art-label">{p.title.toUpperCase()} · LIVE</div>
                  <Art accent={accent} />
                </div>
                <p className="pillar-lede">{p.lede}</p>
                <ul className="pillar-list">
                  {p.bullets.map((b) => <li key={b}>{b}</li>)}
                </ul>
                <div className="pillar-meta">
                  {p.meta.map((m, i) => <span key={i} className="mono">{m}</span>)}
                </div>
              </article>
            );
          })}
        </div>
      </div>
    </section>
  );
}

// ---------------- Use cases ----------------
// 4 cards. Each is a customer archetype with a one-line value prop and the
// specific Graph products they use.

function UseCases({ accent }) {
  const cases = [
    {
      who: "Solar operations teams",
      n: "I",
      bold: "See PR drift before it costs you a quarter.",
      detail: "Move from anonymous public cluster signals into protected internal workflows without exposing exact sites or customer layouts.",
      uses: "Observe · Optimize",
      icon: (
        <svg viewBox="0 0 80 56" fill="none">
          <rect x="6" y="8" width="68" height="40" rx="2" stroke="currentColor" strokeOpacity="0.3" />
          {[0,1,2,3].map(r => [0,1,2,3,4,5,6].map(c => (
            <rect key={`${r}-${c}`} x={10 + c*9} y={12 + r*9} width="6" height="6" fill="currentColor" fillOpacity={0.1 + (r*0.05) + ((c+r)%3)*0.04} />
          )))}
        </svg>
      ),
    },
    {
      who: "EV charging operators",
      n: "II",
      bold: "Charge from sun, not the grid.",
      detail: "Modulate AC charge rate to track real-time PV surplus. Cloud control, no extra hardware. Tariff-aware fallback at night.",
      uses: "Optimize · Control",
      icon: (
        <svg viewBox="0 0 80 56" fill="none">
          <path d="M14 20 Q40 4 66 20" stroke="currentColor" strokeOpacity="0.4" />
          <path d="M14 36 L66 36" stroke="currentColor" strokeOpacity="0.4" strokeDasharray="3 3" />
          <path d="M14 28 Q40 14 66 28" stroke="currentColor" strokeWidth="1.5" />
          <circle cx="40" cy="21" r="2" fill="currentColor" />
        </svg>
      ),
    },
    {
      who: "Battery & VPP operators",
      n: "III",
      bold: "Dispatch on real Singapore prices, not estimates.",
      detail: "Closed-loop battery control with USEP-aware schedules, safety interlocks, and full audit trail.",
      uses: "Optimize · Control",
      icon: (
        <svg viewBox="0 0 80 56" fill="none">
          <rect x="14" y="18" width="52" height="20" rx="2" stroke="currentColor" strokeOpacity="0.4" />
          <rect x="14" y="18" width="36" height="20" rx="2" fill="currentColor" fillOpacity="0.18" />
          <rect x="64" y="22" width="3" height="12" fill="currentColor" fillOpacity="0.5" />
          <line x1="14" y1="44" x2="66" y2="44" stroke="currentColor" strokeOpacity="0.25" strokeDasharray="2 3" />
        </svg>
      ),
    },
    {
      who: "Grid-aware operations",
      n: "IV",
      bold: "Operate inside grid constraints, not against them.",
      detail: "Real-time voltage and frequency overlays stay legible in the public map while protected controls remain behind internal operator surfaces.",
      uses: "Observe · Control",
      icon: (
        <svg viewBox="0 0 80 56" fill="none">
          <path d="M8 28 Q20 12 32 28 T56 28 T80 28" stroke="currentColor" strokeOpacity="0.4" />
          <path d="M8 28 Q20 12 32 28 T56 28" stroke="currentColor" strokeWidth="1.5" />
          <circle cx="32" cy="28" r="2" fill="currentColor" />
          <circle cx="56" cy="28" r="2" fill="currentColor" />
        </svg>
      ),
    },
  ];

  return (
    <section className="sec" id="use-cases" data-screen-label="use-cases">
      <div className="wrap">
        <div className="sec-head">
          <div className="label">03 · USE CASES</div>
          <div>
            <h2>One platform, four operating modes.</h2>
            <p>Whether you run solar, chargers, batteries, or grid-aware operations, Graph composes around your loop without turning the public layer into an asset register.</p>
          </div>
        </div>

        <div className="use-grid">
          {cases.map((c) => (
            <article className="use-card" key={c.n}>
              <div className="use-icon" style={{ color: accent }}>{c.icon}</div>
              <div className="mono use-meta">
                <span>USE CASE · {c.n}</span>
                <span style={{ color: "var(--ink-3)" }}>{c.uses}</span>
              </div>
              <div className="use-who">{c.who}</div>
              <h3 className="use-bold">{c.bold}</h3>
              <p className="use-detail">{c.detail}</p>
              <a href="#contact" className="use-more mono">DISCUSS YOUR LOOP →</a>
            </article>
          ))}
        </div>
      </div>
    </section>
  );
}

// ---------------- Why Graph (moat) ----------------
function WhyGraph({ accent }) {
  const points = [
    {
      n: "I",
      t: "Built from real solar operations, not a deck.",
      d: "Graph is shaped by real operating workflows in Singapore. The public surface stays anonymised; the protected operator layer carries the exact operational detail.",
    },
    {
      n: "II",
      t: "Tropical PV is its own discipline.",
      d: "Heat, monsoon cloud, salt corrosion — Singapore data is messy in ways generic forecasting libraries don't expect. Our models are tuned on it.",
    },
    {
      n: "III",
      t: "One schema across mixed telemetry sources.",
      d: "Most platforms stop at one OEM and bolt the rest on later. Graph normalises mixed field telemetry into one time-series shape that can be redacted safely for public use.",
    },
    {
      n: "IV",
      t: "Closed-loop, not just observability.",
      d: "We write back. Setpoints, dispatch, charge curves. With safety guards and a full audit trail because someone has to sign off when the breaker trips at 02:00.",
    },
  ];

  return (
    <section className="sec sec-tight" id="why" data-screen-label="why">
      <div className="wrap">
        <div className="sec-head">
          <div className="label">06 · WHY GRAPH</div>
          <div>
            <h2>Graph is the energy software you'd build if you ran the assets.</h2>
            <p>The advantage is not louder numbers on a homepage. It is knowing how to expose a credible live network view without leaking private operational detail.</p>
          </div>
        </div>

        <div className="why-grid">
          {points.map((p) => (
            <div className="why-item" key={p.n}>
              <div className="mono why-n">{p.n}</div>
              <div>
                <h4 className="why-t">{p.t}</h4>
                <p className="why-d">{p.d}</p>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ---------------- CTA ----------------
function CTA({ accent }) {
  return (
    <section className="cta" id="contact" data-screen-label="cta">
      <div className="wrap">
        <div className="cta-inner">
          <div className="cta-bg" aria-hidden>
            {/* Subtle topographic contour rings */}
            <svg viewBox="0 0 1200 400" preserveAspectRatio="xMidYMid slice" style={{ width: "100%", height: "100%", position: "absolute", inset: 0 }}>
              <defs>
                <radialGradient id="ctaGlow" cx="0.85" cy="0.5" r="0.6">
                  <stop offset="0%" stopColor={accent} stopOpacity="0.18" />
                  <stop offset="100%" stopColor={accent} stopOpacity="0" />
                </radialGradient>
              </defs>
              <rect width="1200" height="400" fill="url(#ctaGlow)" />
              {[...Array(12)].map((_, i) => (
                <ellipse key={i}
                  cx="1020" cy="200"
                  rx={40 + i * 60} ry={20 + i * 28}
                  fill="none" stroke="rgba(255,255,255,0.05)" strokeWidth="1" />
              ))}
            </svg>
          </div>
          <div className="cta-grid">
            <div>
              <div className="mono cta-eyebrow">07 · GET STARTED</div>
              <h2 className="cta-h">Stand up a privacy-safe live pilot.</h2>
              <p className="cta-p">We can scope a public external view and a protected operator layer together, so your team gets live insight without exposing exact sites, customer identities, or portfolio totals.</p>
              <div className="cta-actions">
                <a className="btn btn-primary" href="#">Talk to our team →</a>
                <a className="btn btn-ghost" href="#">Read the brief (PDF)</a>
              </div>
            </div>
            <div className="cta-side">
              <div className="cta-side-h mono">WHAT YOU GET · WEEK 0–2</div>
              <ol className="cta-list">
                <li><span className="mono">W0</span> Public data boundary design<span className="cta-sub">Define what stays anonymised and what remains internal</span></li>
                <li><span className="mono">W1</span> External network view<span className="cta-sub">Cluster mapping, freshness, and signal health</span></li>
                <li><span className="mono">W2</span> Protected operator layer<span className="cta-sub">Alerts, workflows, and internal telemetry</span></li>
                <li><span className="mono">+30D</span> Optional control loop pilot<span className="cta-sub">EV, battery, or curtailment</span></li>
              </ol>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

window.TrustStrip = TrustStrip;
window.Pillars = Pillars;
window.UseCases = UseCases;
window.WhyGraph = WhyGraph;
window.CTA = CTA;
