/* ============================================================
   components.jsx
   Small reusable components: icons, glitch text, reveal wrapper,
   nav, hero visuals, mascot.
   ============================================================ */

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

/* ───── glitch headline word (chromatic aberration) ───── */
function Glitch({ children, color }) {
  const text = typeof children === "string" ? children : "";
  return (
    <span className="glitch-word" data-text={text} style={color ? { color } : undefined}>
      {children}
    </span>);

}

/* ───── reveal-on-scroll ───── */
function Reveal({ as = "div", stagger, className = "", children, ...rest }) {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            el.classList.add("in");
            io.unobserve(el);
          }
        });
      },
      { threshold: 0.12, rootMargin: "0px 0px -8% 0px" }
    );
    io.observe(el);
    return () => io.disconnect();
  }, []);
  const Tag = as;
  return (
    <Tag
      ref={ref}
      className={`reveal ${className}`}
      data-stagger={stagger || undefined}
      {...rest}>
      
      {children}
    </Tag>);

}

/* ───── pixel icons (12x12 grid -> SVG rects) ───── */
function PixelIcon({ map, size = 36, color = "currentColor" }) {
  // map: array of strings; "1" = pixel on
  const cells = [];
  const rows = map.length;
  const cols = map[0].length;
  for (let y = 0; y < rows; y++) {
    for (let x = 0; x < cols; x++) {
      if (map[y][x] !== " " && map[y][x] !== "0") {
        cells.push(
          <rect
            key={`${x}-${y}`}
            x={x}
            y={y}
            width="1"
            height="1"
            fill={color} />

        );
      }
    }
  }
  return (
    <svg
      width={size}
      height={size}
      viewBox={`0 0 ${cols} ${rows}`}
      shapeRendering="crispEdges"
      style={{ display: "block" }}>
      
      {cells}
    </svg>);

}

/* preset icons */
const ICONS = {
  // bullseye / target — Tráfego pago
  trafego: [
  "  111111  ",
  " 1      1 ",
  "1  1111  1",
  "1 1    1 1",
  "1 1 11 1 1",
  "1 1 11 1 1",
  "1 1    1 1",
  "1  1111  1",
  " 1      1 ",
  "  111111  "],

  // browser window — Site / Landing
  site: [
  "1111111111",
  "1        1",
  "1 11 11  1",
  "1        1",
  "1        1",
  "1  111   1",
  "1 1   1  1",
  "1  111   1",
  "1        1",
  "1111111111"],

  // brush / paint — Branding
  branding: [
  "       111",
  "      1111",
  "     1111 ",
  "    1111  ",
  "   1111   ",
  "  1111    ",
  " 11 1     ",
  "11   1    ",
  "11   1    ",
  " 1111     "],

  // magnifier — SEO
  seo: [
  " 11111    ",
  "1     1   ",
  "1     1   ",
  "1     1   ",
  "1     1   ",
  " 11111    ",
  "      1   ",
  "       1  ",
  "        1 ",
  "         1"],

  // map pin — Google Business
  pin: [
  "  1111    ",
  " 1    1   ",
  "1  11  1  ",
  "1 1  1 1  ",
  "1 1  1 1  ",
  "1  11  1  ",
  " 1    1   ",
  "  1  1    ",
  "   11     ",
  "   11     "],

  arrow: [
  "         ",
  "    111  ",
  "     11  ",
  "      1  ",
  "11111111 ",
  "      1  ",
  "     11  ",
  "    111  ",
  "         "],

  social: [
  " 1111111 ",
  "1       1",
  "1 1   1 1",
  "1  1 1  1",
  "1   1   1",
  "1       1",
  "1  111  1",
  "1       1",
  " 1111111 ",
  "    1    "]

};

/* ───── nav ───── */
function Nav() {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 8);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  return (
    <nav className={`nav ${scrolled ? "scrolled" : ""}`}>
      <a href="#top" className="nav-brand" aria-label="Mimicus">
        <img className="nav-logo-full" src="assets/logotipo.webp" alt="Mimicus — Marketing de Performance" style={{ height: "100px" }} />
      </a>
      <ul className="nav-links">
        <li><a href="#servicos">Serviços</a></li>
        <li><a href="#processo">Processo</a></li>
        <li><a href="#sobre">Sobre</a></li>
        <li><a href="#depoimentos">Depoimentos</a></li>
        <li><a href="#faq">FAQ</a></li>
        <li><a href="blog/index.html">Blog</a></li>
      </ul>
      <a href="#contato" className="nav-cta">
        Falar com especialista
        <span aria-hidden="true">↗</span>
      </a>
    </nav>);

}

/* ───── scroll progress strip ───── */
function ScrollProgress() {
  const ref = useRef(null);
  useEffect(() => {
    const onScroll = () => {
      if (!ref.current) return;
      const h = document.documentElement.scrollHeight - window.innerHeight;
      const pct = h > 0 ? window.scrollY / h * 100 : 0;
      ref.current.style.width = `${pct}%`;
    };
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  return <div className="scroll-progress" ref={ref} />;
}

/* ───── pixel mascot — bobs, tilts with scroll velocity, talks at section breaks ───── */
function PixelMascot() {
  const ref = useRef(null);
  const speechRef = useRef(null);
  const [hidden, setHidden] = useState(true);
  const [speech, setSpeech] = useState("");
  const lastScrollY = useRef(0);
  const lastVel = useRef(0);
  const speechTimer = useRef(null);
  const lastSection = useRef("");

  useEffect(() => {
    const SECTION_GREETINGS = {
      "servicos": "Esse é o cardápio.",
      "processo": "Como a gente trabalha.",
      "sobre": "Esse é o time.",
      "depoimentos": "Olha o que falam.",
      "faq": "Dúvidas? respondi.",
      "contato": "Bora conversar 🦑"
    };

    const onScroll = () => {
      const y = window.scrollY;
      const vel = y - lastScrollY.current;
      lastScrollY.current = y;
      lastVel.current = vel;

      setHidden(y < 200);

      const tilt = Math.max(-14, Math.min(14, vel * 0.6));
      if (ref.current) {
        ref.current.style.transform = `rotate(${tilt}deg)`;
      }

      // detect which section is most in view
      const sections = ["servicos", "processo", "sobre", "depoimentos", "faq", "contato"];
      const center = window.innerHeight * 0.45;
      let best = "";
      let bestDist = Infinity;
      for (const id of sections) {
        const el = document.getElementById(id);
        if (!el) continue;
        const rect = el.getBoundingClientRect();
        if (rect.top < center && rect.bottom > center) {
          const d = Math.abs(rect.top - center);
          if (d < bestDist) {bestDist = d;best = id;}
        }
      }
      if (best && best !== lastSection.current) {
        lastSection.current = best;
        const msg = SECTION_GREETINGS[best];
        if (msg) {
          setSpeech(msg);
          clearTimeout(speechTimer.current);
          speechTimer.current = setTimeout(() => setSpeech(""), 2400);
        }
      }
    };

    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => {
      window.removeEventListener("scroll", onScroll);
      clearTimeout(speechTimer.current);
    };
  }, []);

  return (
    <>
      <div className={`mascot mascot-left ${hidden ? "hidden" : ""} ${speech ? "show-speech" : ""}`}>
        <div className="speech speech-right" ref={speechRef}>{speech || "·"}</div>
        <div className="mascot-inner" ref={ref}>
          <img src="assets/mimicus-octopus-transparent.png" alt="" aria-hidden="true" />
        </div>
      </div>
      <a
        href="https://wa.me/5511999999999?text=Ol%C3%A1%2C%20vim%20do%20site%20da%20Mimicus"
        target="_blank"
        rel="noopener noreferrer"
        className={`wa-fab ${hidden ? "hidden" : ""}`}
        aria-label="Falar no WhatsApp"
      >
        <span className="wa-fab-pulse" aria-hidden="true" />
        <svg viewBox="0 0 32 32" width="26" height="26" fill="currentColor" aria-hidden="true">
          <path d="M16 3a13 13 0 0 0-11.2 19.6L3 29l6.6-1.8A13 13 0 1 0 16 3zm0 23.6a10.6 10.6 0 0 1-5.4-1.5l-.4-.2-3.9.9 1-3.8-.2-.4A10.6 10.6 0 1 1 16 26.6zm5.9-7.9c-.3-.2-1.9-1-2.2-1-.3-.1-.5-.2-.7.2-.2.3-.8 1-1 1.2-.2.2-.4.2-.7.1-.3-.2-1.4-.5-2.6-1.6-1-.9-1.6-1.9-1.8-2.2-.2-.3 0-.5.1-.6.2-.2.3-.4.5-.6.2-.2.2-.3.3-.5.1-.2.1-.4 0-.5-.1-.2-.7-1.7-1-2.3-.3-.6-.5-.5-.7-.6h-.6c-.2 0-.6.1-.9.4-.3.3-1.2 1.1-1.2 2.7s1.2 3.2 1.4 3.4c.2.2 2.4 3.7 5.9 5.2.8.3 1.5.5 2 .7.8.3 1.6.2 2.2.1.7-.1 2.1-.8 2.4-1.7.3-.8.3-1.6.2-1.7-.1-.1-.3-.2-.6-.4z"/>
        </svg>
        <span className="wa-fab-label">Fale com a Mimicus</span>
      </a>
    </>);

}

/* ───── hero dashboard mock ───── */
function HeroDashboard() {
  // generate a sparkline-ish path
  const points = useMemo(() => {
    const seed = [10, 14, 12, 18, 22, 19, 27, 31, 28, 35, 42, 38, 48, 56, 53, 64, 72, 78];
    return seed;
  }, []);
  const points2 = useMemo(() => {
    return [6, 8, 10, 11, 14, 15, 16, 19, 20, 22, 24, 26, 27, 30, 32, 34, 38, 40];
  }, []);

  const w = 360,h = 110;
  const toPath = (vals) => {
    const max = Math.max(...vals);
    const step = w / (vals.length - 1);
    return vals.
    map((v, i) => `${i === 0 ? "M" : "L"} ${i * step} ${h - v / max * (h - 8)}`).
    join(" ");
  };

  return (
    <div className="dash">
      <div className="dash-head">
        <div className="title">Visão geral</div>
        <div className="pill">Últimos 30 dias ⌄</div>
      </div>
      <div className="dash-stats">
        <div className="dash-stat">
          <div className="lbl">Investimento</div>
          <div className="num">R$ 1.327.892</div>
          <div className="delta up">+28,6%</div>
        </div>
        <div className="dash-stat">
          <div className="lbl">Faturamento</div>
          <div className="num">R$ 4.982.031</div>
          <div className="delta up">+45,3%</div>
        </div>
        <div className="dash-stat">
          <div className="lbl">ROAS</div>
          <div className="num">3,75x</div>
          <div className="delta up">+32,1%</div>
        </div>
      </div>
      <div className="dash-chart">
        <div className="legend">
          <div className="title">Desempenho</div>
          <div className="keys">
            <span><i style={{ background: "var(--text-3)" }} /> Investimento</span>
            <span><i style={{ background: "var(--primary)" }} /> Faturamento</span>
          </div>
        </div>
        <svg className="svg-chart" viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none">
          <defs>
            <linearGradient id="fillg" x1="0" y1="0" x2="0" y2="1">
              <stop offset="0%" stopColor="var(--primary)" stopOpacity="0.35" />
              <stop offset="100%" stopColor="var(--primary)" stopOpacity="0" />
            </linearGradient>
          </defs>
          {/* gridlines */}
          {[0, 1, 2, 3].map((i) =>
          <line key={i} x1="0" x2={w} y1={h * (i + 1) / 4} y2={h * (i + 1) / 4}
          stroke="var(--border)" strokeDasharray="2 4" />
          )}
          {/* fill under primary line */}
          <path d={`${toPath(points)} L ${w} ${h} L 0 ${h} Z`} fill="url(#fillg)" />
          {/* secondary line (grey) */}
          <path d={toPath(points2)} fill="none" stroke="var(--text-3)" strokeWidth="1.5" strokeLinecap="round" />
          {/* primary */}
          <path d={toPath(points)} fill="none" stroke="var(--primary)" strokeWidth="2" strokeLinecap="round" />
          {/* dot */}
          <circle cx={w} cy={h - points[points.length - 1] / Math.max(...points) * (h - 8)} r="3" fill="var(--primary)" />
        </svg>
      </div>
    </div>);

}

function HeroPhone() {
  // donut for ROAS
  const pct = 0.78;
  const r = 38;
  const c = 2 * Math.PI * r;
  return (
    <div className="phone">
      <div className="phone-screen">
        <div className="ph-top">
          <span className="ph-pill">Campanha ativa ⌄</span>
          <span className="ph-eyebrow ph-tiny">Performance</span>
        </div>
        <div className="ph-donut" aria-hidden="true">
          <svg viewBox="0 0 100 100" width="100%" height="100%">
            <circle cx="50" cy="50" r={r} fill="none" stroke="rgba(255,255,255,0.07)" strokeWidth="9" />
            <circle cx="50" cy="50" r={r} fill="none" stroke="var(--primary)" strokeWidth="9"
              strokeLinecap="round" strokeDasharray={`${c * pct} ${c}`} transform="rotate(-90 50 50)" />
          </svg>
          <div className="ph-donut-text">
            <div className="ph-donut-num">3,75x</div>
            <div className="ph-donut-lbl">ROAS</div>
          </div>
        </div>
        <div className="ph-mini-stats">
          <div>
            <div className="ph-tiny">Investimento</div>
            <div className="ph-num">R$ 1.327.892</div>
          </div>
          <div>
            <div className="ph-tiny">Faturamento</div>
            <div className="ph-num">R$ 4.982.031</div>
          </div>
        </div>
        <div className="ph-bars" aria-hidden="true">
          {[34, 52, 28, 70, 40, 88, 64, 96, 58, 78, 92, 70].map((h, i) => (
            <span key={i} style={{ height: `${h}%` }} />
          ))}
        </div>
      </div>
    </div>);

}

function HeroPixels() {
  // a few floating pixel squares around the visual
  const items = [
  { x: "8%", y: "5%", c: "var(--primary)", d: 0 },
  { x: "92%", y: "12%", c: "var(--neon-cyan)", d: 0.4 },
  { x: "70%", y: "2%", c: "var(--neon-magenta)", d: 0.8 },
  { x: "5%", y: "60%", c: "var(--neon-cyan)", d: 1.2 },
  { x: "96%", y: "70%", c: "var(--primary)", d: 1.6 },
  { x: "50%", y: "95%", c: "var(--neon-magenta)", d: 2.0 },
  { x: "30%", y: "85%", c: "var(--primary)", d: 2.4 },
  { x: "85%", y: "45%", c: "var(--neon-cyan)", d: 2.8 }];

  return (
    <div className="hero-pixels" aria-hidden="true">
      {items.map((p, i) =>
      <span key={i} style={{
        left: p.x, top: p.y, background: p.c,
        animationDelay: `${p.d}s`,
        boxShadow: `0 0 14px ${p.c}`
      }} />
      )}
    </div>);

}

Object.assign(window, {
  Glitch, Reveal, PixelIcon, ICONS, Nav, ScrollProgress, PixelMascot,
  HeroDashboard, HeroPhone, HeroPixels
});