// === HERO ===
const { useState, useEffect, useRef } = React;

function Hero({ variant = 'flow' }) {
  const [mousePos, setMousePos] = useState({ x: 0.5, y: 0.5 });
  const heroRef = useRef(null);

  useEffect(() => {
    const onMove = (e) => {
      if (!heroRef.current) return;
      const r = heroRef.current.getBoundingClientRect();
      setMousePos({
        x: (e.clientX - r.left) / r.width,
        y: (e.clientY - r.top) / r.height,
      });
    };
    window.addEventListener('mousemove', onMove);
    return () => window.removeEventListener('mousemove', onMove);
  }, []);

  return (
    <section ref={heroRef} className="hero" data-variant={variant}>
      <HeroCanvas mouse={mousePos} variant={variant} />
      <div className="hero-content">
        <div className="hero-eyebrow mono">
          <span className="live-dot" />
          CONSULTORIA OPERACIONAL
        </div>
        <h1 className="hero-title serif">
          Melhoria e<br/>
          automação de<br/>
          <em>processos</em><br/>
          operacionais.
        </h1>
        <p className="hero-sub">
          A Think Process redesenha o fluxo, automatiza etapas repetitivas,
          constrói sistema próprio quando o problema se repete entre clientes,
          e permanece até o time do cliente operar sozinho.
        </p>
        <div className="hero-ctas">
          <a href="#contato" className="btn btn-primary">
            Descreva o processo
            <span className="arrow">→</span>
          </a>
          <a href="#servicos" className="btn btn-ghost">
            Ver serviços
          </a>
        </div>
        <HeroMetrics />
      </div>
      <HeroScrollHint />
    </section>
  );
}

function HeroCanvas({ mouse, variant }) {
  // Layered animated canvas — offset parallax based on mouse
  const px = (mouse.x - 0.5) * 30;
  const py = (mouse.y - 0.5) * 30;
  if (variant === 'flow') return <HeroFlow px={px} py={py} />;
  if (variant === 'grid') return <HeroGrid px={px} py={py} />;
  return <HeroFlow px={px} py={py} />;
}

function HeroFlow({ px, py }) {
  // Flowing lines forming an abstract process diagram
  return (
    <div className="hero-canvas">
      <svg viewBox="0 0 1440 900" preserveAspectRatio="xMidYMid slice" style={{position:'absolute', inset: 0, width: '100%', height: '100%'}}>
        <defs>
          <linearGradient id="flow-grad" x1="0" y1="0" x2="1" y2="1">
            <stop offset="0%" stopColor="var(--accent)" stopOpacity="0" />
            <stop offset="50%" stopColor="var(--accent)" stopOpacity="1" />
            <stop offset="100%" stopColor="var(--accent)" stopOpacity="0" />
          </linearGradient>
          <filter id="glow">
            <feGaussianBlur stdDeviation="4" result="coloredBlur"/>
            <feMerge>
              <feMergeNode in="coloredBlur"/>
              <feMergeNode in="SourceGraphic"/>
            </feMerge>
          </filter>
        </defs>

        {/* Background dots grid */}
        <g opacity="0.4" style={{transform: `translate(${px*0.3}px, ${py*0.3}px)`}}>
          {Array.from({length: 20}).map((_, r) =>
            Array.from({length: 30}).map((_, c) => (
              <circle key={`${r}-${c}`} cx={c*50+20} cy={r*50+20} r="1" fill="var(--fg-mute)" />
            ))
          )}
        </g>

        {/* Flow paths */}
        <g style={{transform: `translate(${px*0.6}px, ${py*0.6}px)`}}>
          {[0, 1, 2, 3].map(i => (
            <path
              key={i}
              d={`M ${-100 + i*20} ${200 + i*120} Q ${400 + i*50} ${100 + i*80}, ${800 + i*30} ${400 + i*60} T ${1600 + i*20} ${300 + i*100}`}
              stroke="url(#flow-grad)"
              strokeWidth="1"
              fill="none"
              opacity={0.6 - i*0.1}
            >
              <animate attributeName="stroke-dasharray" values="0 2000; 2000 0" dur={`${8+i*2}s`} repeatCount="indefinite" />
            </path>
          ))}
        </g>

        {/* Process nodes */}
        <g style={{transform: `translate(${px}px, ${py}px)`}} filter="url(#glow)">
          <ProcessNode cx={280} cy={280} label="CAPTURA" delay={0} />
          <ProcessNode cx={620} cy={180} label="ANÁLISE" delay={0.5} />
          <ProcessNode cx={960} cy={340} label="EXECUÇÃO" delay={1} />
          <ProcessNode cx={1220} cy={240} label="CONTROLE" delay={1.5} accent />
        </g>

        {/* Big number mark — watermark */}
        <text
          x="95%" y="98%"
          textAnchor="end"
          fontFamily="JetBrains Mono, monospace"
          fontSize="11"
          fill="var(--fg-mute)"
          opacity="0.6"
          style={{transform: `translate(${px*0.2}px, ${py*0.2}px)`}}
        >
          TP/0001 — OPERATIONAL INTELLIGENCE
        </text>
      </svg>

      {/* Floating panels layer */}
      <div className="hero-panels" style={{transform: `translate(${px*1.2}px, ${py*1.2}px)`}}>
        <FloatingPanel x={62} y={18} title="fluxo.ativo" delay={0}>
          <div className="panel-line"><span className="dot g"/>Contas a pagar → aprovação</div>
          <div className="panel-line"><span className="dot g"/>NF entrada → ERP</div>
          <div className="panel-line"><span className="dot a"/>Onboarding cliente</div>
          <div className="panel-meter"><div className="panel-meter-fill" style={{width:'74%'}}/></div>
          <div className="panel-foot">74% automatizado</div>
        </FloatingPanel>
        <FloatingPanel x={74} y={58} title="tempo.ganho" delay={0.3}>
          <div className="panel-big">312<span className="panel-unit">h/mês</span></div>
          <div className="panel-foot">↓ 68% vs. baseline</div>
        </FloatingPanel>
        <FloatingPanel x={10} y={62} title="alertas" delay={0.6}>
          <div className="panel-line"><span className="dot w"/>SLA em risco (2)</div>
          <div className="panel-line"><span className="dot g"/>Tudo operando</div>
        </FloatingPanel>
      </div>
    </div>
  );
}

function HeroGrid({ px, py }) {
  // Alt: minimalist type-forward with a rotating grid of process terms
  const terms = ['PROCESSOS','AUTOMAÇÃO','MELHORIA','OPERAÇÕES','SISTEMAS','CONTROLE','DADOS','AUTONOMIA'];
  return (
    <div className="hero-canvas hero-canvas-grid">
      <div className="hero-terms" style={{transform: `translate(${px*0.5}px, ${py*0.5}px)`}}>
        {Array.from({length: 8}).map((_, row) => (
          <div className="hero-terms-row" key={row} style={{animationDelay: `${row*-3}s`}}>
            {[...terms, ...terms].map((t, i) => (
              <span key={i} className={(row+i)%5===0?'em':''}>{t}</span>
            ))}
          </div>
        ))}
      </div>
    </div>
  );
}

function ProcessNode({ cx, cy, label, delay = 0, accent = false }) {
  return (
    <g>
      <circle cx={cx} cy={cy} r="6" fill={accent ? 'var(--accent)' : 'var(--fg)'}>
        <animate attributeName="r" values="6;9;6" dur="3s" begin={`${delay}s`} repeatCount="indefinite" />
      </circle>
      <circle cx={cx} cy={cy} r="20" fill="none" stroke={accent ? 'var(--accent)' : 'var(--fg)'} strokeWidth="1" opacity="0.3">
        <animate attributeName="r" values="20;40;20" dur="3s" begin={`${delay}s`} repeatCount="indefinite" />
        <animate attributeName="opacity" values="0.4;0;0.4" dur="3s" begin={`${delay}s`} repeatCount="indefinite" />
      </circle>
      <text x={cx} y={cy+36} textAnchor="middle" fontFamily="JetBrains Mono, monospace" fontSize="10" fill="var(--fg-dim)" letterSpacing="0.1em">
        {label}
      </text>
    </g>
  );
}

function FloatingPanel({ x, y, title, children, delay = 0 }) {
  return (
    <div className="float-panel" style={{left: `${x}%`, top: `${y}%`, animationDelay: `${delay}s`}}>
      <div className="panel-head">
        <div className="panel-lights">
          <span/><span/><span/>
        </div>
        <span className="panel-title mono">{title}</span>
      </div>
      <div className="panel-body">
        {children}
      </div>
    </div>
  );
}

function HeroMetrics() {
  const metrics = [
    { n: '−52,5%', l: 'ruptura em\nfarmacêutica' },
    { n: '−75%', l: 'tempo de\nciclo de S&OP' },
    { n: '6', l: 'setores com\nentregas comprovadas' },
  ];
  return (
    <div className="hero-metrics">
      {metrics.map((m, i) => (
        <div key={i} className="hero-metric">
          <div className="hero-metric-n serif">{m.n}</div>
          <div className="hero-metric-l mono">{m.l}</div>
        </div>
      ))}
    </div>
  );
}

function HeroScrollHint() {
  return (
    <div className="scroll-hint mono">
      <span>SCROLL</span>
      <div className="scroll-line"><div/></div>
    </div>
  );
}

window.Hero = Hero;
