/* ===================================================================
   GLOBALSTAFF — Hero
   Right side: an architectural blueprint of a stone wall that draws
   itself, then transforms into a finished stone installation.
   Narrative: Concept → Planning → Execution → Result.
   =================================================================== */

/* deterministic coursed-ashlar block layout (no photography) */
const STONE_WALL = (() => {
  // pseudo-random with fixed seed for stable layout
  let s = 20260612;
  const rnd = () => {
    s = (s * 1664525 + 1013904223) % 4294967296;
    return s / 4294967296;
  };
  const X0 = 36, X1 = 524, Y0 = 60, Y1 = 540;
  const tones = ["#D9D2C5", "#CFC6B6", "#E1DBCF", "#C9C0AF", "#D4CCBD", "#DED8CA", "#C5BCAB", "#D0C8B8"];
  const rows = [];
  let y = Y0;
  let r = 0;
  while (y < Y1 - 20) {
    const h = 44 + Math.round(rnd() * 30);
    const hh = Math.min(h, Y1 - y);
    // split row into blocks
    const blocks = [];
    let x = X0;
    // offset start so courses break joints
    while (x < X1 - 20) {
      let w = 70 + Math.round(rnd() * 90);
      if (x + w > X1) w = X1 - x;
      blocks.push({ x, y, w, h: hh, tone: tones[(r + blocks.length) % tones.length] });
      x += w;
    }
    rows.push(blocks);
    y += hh;
    r++;
  }
  return rows.flat();
})();

function HeroStone() {
  // 0 board · 1 blueprint lines · 2 block outlines · 3 material · 4 finished
  const [phase, setPhase] = useState(0);
  const wrapRef = useRef(null);

  useEffect(() => {
    let timers = [];
    const run = () => {
      timers.forEach(clearTimeout);
      timers = [];
      setPhase(0);
      timers.push(setTimeout(() => setPhase(1), 1100));
      timers.push(setTimeout(() => setPhase(2), 2900));
      timers.push(setTimeout(() => setPhase(3), 4700));
      timers.push(setTimeout(() => setPhase(4), 6500));
    };
    let started = false;
    const begin = () => { if (started) return; started = true; run(); };
    const unsub = watchInView(wrapRef.current, begin, 0.2);
    timers.push(setTimeout(begin, 600));
    const loop = setInterval(() => { run(); }, 16000);
    return () => { timers.forEach(clearTimeout); clearInterval(loop); if (unsub) unsub(); };
  }, []);

  const STAGES = ["Drawing board", "Blueprint", "Stone layout", "Material", "Finished"];
  // course separators (horizontal) for the planning stage
  const courseYs = [...new Set(STONE_WALL.map((b) => b.y))].filter((y) => y > 60);

  return (
    <div className="hero-stone" ref={wrapRef} data-phase={phase}>
      <svg viewBox="0 0 560 600" width="100%" height="100%" preserveAspectRatio="xMidYMid meet" aria-hidden="true">
        <defs>
          <pattern id="hsgrid" width="28" height="28" patternUnits="userSpaceOnUse">
            <path d="M28 0H0V28" fill="none" stroke="#C7BFAF" strokeWidth="0.6" />
          </pattern>
          <linearGradient id="sheen" x1="0" y1="0" x2="1" y2="1">
            <stop offset="0" stopColor="#fff" stopOpacity="0.5" />
            <stop offset="0.5" stopColor="#fff" stopOpacity="0" />
          </linearGradient>
        </defs>

        {/* technical grid removed per request — board stays clean */}

        {/* ---- STAGE 1: drawing-board references (coord frame, ticks, labels) ---- */}
        <g style={{ opacity: phase >= 4 ? 0.16 : 0.62, transition: "opacity 700ms ease" }}>
          <g stroke="#264653" strokeWidth="1">
            <line x1="36" y1="44" x2="36" y2="556" strokeDasharray="2 6" />
            <line x1="36" y1="44" x2="524" y2="44" strokeDasharray="2 6" />
            {/* measurement ticks down the left rule */}
            {[100, 160, 220, 280, 340, 400, 460, 520].map((y) => (
              <line key={y} x1="30" y1={y} x2="36" y2={y} />
            ))}
            {/* top ruler ticks */}
            {[100, 160, 220, 280, 340, 400, 460].map((x) => (
              <line key={x} x1={x} y1="38" x2={x} y2="44" />
            ))}
          </g>
          <text x="42" y="34" className="hs-coord">ELEV · NATURAL STONE WALL · 1:20</text>
          <text x="500" y="34" textAnchor="end" className="hs-coord" style={{ fontSize: 9 }}>N 59°·24°E</text>
        </g>

        {/* registration crosshairs at the corners (board) */}
        <g stroke="#D99041" strokeWidth="1" opacity={phase === 0 ? 0.8 : 0.25} style={{ transition: "opacity 600ms ease" }}>
          <path d="M58 78 h12 M64 72 v12" />
          <path d="M490 522 h12 M496 516 v12" />
        </g>

        {/* ---- STONE FILLS — stage 3 (material) ---- */}
        <g>
          {STONE_WALL.map((b, i) => (
            <rect
              key={"f" + i}
              x={b.x + 1.5} y={b.y + 1.5} width={b.w - 3} height={b.h - 3}
              fill={b.tone}
              style={{
                opacity: phase >= 3 ? 1 : 0,
                transition: `opacity 620ms cubic-bezier(0.22,1,0.36,1) ${(i % 14) * 70}ms`,
              }}
            />
          ))}
          {/* facet shading — stage 4 (finished) */}
          {STONE_WALL.map((b, i) => (
            <path
              key={"s" + i}
              d={`M${b.x + 1.5} ${b.y + b.h - 1.5} L${b.x + b.w - 3} ${b.y + b.h - 1.5}`}
              stroke="rgba(120,108,86,0.30)" strokeWidth="2"
              style={{ opacity: phase >= 4 ? 1 : 0, transition: `opacity 500ms ease ${(i % 10) * 50}ms` }}
            />
          ))}
        </g>

        {/* ---- STAGE 2: course separators draw first ---- */}
        <g fill="none" stroke="#264653" strokeWidth="1" strokeLinecap="round">
          {courseYs.map((y, i) => (
            <line
              key={"c" + i}
              x1="36" y1={y} x2="524" y2={y}
              pathLength="1" strokeDasharray="1"
              strokeDashoffset={phase >= 1 ? 0 : 1}
              style={{ transition: `stroke-dashoffset 600ms ease ${i * 90}ms`, opacity: phase >= 4 ? 0.4 : 0.8 }}
            />
          ))}
        </g>

        {/* ---- BLOCK OUTLINES — stage 2 (stone layout) ---- */}
        <g fill="none" strokeLinejoin="round" strokeLinecap="round">
          {STONE_WALL.map((b, i) => (
            <rect
              key={"o" + i}
              x={b.x + 1.5} y={b.y + 1.5} width={b.w - 3} height={b.h - 3}
              pathLength="1"
              stroke={phase >= 4 ? "rgba(120,108,86,0.55)" : "#264653"}
              strokeWidth={phase >= 4 ? 1 : 1.3}
              strokeDasharray="1"
              strokeDashoffset={phase >= 2 ? 0 : 1}
              style={{ transition: `stroke-dashoffset 640ms ease ${(i % 16) * 60}ms, stroke 600ms ease` }}
            />
          ))}
        </g>

        {/* outer frame draws at stage 1 */}
        <rect
          x="36" y="60" width="488" height="480"
          fill="none" stroke="#264653" strokeWidth="1.6"
          pathLength="1" strokeDasharray="1"
          strokeDashoffset={phase >= 1 ? 0 : 1}
          style={{ transition: "stroke-dashoffset 900ms ease", opacity: phase >= 4 ? 0.45 : 1 }}
        />

        {/* dimension line — board/planning */}
        <g stroke="#D99041" strokeWidth="1" fill="none"
           style={{ opacity: phase >= 1 && phase < 3 ? 1 : 0, transition: "opacity 500ms ease" }}>
          <line x1="36" y1="556" x2="524" y2="556" />
          <path d="M36 551 v10 M524 551 v10" />
        </g>
        <text x="280" y="572" textAnchor="middle" className="hs-dim"
          style={{ opacity: phase >= 1 && phase < 3 ? 1 : 0 }}>4.88 m</text>

        {/* result sheen — stage 4 */}
        <rect x="37" y="61" width="486" height="478" fill="url(#sheen)"
          style={{ opacity: phase >= 4 ? 0.35 : 0, transition: "opacity 700ms ease" }} />
      </svg>

      {/* stage indicator */}
      <div className="hs-stages">
        {STAGES.map((st, i) => (
          <div key={st} className={"hs-stage" + (phase >= i ? " on" : "") + (phase === i ? " cur" : "")}>
            <span className="hs-stage-dot" />
            <span className="mono hs-stage-label">{st}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

function Hero() {
  return (
    <section className="hero" id="top">
      <div className="hero-grid container">
        <div className="hero-copy">
          <span className="kicker reveal">Natural stone · Facades · Masonry</span>
          <h1 className="h1 hero-title reveal d1">Architectural stone, built with engineering precision</h1>
          <p className="body-lg hero-sub reveal d2">
            GlobalStaff designs and installs natural stone, facade cladding and masonry across
            Estonia and the Baltics — carrying every project from technical drawing to finished surface.
          </p>
          <div className="hero-cta reveal d3">
            <a href="#quote" className="btn btn-accent btn-lg">
              Request a Quote
              <svg className="arrow" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <path d="M5 12h14M13 6l6 6-6 6" />
              </svg>
            </a>
            <a href="#projects" className="btn btn-secondary btn-lg">View Projects</a>
          </div>
        </div>

        <div className="hero-viz-wrap reveal d2">
          <HeroStone />
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Hero });
