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

/* ===========================================================================
   Hero countdown — big synced timer that drives the watch in the hero
   =========================================================================== */

function useCountdown(start = 90, paused = false) {
  const [t, setT] = useState(start);
  const ref = useRef();
  useEffect(() => {
    if (paused) return;
    let last = performance.now();
    let id;
    const tick = (now) => {
      const dt = (now - last) / 1000;
      last = now;
      setT(prev => {
        let next = prev - dt;
        if (next < -3) next = start; // loop
        return next;
      });
      id = requestAnimationFrame(tick);
    };
    id = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(id);
  }, [paused, start]);
  // expose reset
  ref.current = () => setT(start);
  return [t, ref.current];
}

function HeroCountdownStage({ start = 90 }) {
  const [paused, setPaused] = useState(false);
  const [t, reset] = useCountdown(start, paused);
  // clamp for display
  const tClamped = Math.max(0, t);
  const showPill = window.innerWidth > 640;

  return (
    <div className="hero-device-stage">
      {/* Decorative compass arc behind */}
      <svg
        width="520"
        height="520"
        style={{
          position: "absolute",
          right: "-80px",
          top: "50%",
          transform: "translateY(-50%)",
          opacity: 0.35,
          pointerEvents: "none"
        }}
      >
        <circle cx="260" cy="260" r="240" fill="none" stroke="rgba(70,197,255,0.18)" strokeWidth="1" strokeDasharray="2 6" />
        <circle cx="260" cy="260" r="200" fill="none" stroke="rgba(70,197,255,0.12)" strokeWidth="1" />
        <circle cx="260" cy="260" r="160" fill="none" stroke="rgba(70,197,255,0.08)" strokeWidth="1" />
        {/* Tick marks */}
        {Array.from({ length: 36 }).map((_, i) => {
          const a = (i * 10) * Math.PI / 180;
          const r1 = 240, r2 = 232;
          const major = i % 9 === 0;
          return (
            <line key={i}
              x1={260 + Math.sin(a) * r1} y1={260 - Math.cos(a) * r1}
              x2={260 + Math.sin(a) * (major ? 220 : r2)} y2={260 - Math.cos(a) * (major ? 220 : r2)}
              stroke={major ? "rgba(70,197,255,0.5)" : "rgba(70,197,255,0.2)"}
              strokeWidth={major ? 1.25 : 0.75}
            />
          );
        })}
      </svg>
      <div>
        <WatchFrame scale={1.35}>
          <WatchPreStart seconds={tClamped} />
        </WatchFrame>
      </div>
      {/* Caption pill — hidden on mobile to avoid overlapping watch */}
      {showPill && <div className="hero-countdown-pill" style={{
        position: "absolute",
        bottom: 0,
        left: "50%",
        transform: "translateX(-50%)",
        display: "inline-flex",
        alignItems: "center",
        gap: 10,
        padding: "8px 14px",
        background: "rgba(0,0,0,0.45)",
        border: "1px solid rgba(255,255,255,0.12)",
        backdropFilter: "blur(20px)",
        borderRadius: 999,
        fontSize: 12,
        fontFamily: "Archivo, system-ui, sans-serif",
        color: "rgba(244,247,250,0.85)",
        letterSpacing: "-0.005em"
      }}>
        <span style={{
          width: 6, height: 6, borderRadius: 999, background: "#FF3B47",
          boxShadow: "0 0 8px #FF3B47", animation: "pulse 1.2s ease-in-out infinite"
        }} />
        Live pre-start sequence — T-{Math.max(0, Math.floor(tClamped))}s
        <button
          onClick={() => { setPaused(p => !p); }}
          style={{
            border: "1px solid rgba(255,255,255,0.18)",
            background: "transparent",
            color: "#fff",
            fontSize: 11,
            fontWeight: 500,
            padding: "3px 10px",
            borderRadius: 999,
            cursor: "pointer",
            marginLeft: 6
          }}
        >{paused ? "Play" : "Pause"}</button>
        <button
          onClick={() => reset && reset()}
          style={{
            border: "none",
            background: "transparent",
            color: "#46C5FF",
            fontSize: 11,
            fontWeight: 500,
            padding: "3px 4px",
            cursor: "pointer"
          }}
        >Reset</button>
      </div>}
    </div>
  );
}

/* ===========================================================================
   Line bias diagram — committee boat / pin / line / favored end indicator
   =========================================================================== */

function LineBiasDiagram() {
  return (
    <div className="diagram-frame" style={{ aspectRatio: "1.1 / 1", minHeight: 460 }}>
      <div className="diagram-readout">
        <div className="item">
          <div className="lab">Bias</div>
          <div className="val signal-lift">PIN +8°</div>
        </div>
        <div className="item">
          <div className="lab">Wind</div>
          <div className="val">045°</div>
        </div>
        <div className="item">
          <div className="lab">Line</div>
          <div className="val">28m</div>
        </div>
      </div>

      <svg viewBox="0 0 480 460" width="100%" height="100%" style={{ position: "relative", zIndex: 1 }}>
        {/* Dashed laylines from each end up to windward mark */}
        <line x1="100" y1="350" x2="240" y2="155" stroke="#46C5FF" strokeWidth="1" strokeDasharray="4 6" opacity="0.45" />
        <line x1="385" y1="350" x2="240" y2="155" stroke="#46C5FF" strokeWidth="1" strokeDasharray="4 6" opacity="0.45" />

        {/* Start line */}
        <line x1="80" y1="350" x2="400" y2="350" stroke="#3CE0A1" strokeWidth="2.5" />

        {/* Windward mark */}
        <g transform="translate(240, 148)">
          <circle cx="0" cy="0" r="9" fill="none" stroke="#FFB300" strokeWidth="1.75" />
          <circle cx="0" cy="0" r="3" fill="#FFB300" />
          <text x="0" y="-18" fontSize="10" fontFamily="Archivo" fontWeight="700" textAnchor="middle" fill="#FFB300" letterSpacing="1.5">WINDWARD</text>
        </g>

        {/* Pin end — favored */}
        <g transform="translate(80, 350)">
          <text x="0" y="-52" fontSize="9" fontFamily="Archivo" fontWeight="700" letterSpacing="1.5" textAnchor="middle" fill="#3CE0A1">FAVORED</text>
          <circle cx="0" cy="-14" r="26" fill="rgba(60,224,161,0.14)" stroke="#3CE0A1" strokeWidth="1.25" strokeDasharray="3 3" />
          <polygon points="0,-28 -9,-8 9,-8" fill="#FF3B47" />
          <text x="0" y="22" fontSize="10" fontFamily="Archivo" fontWeight="700" textAnchor="middle" fill="#FF3B47" letterSpacing="1">PIN</text>
        </g>

        {/* Boat end (right) */}
        <g transform="translate(400, 350)">
          <rect x="-22" y="-20" width="44" height="16" rx="3" fill="#2C2C2F" stroke="rgba(255,255,255,0.18)" strokeWidth="1.25" />
          <rect x="-14" y="-30" width="28" height="12" rx="2" fill="#2C2C2F" stroke="rgba(255,255,255,0.14)" strokeWidth="1" />
          <text x="0" y="22" fontSize="10" fontFamily="Archivo" fontWeight="700" textAnchor="middle" fill="#A9B7C5" letterSpacing="1">BOAT</text>
        </g>

        {/* Boat position + heading arrow — pointing left toward favored pin end */}
        <g transform="translate(200, 408) rotate(-90)">
          <polygon points="-8,12 0,-16 8,12" fill="#46C5FF" />
        </g>

        {/* DTL readout */}
        <text x="240" y="376" fontSize="10" fontFamily="Chivo Mono, monospace" fontWeight="700" fill="#3CE0A1" textAnchor="middle">7m</text>
      </svg>
    </div>
  );
}

/* ===========================================================================
   VMG / Compass big stage (used in features section)
   =========================================================================== */

function VmgCompassStage() {
  // Wind from north → no-sail zone centered at top, matching actual app
  const windDir = 0;
  const noSailHalf = 43; // ~86° total no-sail zone (app shows 316°–042°)
  const size = 360;
  const cx = size / 2, cy = size / 2;
  const r = size / 2 - 16;

  const ticks = [];
  for (let i = 0; i < 72; i++) {
    const a = (i * 5) * Math.PI / 180;
    const major = i % 18 === 0;
    const med = i % 6 === 0;
    const inner = r - (major ? 14 : med ? 8 : 4);
    ticks.push(
      <line key={i}
        x1={cx + Math.sin(a) * r} y1={cy - Math.cos(a) * r}
        x2={cx + Math.sin(a) * inner} y2={cy - Math.cos(a) * inner}
        stroke={major ? "#A9B7C5" : med ? "#3D4D5E" : "#28282B"}
        strokeWidth={major ? 1.5 : 1}
      />
    );
  }

  const arcR = r - 28;
  const leftRad = (windDir - noSailHalf) * Math.PI / 180;  // 317°
  const rightRad = (windDir + noSailHalf) * Math.PI / 180; // 043°
  const x1 = cx + Math.sin(leftRad) * arcR;
  const y1 = cy - Math.cos(leftRad) * arcR;
  const x2 = cx + Math.sin(rightRad) * arcR;
  const y2 = cy - Math.cos(rightRad) * arcR;

  // Pill label positions at outer ring edge
  const pillR = r - 4;
  const pill1x = Math.round(cx + Math.sin(leftRad) * pillR);
  const pill1y = Math.round(cy - Math.cos(leftRad) * pillR);
  const pill2x = Math.round(cx + Math.sin(rightRad) * pillR);
  const pill2y = Math.round(cy - Math.cos(rightRad) * pillR);

  return (
    <div className="vmg-stage">
      {/* Top readouts */}
      <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 16, gap: 12 }}>
        <div>
          <div style={{ fontSize: 10, fontWeight: 600, letterSpacing: "0.16em", color: "#6F7E8E", textTransform: "uppercase" }}>Speed</div>
          <div style={{ fontFamily: "Chivo Mono, monospace", fontWeight: 700, fontSize: 32, color: "#3CE0A1", letterSpacing: "-0.02em", textShadow: "0 0 18px rgba(60,224,161,0.3)" }}>
            7.7<span style={{ fontSize: 14, color: "#6F7E8E", marginLeft: 4 }}>mph</span>
          </div>
        </div>
        <div style={{ textAlign: "center" }}>
          <div style={{ fontSize: 10, fontWeight: 600, letterSpacing: "0.16em", color: "#6F7E8E", textTransform: "uppercase" }}>VMG</div>
          <div style={{ fontFamily: "Chivo Mono, monospace", fontWeight: 700, fontSize: 32, color: "#FFB300", letterSpacing: "-0.02em" }}>
            7.7<span style={{ fontSize: 14, color: "#6F7E8E", marginLeft: 4 }}>mph</span>
          </div>
        </div>
        <div style={{ textAlign: "right" }}>
          <div style={{ fontSize: 10, fontWeight: 600, letterSpacing: "0.16em", color: "#6F7E8E", textTransform: "uppercase" }}>Layline</div>
          <div style={{ fontFamily: "Chivo Mono, monospace", fontWeight: 700, fontSize: 32, color: "#46C5FF", letterSpacing: "-0.02em" }}>
            0:42
          </div>
        </div>
      </div>

      <div style={{ display: "flex", justifyContent: "center" }}>
        <svg width={size} height={size}>
          {/* Outer ring */}
          <circle cx={cx} cy={cy} r={r} fill="none" stroke="rgba(255,255,255,0.08)" strokeWidth="1" />
          {ticks}
          <circle cx={cx} cy={cy} r={arcR} fill="none" stroke="rgba(70,197,255,0.05)" strokeWidth="1" />

          {/* No-sail zone — dark maroon fill matching the app */}
          <path
            d={`M ${cx} ${cy} L ${x1} ${y1} A ${arcR} ${arcR} 0 0 1 ${x2} ${y2} Z`}
            fill="rgba(110,18,18,0.65)"
            stroke="#FF3B47"
            strokeWidth="1"
            strokeDasharray="3 3"
          />

          {/* Dashed blue layline lines from center to pill positions */}
          <line x1={cx} y1={cy} x2={pill1x} y2={pill1y} stroke="#46C5FF" strokeWidth="1" strokeDasharray="3 4" opacity="0.65" />
          <line x1={cx} y1={cy} x2={pill2x} y2={pill2y} stroke="#46C5FF" strokeWidth="1" strokeDasharray="3 4" opacity="0.65" />

          {/* Layline angle pill labels — key feature from the app */}
          {[[pill1x, pill1y, "316°"], [pill2x, pill2y, "042°"]].map(([px, py, label]) => (
            <g key={label} transform={`translate(${px}, ${py})`}>
              <rect x="-26" y="-13" width="52" height="26" rx="13" fill="#0B1E2E" />
              <text x="0" y="5" fontSize="13" fontFamily="Chivo Mono, monospace" fontWeight="700"
                textAnchor="middle" fill="#46C5FF" fontVariantNumeric="tabular-nums">{label}</text>
            </g>
          ))}

          {/* Wind dot at top of ring (wind from north) */}
          <circle cx={cx} cy={cy - r} r="3.5" fill="#46C5FF" />

          {/* Heading indicator — 6-point nav pointer: tip, flared sides, V-notch base */}
          <g transform={`translate(${cx}, ${cy})`}>
            <polygon points="0,-52 24,20 0,4 -24,20" fill="#46C5FF" />
          </g>

          {/* Cardinals */}
          {["N", "E", "S", "W"].map((c, i) => {
            const a = (i * 90) * Math.PI / 180;
            const tr = r - 30;
            return <text key={c}
              x={cx + Math.sin(a) * tr}
              y={cy - Math.cos(a) * tr + 5}
              fontSize="14" fontFamily="Archivo" fontWeight="700"
              textAnchor="middle"
              fill={c === "N" ? "#F4F7FA" : "#6F7E8E"}
            >{c}</text>;
          })}

          {/* HDG readout */}
          <text x={cx} y={cy + 58} fontSize="11" fontFamily="Archivo" fontWeight="600" letterSpacing="3" textAnchor="middle" fill="#6F7E8E">HDG</text>
          <text x={cx} y={cy + 82} fontSize="22" fontFamily="Chivo Mono, monospace" fontWeight="700" textAnchor="middle" fill="#F4F7FA" letterSpacing="-0.02em">000°</text>
        </svg>
      </div>

      {/* Bottom stats strip */}
      <div style={{
        marginTop: 24,
        display: "grid",
        gridTemplateColumns: "repeat(4, 1fr)",
        gap: 8,
        paddingTop: 16,
        borderTop: "1px solid rgba(255,255,255,0.06)"
      }}>
        {[
          { lab: "AVG", val: "8.6", u: "mph", c: "#46C5FF" },
          { lab: "MAX", val: "9.9", u: "mph", c: "#FFB300" },
          { lab: "TWA", val: "42°", u: "", c: "#F4F7FA" },
          { lab: "POLAR", val: "92%", u: "", c: "#3CE0A1" }
        ].map(s => (
          <div key={s.lab}>
            <div style={{ fontSize: 9, fontWeight: 600, letterSpacing: "0.14em", color: "#6F7E8E", textTransform: "uppercase" }}>{s.lab}</div>
            <div style={{ fontFamily: "Chivo Mono, monospace", fontWeight: 700, fontSize: 18, color: s.c, marginTop: 3, fontVariantNumeric: "tabular-nums slashed-zero", letterSpacing: "-0.02em" }}>
              {s.val}<span style={{ fontSize: 11, color: "#6F7E8E", marginLeft: 2 }}>{s.u}</span>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ===========================================================================
   Three-watch storyboard (countdown sequence)
   =========================================================================== */

function PreStartStoryboard() {
  return (
    <div className="prestart-storyboard-wrap">
    <div style={{
      display: "grid",
      gridTemplateColumns: "repeat(3, 1fr)",
      gap: 24,
      padding: 12,
      minWidth: 560
    }}>
      {[
        { sec: 180, lab: "T-3:00", note: "Sync" },
        { sec: 8, lab: "T-0:08", note: "Burn" },
        { sec: -1, lab: "OCS", note: "Bear away" }
      ].map((s) => (
        <div key={s.lab} style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 12 }}>
          <WatchFrame scale={0.78}>
            <WatchPreStart seconds={s.sec} />
          </WatchFrame>
          <div style={{
            fontFamily: "Chivo Mono, monospace",
            fontSize: 13,
            fontWeight: 700,
            color: s.sec < 0 ? "#FF3B47" : s.sec <= 10 ? "#FFB300" : "#F4F7FA",
            letterSpacing: "-0.01em"
          }}>{s.lab}</div>
          <div style={{ fontSize: 11, color: "#6F7E8E", letterSpacing: "0.12em", textTransform: "uppercase", fontWeight: 600 }}>{s.note}</div>
        </div>
      ))}
    </div>
    </div>
  );
}

Object.assign(window, {
  HeroCountdownStage,
  LineBiasDiagram,
  VmgCompassStage,
  PreStartStoryboard
});
