// Hero — supports 2 variants ("spotlight" = big animated logo center, "terminal" = split with terminal pane).
// Both share: scramble headline, mono meta strip, blueprint frame, drift motif.

function HeroFrame({ children, dark }) {
  // Blueprint-style corner ticks + side labels around the hero canvas.
  const tick = (placement) => {
    const base = { position: "absolute", width: 18, height: 18, pointerEvents: "none" };
    const c = dark ? "rgba(245,243,238,0.35)" : "rgba(10,10,10,0.35)";
    const lines = {
      tl: { left: 24, top: 24, borderLeft: `1px solid ${c}`, borderTop: `1px solid ${c}` },
      tr: { right: 24, top: 24, borderRight: `1px solid ${c}`, borderTop: `1px solid ${c}` },
      bl: { left: 24, bottom: 24, borderLeft: `1px solid ${c}`, borderBottom: `1px solid ${c}` },
      br: { right: 24, bottom: 24, borderRight: `1px solid ${c}`, borderBottom: `1px solid ${c}` },
    };
    return <span style={{ ...base, ...lines[placement] }} />;
  };
  return (
    <>
      {tick("tl")}{tick("tr")}{tick("bl")}{tick("br")}
      {/* Side mono labels */}
      <span style={{
        position: "absolute", left: 24, top: "50%", transform: "translateY(-50%) rotate(-90deg)",
        transformOrigin: "left center",
        fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.32em",
        color: dark ? "var(--n-400)" : "var(--fg-3)",
        whiteSpace: "nowrap",
      }} className="hide-sm">PROMEFY · BUILD 2026.05</span>
      <span style={{
        position: "absolute", right: 24, top: "50%", transform: "translateY(-50%) rotate(90deg)",
        transformOrigin: "right center",
        fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.32em",
        color: dark ? "var(--n-400)" : "var(--fg-3)",
        whiteSpace: "nowrap",
      }} className="hide-sm">PROMEFY_SOLUTIONS · BUILD 2026.05</span>
      {children}
    </>
  );
}

function HeroSpotlight({ dark, intensity }) {

  return (
    <section id="top" style={{
      position: "relative",
      minHeight: "100vh",
      paddingTop: 80,
      paddingBottom: 96,
      overflow: "hidden",
      background: dark ? "var(--ink)" : "#FFFFFF",
      display: "flex",
      flexDirection: "column",
      justifyContent: "center",
    }}>
      {intensity > 1 && <HeroFrame dark={dark} />}

      {/* Subtle drifting wireframe motif */}
      {intensity > 0 && (
        <img
          src="assets/motif-wireframe-torus.svg"
          alt=""
          className="drift-y"
          style={{
            position: "absolute", right: "-180px", top: "12%",
            width: 520, opacity: dark ? 0.14 : 0.18,
            filter: dark ? "invert(1)" : "none",
            pointerEvents: "none",
          }}/>
      )}
      {intensity > 2 && (
        <img
          src="assets/motif-wireframe-sphere.svg"
          alt=""
          className="drift-x"
          style={{
            position: "absolute", left: "-220px", bottom: "8%",
            width: 460, opacity: dark ? 0.10 : 0.14,
            filter: dark ? "invert(1)" : "none",
            pointerEvents: "none",
          }}/>
      )}

      <div className="container" style={{
        position: "relative",
        display: "flex",
        flexDirection: "column",
        alignItems: "center",
        textAlign: "center",
        gap: 40,
      }}>
        {/* Top mono strip */}
        <Reveal className="reveal-up" delay={0}>
          <div style={{
            display: "flex", alignItems: "center", gap: 12,
            fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.20em",
            color: dark ? "var(--n-400)" : "var(--fg-3)",
            textTransform: "uppercase",
          }}>
            <span style={{ color: "var(--site-accent, var(--flame))" }}>●</span>
            <span>EST 2025</span>
            <span style={{ opacity: 0.4 }}>·</span>
            <span>SOFTWARE STUDIO</span>
          </div>
        </Reveal>

        {/* Static logo, subtle reveal */}
        <Reveal className="reveal-up" delay={120}>
          <img
            src="assets/logo.png"
            alt="Promefy Solutions"
            style={{
              width: "min(520px, 68vw)",
              height: "auto",
              userSelect: "none",
              filter: dark
                ? "invert(1) drop-shadow(0 24px 48px rgba(0,0,0,0.45))"
                : "drop-shadow(0 24px 48px rgba(10,10,10,0.08))",
            }}/>
        </Reveal>

        {/* Scramble headline */}
        <h1 style={{
          fontFamily: "var(--font-display)",
          fontSize: "clamp(42px, 6.8vw, 96px)",
          fontWeight: 500,
          lineHeight: 1.0,
          letterSpacing: "-0.028em",
          color: dark ? "var(--paper)" : "var(--fg-1)",
          margin: 0,
          textWrap: "balance",
          maxWidth: "100%",
        }}>
          <ScrambleText
            segments={[
              { text: "Bring new fire to " },
              { text: "old firms.", accent: true },
            ]}
            perCharDuration={80}
            charGap={32}
            delay={600}
          />
        </h1>

        <p style={{
          fontSize: 19,
          lineHeight: 1.55,
          color: dark ? "var(--n-300)" : "var(--fg-2)",
          maxWidth: "56ch",
          fontFamily: "var(--font-sans)",
          margin: 0,
        }}>
          <ScrambleText
            segments={[{
              text: "We build the software your firm needs — and refresh how you look online. Two services, one team.",
            }]}
            perCharDuration={28}
            charGap={10}
            delay={1400}
          />
        </p>

        <Reveal className="reveal-up" delay={1500} style={{
          display: "flex", gap: 12, alignItems: "center", flexWrap: "wrap", justifyContent: "center",
          marginTop: 4,
        }}>
          <Button variant="flame" href="#contact" onClick={(e) => { e.preventDefault(); document.getElementById("contact").scrollIntoView({ behavior: "smooth" }); }}>
            Start a project <ArrowGlyph />
          </Button>
          <Button variant={dark ? "outline" : "secondary"} href="#services" onClick={(e) => { e.preventDefault(); document.getElementById("services").scrollIntoView({ behavior: "smooth" }); }}>
            See the work
          </Button>
        </Reveal>

        {/* Scroll indicator */}
        <Reveal className="reveal-up" delay={1800} style={{
          position: "absolute", bottom: -24, left: "50%", transform: "translateX(-50%)",
          display: "flex", flexDirection: "column", alignItems: "center", gap: 6,
          fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.24em",
          color: dark ? "var(--n-400)" : "var(--fg-3)",
        }}>
          <span>SCROLL</span>
          <span style={{
            width: 1, height: 36,
            background: `linear-gradient(to bottom, ${dark ? "var(--n-400)" : "var(--fg-3)"} 50%, transparent 50%)`,
            backgroundSize: "1px 8px",
          }} />
        </Reveal>
      </div>
    </section>
  );
}

// ---- LiveTerminal — typing animation + matrix rain backdrop ---------------

function useMatrixRain(canvasRef, { color = "var(--site-accent, #00FF66)", density = 1, speed = 1 } = {}) {
  React.useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext("2d");
    if (!ctx) return;

    let raf, drops, fontSize = 14, columns = 0, w = 0, h = 0;
    // Resolve CSS var for the accent into a real color value at runtime.
    const probe = document.createElement("span");
    probe.style.color = color;
    document.body.appendChild(probe);
    const resolved = getComputedStyle(probe).color || "#00FF66";
    document.body.removeChild(probe);

    const glyphs = "アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホ0123456789{}[]<>/\\|=+-*&%$#@!?".split("");

    const resize = () => {
      const dpr = Math.min(window.devicePixelRatio || 1, 2);
      const r = canvas.getBoundingClientRect();
      w = r.width; h = r.height;
      canvas.width = w * dpr; canvas.height = h * dpr;
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
      columns = Math.floor(w / fontSize);
      drops = new Array(columns).fill(0).map(() => Math.random() * -h / fontSize);
      // Fill once so the first frame isn't pure black flash
      ctx.fillStyle = "rgba(10, 10, 10, 1)";
      ctx.fillRect(0, 0, w, h);
    };
    resize();
    const ro = new ResizeObserver(resize);
    ro.observe(canvas);

    const tick = () => {
      // While the page-transition overlay is covering/wiping, this canvas is
      // hidden behind it — skip the per-frame work so the wipe transform keeps
      // the main thread and stays smooth. Keep the rAF scheduled so it resumes.
      if (window.__omPtAnimating) { raf = requestAnimationFrame(tick); return; }
      // Translucent black overlay leaves a fading trail
      ctx.fillStyle = "rgba(10, 10, 10, 0.10)";
      ctx.fillRect(0, 0, w, h);

      ctx.font = `${fontSize}px var(--font-mono, ui-monospace, monospace)`;
      ctx.fillStyle = resolved;
      ctx.globalAlpha = 0.55;

      for (let i = 0; i < columns; i++) {
        if (Math.random() > density * 0.6) continue;
        const ch = glyphs[(Math.random() * glyphs.length) | 0];
        const x = i * fontSize;
        const y = drops[i] * fontSize;
        // Brighter head
        ctx.globalAlpha = 0.9;
        ctx.fillText(ch, x, y);
        // Trail one above with lower alpha
        ctx.globalAlpha = 0.35;
        ctx.fillText(glyphs[(Math.random() * glyphs.length) | 0], x, y - fontSize);

        if (y > h && Math.random() > 0.975) drops[i] = 0;
        drops[i] += 0.6 * speed;
      }

      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);

    return () => {
      cancelAnimationFrame(raf);
      ro.disconnect();
    };
  }, [color, density, speed]);
}

// Each block is a "question" the visitor "asks" and one or more response lines
// the terminal "prints back". Plain English, no command-line jargon.
const TERM_BLOCKS = [
  {
    cmd: "whoami",
    lines: [
      "→ A software studio for traditional firms.",
      "→ Engineers, designers, ML researchers.",
      "→ Founded 2025.",
    ],
  },
  {
    cmd: "ls ./services",
    lines: [
      "→ New websites and brand kits for traditional firms.",
      "→ Custom web apps built around how you work.",
      "→ AI that reads drawings, scans and PDFs.",
      "→ Old databases turned into something you can search.",
    ],
  },
  {
    cmd: "cat clients.txt",
    lines: [
      "→ Architects, engineers, lawyers, accountants.",
      "→ Firms run on email, spreadsheets, PDFs.",
      "→ Partners who'd rather not.",
    ],
  },
  {
    cmd: "./process.sh",
    lines: [
      "→ 30-min intro call. Free, no pitch deck.",
      "→ We scope it. You decide if it's worth it.",
      "→ 4–12 weeks of building. Then we ship.",
      "→ Code and data are yours.",
    ],
  },
  {
    cmd: "status --availability",
    lines: [
      "→ 12 projects live in production.",
      "→ 2 intake slots open this quarter.",
      "→ Last shipped: 2 hours ago.",
    ],
  },
  {
    cmd: "why-not-an-agency",
    lines: [
      "→ We don't subcontract. Same team start to finish.",
      "→ No SaaS lock-in. The keys are yours.",
      "→ Working software by week four, not a slide deck.",
    ],
  },
  {
    cmd: "./start.sh",
    lines: [
      "→ Scroll down. Send us a brief.",
      "→ Or email sales@promefy.com.",
      "→ Reply within 2 business days.",
    ],
  },
];

function LiveTerminal() {
  const canvasRef = React.useRef(null);
  const scrollerRef = React.useRef(null);
  useMatrixRain(canvasRef, { density: 0.8, speed: 1.05 });

  // Animation state: a flat queue of printed lines, plus the current
  // partially-typed line + char index.
  const [printed, setPrinted] = React.useState([]); // [{ kind: 'cmd' | 'out', text: string }]
  const [typing, setTyping]   = React.useState({ blockIdx: 0, lineIdx: -1, charIdx: 0 }); // lineIdx=-1 means the command itself
  const [clock, setClock]     = React.useState(() => new Date());

  // Tick the clock once a second
  React.useEffect(() => {
    const i = setInterval(() => setClock(new Date()), 1000);
    return () => clearInterval(i);
  }, []);

  // Typewriter loop
  React.useEffect(() => {
    const block = TERM_BLOCKS[typing.blockIdx];
    const currentText = typing.lineIdx === -1 ? block.cmd : block.lines[typing.lineIdx];
    // Done with this block?
    if (typing.lineIdx >= block.lines.length) {
      const t = setTimeout(() => {
        // Trim history so it doesn't grow forever
        setPrinted((p) => p.slice(-40));
        setTyping({ blockIdx: (typing.blockIdx + 1) % TERM_BLOCKS.length, lineIdx: -1, charIdx: 0 });
      }, 1400);
      return () => clearTimeout(t);
    }
    // Still typing chars of current line?
    if (typing.charIdx < currentText.length) {
      const delay = typing.lineIdx === -1 ? 32 : 18; // commands type slower
      const t = setTimeout(() => {
        setTyping((s) => ({ ...s, charIdx: s.charIdx + 1 }));
      }, delay + Math.random() * 30);
      return () => clearTimeout(t);
    }
    // Finished a line — push it to the log and advance
    const t = setTimeout(() => {
      setPrinted((p) => [...p, {
        kind: typing.lineIdx === -1 ? "cmd" : "out",
        text: currentText,
      }]);
      setTyping((s) => ({ ...s, lineIdx: s.lineIdx + 1, charIdx: 0 }));
    }, typing.lineIdx === -1 ? 220 : 80);
    return () => clearTimeout(t);
  }, [typing]);

  // Keep newest line visible
  React.useEffect(() => {
    const el = scrollerRef.current;
    if (el) el.scrollTop = el.scrollHeight;
  }, [printed, typing]);

  const block = TERM_BLOCKS[typing.blockIdx];
  const currentText = typing.lineIdx === -1
    ? block.cmd
    : (block.lines[typing.lineIdx] ?? "");
  const partial = currentText.slice(0, typing.charIdx);

  const fmt2 = (n) => String(n).padStart(2, "0");
  const timeStr = `${fmt2(clock.getHours())}:${fmt2(clock.getMinutes())}:${fmt2(clock.getSeconds())}`;

  return (
    <Reveal className="reveal-up" delay={300} style={{
      position: "relative",
      background: "var(--ink)",
      color: "var(--paper)",
      borderRadius: 6,
      overflow: "hidden",
      alignSelf: "stretch",
      minHeight: 380,
      display: "flex",
      flexDirection: "column",
      boxShadow: "0 20px 40px -16px rgba(10,10,10,0.4)",
      border: "1px solid rgba(245,243,238,0.10)",
    }}>
      {/* Matrix rain canvas — fills the whole thing */}
      <canvas ref={canvasRef} style={{
        position: "absolute", inset: 0,
        width: "100%", height: "100%",
        opacity: 0.34,
        pointerEvents: "none",
      }}/>
      {/* Vignette to keep text readable in the middle */}
      <div aria-hidden="true" style={{
        position: "absolute", inset: 0,
        background: "radial-gradient(ellipse at center, rgba(10,10,10,0.55) 0%, rgba(10,10,10,0.15) 60%, transparent 100%)",
        pointerEvents: "none",
      }}/>

      {/* Single window chrome — top bar with everything */}
      <div style={{
        position: "relative",
        display: "flex", alignItems: "center", justifyContent: "space-between",
        padding: "12px 16px",
        borderBottom: "1px solid rgba(245,243,238,0.10)",
        background: "rgba(0,0,0,0.4)",
        fontFamily: "var(--font-mono)", fontSize: 11.5,
        letterSpacing: "0.12em", color: "var(--n-400)", textTransform: "uppercase",
      }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
          <span style={{ display: "inline-flex", gap: 6 }}>
            <span style={{ width: 10, height: 10, borderRadius: 10, background: "#FF5F57" }}/>
            <span style={{ width: 10, height: 10, borderRadius: 10, background: "#FEBC2E" }}/>
            <span style={{ width: 10, height: 10, borderRadius: 10, background: "#28C840" }}/>
          </span>
          <span style={{ marginLeft: 6, color: "var(--paper)" }}>promefy — bash</span>
          <span style={{ opacity: 0.4 }}>—</span>
          <span>80×24</span>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
          <span>{String(typing.blockIdx + 1).padStart(2, "0")}/{String(TERM_BLOCKS.length).padStart(2, "0")}</span>
          <span style={{ opacity: 0.4 }}>·</span>
          <span style={{ color: "var(--paper)" }}>{timeStr}</span>
        </div>
      </div>

      {/* Scrolling terminal log */}
      <div ref={scrollerRef} style={{
        position: "relative",
        flex: 1,
        overflowY: "auto",
        padding: "20px 22px 22px",
        fontFamily: "var(--font-mono)",
        fontSize: 15, lineHeight: 1.65,
        scrollbarWidth: "none",
        maxHeight: 400,
      }}>
        <style>{`.live-term::-webkit-scrollbar { display: none; }`}</style>
        {printed.map((ln, i) => (
          <div key={i} style={{
            color: ln.kind === "cmd" ? "var(--paper)" : "var(--n-300)",
            paddingLeft: 0,
            opacity: 0.95,
            marginTop: ln.kind === "cmd" ? 14 : 0,
          }}>
            <span style={{ color: "var(--site-accent, var(--flame))", marginRight: 10 }}>
              {ln.kind === "cmd" ? "promefy@solutions:~$" : " "}
            </span>
            {ln.text}
          </div>
        ))}
        {/* Currently-typing line */}
        <div style={{
          color: typing.lineIdx === -1 ? "var(--paper)" : "var(--n-300)",
          paddingLeft: 0,
          marginTop: typing.lineIdx === -1 ? 14 : 0,
        }}>
          <span style={{ color: "var(--site-accent, var(--flame))", marginRight: 10 }}>
            {typing.lineIdx === -1 ? "promefy@solutions:~$" : " "}
          </span>
          {partial}
          <span className="term-cursor"/>
        </div>
      </div>
    </Reveal>
  );
}

function HeroTerminal({ dark, intensity }) {
  return (
    <section id="top" style={{
      position: "relative",
      paddingTop: 64, paddingBottom: 120, overflow: "hidden",
      background: dark ? "var(--ink)" : "var(--paper)",
      minHeight: "92vh",
    }}>
      <HeroFrame dark={dark} />
      {intensity > 0 && (
        <img src="assets/motif-wireframe-sphere.svg" alt=""
          className="drift-y"
          style={{ position: "absolute", right: "-160px", top: "8%", width: 620,
            opacity: dark ? 0.18 : 0.5, filter: dark ? "invert(1)" : "none", pointerEvents: "none" }}/>
      )}

      <div className="container grid-2 hero-layout" style={{
        position: "relative",
        display: "grid",
        gridTemplateColumns: "minmax(0, 7fr) minmax(0, 5fr)",
        gap: 48,
        alignItems: "end",
        paddingTop: 40,
      }}>
        <div style={{ display: "flex", flexDirection: "column", gap: 32 }}>
          <Reveal className="reveal-up" style={{ display: "flex", alignItems: "center", gap: 14 }}>
            <img
              src="assets/logo.png"
              alt="Promefy"
              style={{ height: 72, width: "auto", filter: dark ? "invert(1)" : "none" }}/>
          </Reveal>

          <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
            <EyebrowLabel color={dark ? "var(--n-400)" : undefined}>EST 2025 · PROMEFY</EyebrowLabel>
            <Hairline flex={1} color={dark ? "rgba(245,243,238,0.10)" : "var(--border-1)"} />
            <EyebrowLabel prefix="●" color={dark ? "var(--n-400)" : undefined}>INTAKE OPEN</EyebrowLabel>
          </div>

          <h1 style={{
            fontFamily: "var(--font-display)",
            fontSize: "clamp(44px, 6.8vw, 96px)",
            fontWeight: 500, lineHeight: 0.96, letterSpacing: "-0.025em",
            color: dark ? "var(--paper)" : "var(--fg-1)",
            margin: 0, textWrap: "balance", maxWidth: "100%",
          }}>
            <ScrambleText
              segments={[
                { text: "Software for firms that build " },
                { text: "everything else.", accent: true },
              ]}
              perCharDuration={85}
              charGap={34}
              delay={250}
            />
          </h1>

          <p style={{
            fontSize: 19, lineHeight: 1.55,
            color: dark ? "var(--n-300)" : "var(--fg-2)",
            maxWidth: "54ch", fontFamily: "var(--font-sans)",
            margin: 0,
          }}>
            <ScrambleText
              segments={[{ text: "For Professionals, By Professionals." }]}
              perCharDuration={70}
              charGap={26}
              delay={1200}
            />
          </p>

          <div style={{ display: "flex", gap: 12, alignItems: "center", flexWrap: "wrap" }}>
            <Button variant="flame" href="#contact" onClick={(e) => { e.preventDefault(); document.getElementById("contact").scrollIntoView({ behavior: "smooth" }); }}>
              Start a project <ArrowGlyph />
            </Button>
            <Button variant={dark ? "outline" : "secondary"} href="#services" onClick={(e) => { e.preventDefault(); document.getElementById("services").scrollIntoView({ behavior: "smooth" }); }}>
              See the work
            </Button>
            <span style={{
              marginLeft: 4, fontFamily: "var(--font-mono)",
              fontSize: 11, letterSpacing: "0.10em",
              color: dark ? "var(--n-500)" : "var(--fg-3)",
            }}>~ 30 MIN INTRO · NO COMMITMENT</span>
          </div>
        </div>

        <LiveTerminal />
      </div>
    </section>
  );
}

function Hero({ variant = "spotlight", dark, intensity = 2 }) {
  if (variant === "terminal") return <HeroTerminal dark={dark} intensity={intensity} />;
  return <HeroSpotlight dark={dark} intensity={intensity} />;
}

Object.assign(window, { Hero });
