// Main React components for M1A1 site.
// Loads in <script type="text/babel"> context.

const { useState, useEffect, useRef, useMemo } = React;

// ==================== NAV ====================
function Nav() {
  const [time, setTime] = useState("");
  useEffect(() => {
    const fmt = () => {
      const d = new Date();
      const hh = String(d.getUTCHours()).padStart(2, "0");
      const mm = String(d.getUTCMinutes()).padStart(2, "0");
      const ss = String(d.getUTCSeconds()).padStart(2, "0");
      setTime(`${hh}:${mm}:${ss}Z`);
    };
    fmt();
    const i = setInterval(fmt, 1000);
    return () => clearInterval(i);
  }, []);
  return (
    <nav className="nav">
      <a className="nav-logo" href="#top">
        <img src="m1a1-logo.png" alt="M1A1 Construction Services" style={{height: "36px", width: "auto"}} />
      </a>
      <ul className="nav-links">
        <li><a href="#capabilities">Capabilities</a></li>
        <li><a href="#performance">Past Performance</a></li>
        <li><a href="#about">About</a></li>
        <li><a href="#origin">Story</a></li>
        <li><a href="#leadership">Command</a></li>
        <li><a href="#careers">Careers</a></li>
        <li><a href="#contact">Contact</a></li>
      </ul>
      <div className="nav-cta">
        <span className="nav-time">SITREP {time}</span>
        <a href="#contact" className="btn primary" style={{padding: "10px 18px"}}>
          Request Intel <span className="arrow" />
        </a>
      </div>
    </nav>
  );
}

// ==================== HERO with animated radar canvas ====================
function HeroRadar({ active }) {
  const canvasRef = useRef(null);
  useEffect(() => {
    if (!active) return;
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext("2d");
    let raf;
    const resize = () => {
      const dpr = window.devicePixelRatio || 1;
      canvas.width = canvas.clientWidth * dpr;
      canvas.height = canvas.clientHeight * dpr;
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
    };
    resize();
    window.addEventListener("resize", resize);

    // Persistent blips + pings created when swept
    const blips = [
      { a: 0.30, r: 0.62, id: "TX", label: "HOUSTON" },
      { a: 1.05, r: 0.48, id: "CA", label: "SAC-METRO" },
      { a: 1.95, r: 0.78, id: "FL", label: "JAX" },
      { a: 2.70, r: 0.35, id: "AZ", label: "TUCSON" },
      { a: 3.45, r: 0.58, id: "VA", label: "SPRINGFIELD" },
      { a: 4.10, r: 0.72, id: "WA", label: "TACOMA" },
      { a: 4.75, r: 0.28, id: "CO", label: "DENVER" },
      { a: 5.40, r: 0.68, id: "GA", label: "ATL" },
      { a: 5.90, r: 0.42, id: "TX2", label: "DFW" },
    ];
    const pings = []; // {x, y, t0, label}
    let lastAngle = 0;

    let t0 = performance.now();
    const draw = (t) => {
      const w = canvas.clientWidth, h = canvas.clientHeight;
      ctx.clearRect(0, 0, w, h);
      // Radar positioned right side, but BIGGER — dominates the right half
      const cx = w * 0.78, cy = h * 0.48;
      const R = Math.min(w * 0.42, h * 0.48);

      const elapsed = (t - t0) / 1000;
      const angle = (elapsed * 0.55) % (Math.PI * 2);

      // Faint fill inside scope
      const bgGrad = ctx.createRadialGradient(cx, cy, 0, cx, cy, R);
      bgGrad.addColorStop(0, "rgba(224, 168, 74, 0.06)");
      bgGrad.addColorStop(1, "rgba(224, 168, 74, 0)");
      ctx.fillStyle = bgGrad;
      ctx.beginPath(); ctx.arc(cx, cy, R, 0, Math.PI * 2); ctx.fill();

      // Concentric range rings (more of them, brighter)
      ctx.strokeStyle = "rgba(224, 168, 74, 0.22)";
      ctx.lineWidth = 1;
      for (let i = 1; i <= 5; i++) {
        const r = (R / 5) * i;
        ctx.beginPath(); ctx.arc(cx, cy, r, 0, Math.PI * 2); ctx.stroke();
      }
      // Outer ring accent
      ctx.strokeStyle = "rgba(224, 168, 74, 0.55)";
      ctx.lineWidth = 1.5;
      ctx.beginPath(); ctx.arc(cx, cy, R, 0, Math.PI * 2); ctx.stroke();

      // Tick marks every 10deg
      ctx.strokeStyle = "rgba(224, 168, 74, 0.35)";
      ctx.lineWidth = 0.8;
      for (let i = 0; i < 36; i++) {
        const a = (i * Math.PI * 2) / 36;
        const isMajor = i % 3 === 0;
        const inner = R * (isMajor ? 0.96 : 0.98);
        ctx.beginPath();
        ctx.moveTo(cx + Math.cos(a) * inner, cy + Math.sin(a) * inner);
        ctx.lineTo(cx + Math.cos(a) * R, cy + Math.sin(a) * R);
        ctx.stroke();
      }

      // Crosshair (subtle)
      ctx.strokeStyle = "rgba(224, 168, 74, 0.18)";
      ctx.lineWidth = 0.8;
      ctx.beginPath();
      ctx.moveTo(cx - R, cy); ctx.lineTo(cx + R, cy);
      ctx.moveTo(cx, cy - R); ctx.lineTo(cx, cy + R);
      ctx.stroke();

      // Cardinal labels
      ctx.fillStyle = "rgba(224, 168, 74, 0.45)";
      ctx.font = "10px 'JetBrains Mono', monospace";
      ctx.textAlign = "center"; ctx.textBaseline = "middle";
      ctx.fillText("N", cx, cy - R - 10);
      ctx.fillText("S", cx, cy + R + 10);
      ctx.fillText("E", cx + R + 10, cy);
      ctx.fillText("W", cx - R - 10, cy);

      // Sweep cone (BIGGER, brighter)
      const grad = ctx.createConicGradient
        ? ctx.createConicGradient(angle - Math.PI / 2, cx, cy)
        : null;
      if (grad) {
        grad.addColorStop(0, "rgba(224, 168, 74, 0.55)");
        grad.addColorStop(0.08, "rgba(224, 168, 74, 0.3)");
        grad.addColorStop(0.25, "rgba(224, 168, 74, 0)");
        grad.addColorStop(1, "rgba(224, 168, 74, 0)");
        ctx.fillStyle = grad;
        ctx.beginPath();
        ctx.moveTo(cx, cy);
        ctx.arc(cx, cy, R, 0, Math.PI * 2);
        ctx.fill();
      }

      // Sweep line
      ctx.strokeStyle = "rgba(245, 194, 107, 1)";
      ctx.lineWidth = 2;
      ctx.shadowColor = "rgba(245, 194, 107, 0.8)";
      ctx.shadowBlur = 12;
      ctx.beginPath();
      ctx.moveTo(cx, cy);
      ctx.lineTo(cx + Math.cos(angle) * R, cy + Math.sin(angle) * R);
      ctx.stroke();
      ctx.shadowBlur = 0;

      // Center dot
      ctx.fillStyle = "rgba(245, 194, 107, 1)";
      ctx.beginPath(); ctx.arc(cx, cy, 3, 0, Math.PI * 2); ctx.fill();
      ctx.strokeStyle = "rgba(245, 194, 107, 0.4)";
      ctx.lineWidth = 1;
      ctx.beginPath(); ctx.arc(cx, cy, 8, 0, Math.PI * 2); ctx.stroke();

      // Detect sweep crossing each blip — spawn ping
      blips.forEach(b => {
        const crossed = (lastAngle < b.a && angle >= b.a) ||
                        (lastAngle > angle && (b.a > lastAngle || b.a <= angle)); // wrap
        if (crossed) {
          pings.push({
            x: cx + Math.cos(b.a) * R * b.r,
            y: cy + Math.sin(b.a) * R * b.r,
            t0: t,
            label: b.label,
          });
        }
      });
      lastAngle = angle;

      // Draw blips (always visible, brighter when recently swept)
      blips.forEach(b => {
        const bx = cx + Math.cos(b.a) * R * b.r;
        const by = cy + Math.sin(b.a) * R * b.r;
        const angDiff = (angle - b.a + Math.PI * 2) % (Math.PI * 2);
        const freshness = Math.max(0, 1 - angDiff / (Math.PI * 1.2));
        // Glow
        const g = ctx.createRadialGradient(bx, by, 0, bx, by, 12);
        g.addColorStop(0, `rgba(245, 194, 107, ${0.5 + freshness * 0.4})`);
        g.addColorStop(1, "rgba(245, 194, 107, 0)");
        ctx.fillStyle = g;
        ctx.beginPath(); ctx.arc(bx, by, 12, 0, Math.PI * 2); ctx.fill();
        // Core
        ctx.fillStyle = `rgba(245, 220, 150, ${0.7 + freshness * 0.3})`;
        ctx.beginPath(); ctx.arc(bx, by, 2.5 + freshness * 1.5, 0, Math.PI * 2); ctx.fill();
      });

      // Draw pings — expanding rings after sweep crosses
      for (let i = pings.length - 1; i >= 0; i--) {
        const p = pings[i];
        const age = (t - p.t0) / 1000;
        if (age > 1.8) { pings.splice(i, 1); continue; }
        const pr = age * 42;
        const pa = Math.max(0, 1 - age / 1.8);
        ctx.strokeStyle = `rgba(245, 194, 107, ${pa * 0.7})`;
        ctx.lineWidth = 1.5;
        ctx.beginPath(); ctx.arc(p.x, p.y, pr, 0, Math.PI * 2); ctx.stroke();
        // Label
        if (age < 1.2) {
          ctx.fillStyle = `rgba(245, 194, 107, ${pa})`;
          ctx.font = "9px 'JetBrains Mono', monospace";
          ctx.textAlign = "left"; ctx.textBaseline = "middle";
          ctx.fillText(`◆ ${p.label}`, p.x + 10, p.y - 10);
        }
      }

      raf = requestAnimationFrame(draw);
    };
    raf = requestAnimationFrame(draw);
    return () => { cancelAnimationFrame(raf); window.removeEventListener("resize", resize); };
  }, [active]);

  return <canvas ref={canvasRef} className="hero-radar" />;
}

function Hero({ heroAnimated }) {
  const [counts, setCounts] = useState({ projects: 0, states: 0, value: 0 });
  useEffect(() => {
    let raf;
    const start = () => {
      const all = window.PROJECT_DATA || [];
      if (all.length === 0) {
        // Data not ready yet — retry shortly
        setTimeout(start, 100);
        return;
      }
      const totalValue = all.reduce((s, p) => s + (p.contractValue || 0), 0);
      const stateSet = new Set(all.map(p => p.state));
      const targets = {
        projects: all.length,
        states: stateSet.size,
        value: Math.round(totalValue / 100000) / 10, // in $M
      };
      const dur = 1600;
      const t0 = performance.now();
      const tick = (t) => {
        const p = Math.min(1, (t - t0) / dur);
        const e = 1 - Math.pow(1 - p, 3);
        setCounts({
          projects: Math.round(targets.projects * e),
          states: Math.round(targets.states * e),
          value: Math.round(targets.value * e * 10) / 10,
        });
        if (p < 1) raf = requestAnimationFrame(tick);
      };
      raf = requestAnimationFrame(tick);
    };
    start();
    return () => { if (raf) cancelAnimationFrame(raf); };
  }, []);

  return (
    <section className="hero" id="top">
      <div className="hero-bg-image" />
      <HeroRadar active={heroAnimated} />

      <div className="hero-topline">
        <div className="left">
          <span>◆ SECURE · CLEARED · READY</span>
          <span>SDVOSB · CVE VERIFIED</span>
          <span>UNION · LOCAL 123</span>
        </div>
        <div className="right">
          <span className="coord">29.7604° N / 95.3698° W</span>
          <span>HQ HOUSTON · TX</span>
        </div>
      </div>

      <div className="hero-content">
        <div className="hero-kicker">
          ★ Service-Disabled Veteran-Owned Small Business
        </div>
        <h1 className="hero-title">
          <span className="line">Built by</span>
          <span className="line accent">Marines.</span>
          <span className="line">Trusted by</span>
          <span className="line">America.</span>
        </h1>
        <p className="hero-sub">
          Federal-grade roofing, waterproofing, and building envelope services for government,
          military, and commercial clients. National coverage. Service-Disabled Veteran-Owned.
        </p>
        <div className="hero-actions">
          <a href="#contact" className="btn primary">Request Assessment <span className="arrow" /></a>
          <a href="#capabilities" className="btn">Capabilities Brief</a>
        </div>
      </div>

      <div className="hero-readout">
        <div className="stat">
          <div className="v">{counts.projects}</div>
          <div className="l">Projects Logged</div>
        </div>
        <div className="stat">
          <div className="v">{counts.states}</div>
          <div className="l">States + Territories</div>
        </div>
        <div className="stat">
          <div className="v">${counts.value}M</div>
          <div className="l">Past Performance</div>
        </div>
        <div className="stat">
          <div className="v">SDVOSB</div>
          <div className="l">CVE Verified</div>
        </div>
      </div>
    </section>
  );
}

// ==================== CAPABILITIES ====================
function Capabilities() {
  const caps = [
    { n: "01", title: "Roofing Systems", desc: "Full-scale commercial and federal roofing — tear-off, re-roof, inspection, repair. TPO, modified bitumen, standing-seam metal, built-up, and historic restoration." },
    { n: "02", title: "Waterproofing", desc: "Advanced membrane and coating systems engineered to protect structures from moisture damage, extend service life, and meet federal spec." },
    { n: "03", title: "Reflective Coatings", desc: "High-albedo silicone and elastomeric roof coatings for desert and southern climates. Heat-load reduction with UV-resistant surface systems." },
    { n: "04", title: "Federal Subcontracting", desc: "SDVOSB set-aside fulfillment for primes on federal contracts. SAM-registered, CVE-verified, cleared and ready." },
  ];
  return (
    <section className="section" id="capabilities">
      <div className="container">
        <div className="sh">
          <div className="num">01 / MISSION CAPABILITIES</div>
          <h2>Full Building Envelope Solutions</h2>
          <div className="meta">ROOFING · ENVELOPE · WATERPROOFING</div>
        </div>
      </div>
      <div className="container">
        <div className="caps">
          {caps.map(c => (
            <div className="cap" key={c.n}>
              <div className="n">{c.n}</div>
              <h3>{c.title}</h3>
              <p>{c.desc}</p>
              <span className="recon">Recon Details</span>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Nav, Hero, Capabilities });
