/* global React */

// Brief-provided headline + subheadline pairs (exposed as a Tweak).
const HEADLINES = [
  { h: 'Precisão técnica em cada detalhe', sub: 'Apoio técnico a advogados e escritórios em disputas patrimoniais, judiciais, extrajudiciais ou arbitragem.' },
  { h: 'Onde há dúvida, há método', sub: 'Análises técnicas que transformam questionamentos em evidências.' },
  { h: 'A resposta está nos detalhes', sub: 'Perícias e avaliações conduzidas com rigor técnico e respaldo profissional.' },
  { h: 'Evidências que falam por si', sub: 'Quando a decisão exige precisão, a análise técnica faz a diferença.' },
  { h: 'Veja além do que é visível', sub: 'Identificamos causas, riscos e responsabilidades com metodologia e experiência.' },
];
window.HEADLINES = HEADLINES;

// Technical terms that drift behind the inspection lens.
const TERMS = [
  { x: 6,  y: 9,  s: 16, m: false, r: -4, t: 'Trincas estruturais' },
  { x: 60, y: 6,  s: 13, m: true,  r: 0,  t: 'NBR 14653' },
  { x: 32, y: 19, s: 18, m: false, r: 2,  t: 'Infiltrações' },
  { x: 67, y: 22, s: 14, m: false, r: -3, t: 'Inspeção predial' },
  { x: 5,  y: 31, s: 13, m: true,  r: 0,  t: 'NBR 13752' },
  { x: 38, y: 38, s: 20, m: false, r: 0,  t: 'Vícios construtivos' },
  { x: 74, y: 40, s: 14, m: false, r: 3,  t: 'Laudo técnico' },
  { x: 9,  y: 50, s: 16, m: false, r: -2, t: 'Patologia das construções' },
  { x: 56, y: 55, s: 14, m: false, r: 0,  t: 'Perícia judicial' },
  { x: 28, y: 63, s: 16, m: false, r: 2,  t: 'Engenharia diagnóstica' },
  { x: 71, y: 66, s: 13, m: false, r: -3, t: 'Parecer técnico' },
  { x: 6,  y: 74, s: 14, m: false, r: 0,  t: 'Avaliação imobiliária' },
  { x: 42, y: 81, s: 15, m: false, r: -2, t: 'Conformidade construtiva' },
  { x: 67, y: 85, s: 14, m: false, r: 2,  t: 'Assistência técnica' },
  { x: 16, y: 91, s: 13, m: false, r: 0,  t: 'Responsabilidade técnica' },
];

function TermField({ sharp, navy, dim }) {
  const blurColor = navy ? 'var(--blue-300)' : 'var(--ink-400)';
  const sharpColor = navy ? 'var(--cream-50)' : 'var(--blue-700)';
  const cls = sharp
    ? 'term-layer term-layer-sharp'
    : ('term-layer term-layer-blur' + (dim ? ' term-layer-dim' : ''));
  return (
    <div className={cls} aria-hidden="true">
      {TERMS.map((term, i) => (
        <span
          key={i}
          className={'term ' + (i % 2 ? 'term-b' : 'term-a')}
          style={{
            left: term.x + '%',
            top: term.y + '%',
            fontSize: term.s + 'px',
            fontFamily: term.m ? 'var(--font-mono)' : 'var(--font-sans)',
            fontWeight: term.m ? 600 : 500,
            letterSpacing: term.m ? '0.04em' : '-0.01em',
            transform: 'rotate(' + term.r + 'deg)',
            color: sharp ? sharpColor : blurColor,
          }}
        >
          {term.t}
        </span>
      ))}
    </div>
  );
}

// Shared inspection-lens animation: drives clip-path + reticle position via rAF.
function useInspectionLens({ hostRef, sharpRef, frameRef, circle, reticle, sweep, deps }) {
  React.useEffect(() => {
    const host = hostRef.current;
    if (!host) return;
    const reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    const { RW, RH, R } = reticle;
    const halfW = circle ? R : RW / 2;
    const halfH = circle ? R : RH / 2;
    const s = { hover: false, mx: sweep.cx0, my: sweep.cy0, cx: sweep.cx0, cy: sweep.cy0 };
    let raf;
    const start = performance.now();
    function tick(now) {
      const w = host.clientWidth || 1;
      const h = host.clientHeight || 1;
      let tx, ty;
      if (s.hover) { tx = s.mx; ty = s.my; }
      else if (reduce) { tx = sweep.cx0; ty = sweep.cy0; }
      else {
        const e = now - start;
        tx = sweep.cx0 + sweep.ax * Math.sin(e * sweep.fx);
        ty = sweep.cy0 + sweep.ay * Math.sin(e * sweep.fy + 1.2);
      }
      const k = s.hover ? 0.20 : 0.045;
      s.cx += (tx - s.cx) * k;
      s.cy += (ty - s.cy) * k;
      const minx = halfW / w, maxx = 1 - halfW / w;
      const miny = halfH / h, maxy = 1 - halfH / h;
      const fx = Math.min(maxx, Math.max(minx, s.cx));
      const fy = Math.min(maxy, Math.max(miny, s.cy));
      const x = fx * w, y = fy * h;
      if (sharpRef.current) {
        sharpRef.current.style.clipPath = circle
          ? 'circle(' + R + 'px at ' + x + 'px ' + y + 'px)'
          : 'inset(' + (y - RH / 2) + 'px ' + (w - (x + RW / 2)) + 'px ' + (h - (y + RH / 2)) + 'px ' + (x - RW / 2) + 'px)';
      }
      if (frameRef.current) {
        frameRef.current.style.left = (circle ? x - R : x - RW / 2) + 'px';
        frameRef.current.style.top = (circle ? y - R : y - RH / 2) + 'px';
      }
      raf = requestAnimationFrame(tick);
    }
    raf = requestAnimationFrame(tick);
    const onMove = (ev) => {
      const r = host.getBoundingClientRect();
      s.mx = (ev.clientX - r.left) / r.width;
      s.my = (ev.clientY - r.top) / r.height;
    };
    const onEnter = () => { s.hover = true; };
    const onLeave = () => { s.hover = false; };
    host.addEventListener('mousemove', onMove);
    host.addEventListener('mouseenter', onEnter);
    host.addEventListener('mouseleave', onLeave);
    return () => {
      cancelAnimationFrame(raf);
      host.removeEventListener('mousemove', onMove);
      host.removeEventListener('mouseenter', onEnter);
      host.removeEventListener('mouseleave', onLeave);
    };
  }, deps);
}

function LensReticle({ innerRef, width, height, circle, markColor, initialLeft, initialTop }) {
  return (
    <div
      ref={innerRef}
      className="lens-frame"
      style={{ width, height, left: initialLeft, top: initialTop, borderRadius: circle ? '50%' : 'var(--r-xs)', borderColor: markColor }}
    >
      <span className="lens-corner lc-tl" style={{ borderColor: markColor }} />
      <span className="lens-corner lc-tr" style={{ borderColor: markColor }} />
      <span className="lens-corner lc-bl" style={{ borderColor: markColor }} />
      <span className="lens-corner lc-br" style={{ borderColor: markColor }} />
      <span className="lens-cross lens-cross-h" style={{ background: markColor }} />
      <span className="lens-cross lens-cross-v" style={{ background: markColor }} />
    </div>
  );
}

// Prova-de-autoridade row — quiet mono labels with hairline separators.
function ProvaRow({ items, tone }) {
  const color = tone === 'inverse' ? 'var(--blue-300)' : 'var(--ink-400)';
  const sep = tone === 'inverse' ? 'var(--line-cool)' : 'var(--line-warm)';
  const border = tone === 'inverse' ? 'var(--line-cool)' : 'var(--line-warm)';
  return (
    <div style={{
      display: 'flex', alignItems: 'center', flexWrap: 'wrap', gap: '10px 18px', marginTop: 48,
      paddingTop: 26, borderTop: '1px solid ' + border,
      fontFamily: 'var(--font-mono)', fontSize: '11.5px', fontWeight: 'var(--fw-medium)',
      letterSpacing: '0.13em', textTransform: 'uppercase', color,
      justifyContent: tone === 'center' ? 'center' : 'flex-start',
    }}>
      {items.map((p, i) => (
        <React.Fragment key={i}>
          {i > 0 && <span style={{ width: 1, height: 11, background: sep, display: 'inline-block' }} />}
          <span>{p.trim()}</span>
        </React.Fragment>
      ))}
    </div>
  );
}

function InspectionPanel({ navy, circle }) {
  const hostRef = React.useRef(null);
  const sharpRef = React.useRef(null);
  const frameRef = React.useRef(null);
  useInspectionLens({
    hostRef, sharpRef, frameRef, circle,
    reticle: { RW: 212, RH: 152, R: 98 },
    sweep: { cx0: 0.5, cy0: 0.46, ax: 0.30, ay: 0.24, fx: 0.00052, fy: 0.00039 },
    deps: [circle, navy],
  });
  const markColor = navy ? 'var(--blue-300)' : 'var(--blue-600)';
  return (
    <div ref={hostRef} className={'inspect-panel' + (navy ? ' inspect-navy' : ' inspect-cream')}>
      <span className="reg-mark rm-tl" style={{ borderColor: markColor }} />
      <span className="reg-mark rm-tr" style={{ borderColor: markColor }} />
      <span className="reg-mark rm-bl" style={{ borderColor: markColor }} />
      <span className="reg-mark rm-br" style={{ borderColor: markColor }} />
      <div className="inspect-caption">
        <span className="inspect-dot" />
        ÁREA DE INSPEÇÃO · FOCO NÍTIDO
      </div>
      <TermField navy={navy} />
      <div ref={sharpRef} className="term-clip" style={{ clipPath: 'circle(0px at 50% 50%)' }}>
        <TermField navy={navy} sharp />
      </div>
      <LensReticle innerRef={frameRef} circle={circle} width={circle ? 196 : 212} height={circle ? 196 : 152} markColor={markColor}
        initialLeft={circle ? 'calc(50% - 98px)' : 'calc(50% - 106px)'} initialTop={circle ? 'calc(46% - 98px)' : 'calc(46% - 76px)'} />
    </div>
  );
}

// ── Format A — Painel: editorial split + boxed inspection panel ──────────────
function PanelHero({ t, scrollTo }) {
  const { Button, Eyebrow } = window.MXDEngenharia_e41562;
  const navy = (t.panelTheme || 'Navy') !== 'Cream';
  const circle = t.lensShape === 'Círculo';
  const msg = HEADLINES[t.headlineIndex] || HEADLINES[0];
  const prova = (t.prova || 'Perícias judiciais • Avaliações imobiliárias • Assistência técnica').split('•');
  return (
    <section id="inicio" style={{ background: 'var(--cream-100)', borderBottom: '1px solid var(--line-warm)' }}>
      <div style={{
        maxWidth: 'var(--container)', margin: '0 auto', padding: '120px 32px 104px',
        display: 'grid', gridTemplateColumns: '1.04fr 0.96fr', gap: 72, alignItems: 'center',
      }}>
        <div>
          <Eyebrow>{t.eyebrow}</Eyebrow>
          <h1 style={{
            fontFamily: 'var(--font-sans)', fontSize: 'var(--fs-display)', lineHeight: 'var(--lh-tight)',
            letterSpacing: 'var(--ls-display)', fontWeight: 'var(--fw-bold)', color: 'var(--ink-900)',
            margin: '20px 0 0', maxWidth: 560, textWrap: 'balance',
          }}>
            {msg.h}
          </h1>
          <p style={{
            fontFamily: 'var(--font-sans)', fontSize: 'var(--fs-body-lg)', lineHeight: 'var(--lh-normal)',
            color: 'var(--text-secondary)', margin: '24px 0 0', maxWidth: 460, textWrap: 'pretty',
          }}>
            {msg.sub}
          </p>
          <div style={{ display: 'flex', gap: 12, marginTop: 34, flexWrap: 'wrap' }}>
            <Button size="lg" onClick={() => scrollTo('contato')} style={{ whiteSpace: 'nowrap' }}>
              Solicitar orçamento
            </Button>
            <Button size="lg" variant="secondary" onClick={() => window.open('https://wa.me/5534996847972', '_blank', 'noopener')} iconLeft={<Icon name="message-circle" size={18} color="var(--blue-700)" />}>
              Falar pelo WhatsApp
            </Button>
          </div>
          <ProvaRow items={prova} />
        </div>
        <InspectionPanel navy={navy} circle={circle} />
      </div>
    </section>
  );
}

// ── Format B — Imersivo: full-bleed navy inspection field ────────────────────
function ImmersiveHero({ t, scrollTo }) {
  const { Button, Eyebrow } = window.MXDEngenharia_e41562;
  const msg = HEADLINES[t.headlineIndex] || HEADLINES[0];
  const prova = (t.prova || 'Perícias judiciais • Avaliações imobiliárias • Assistência técnica').split('•');
  const hostRef = React.useRef(null);
  const sharpRef = React.useRef(null);
  const frameRef = React.useRef(null);
  useInspectionLens({
    hostRef, sharpRef, frameRef, circle: true,
    reticle: { RW: 234, RH: 234, R: 117 },
    sweep: { cx0: 0.72, cy0: 0.52, ax: 0.16, ay: 0.26, fx: 0.00048, fy: 0.00037 },
    deps: [],
  });
  return (
    <section id="inicio" style={{ position: 'relative', background: 'var(--blue-900)', borderBottom: '1px solid var(--line-cool)', overflow: 'hidden' }}>
      <div ref={hostRef} className="immersive-field" style={{ position: 'absolute', inset: 0 }}>
        <span className="reg-mark rm-tl" style={{ borderColor: 'var(--blue-300)' }} />
        <span className="reg-mark rm-tr" style={{ borderColor: 'var(--blue-300)' }} />
        <span className="reg-mark rm-bl" style={{ borderColor: 'var(--blue-300)' }} />
        <span className="reg-mark rm-br" style={{ borderColor: 'var(--blue-300)' }} />
        <div className="inspect-caption" style={{ color: 'var(--blue-300)' }}>
          <span className="inspect-dot" />
          ÁREA DE INSPEÇÃO · FOCO NÍTIDO
        </div>
        <TermField navy dim />
        <div ref={sharpRef} className="term-clip" style={{ clipPath: 'circle(0px at 70% 50%)' }}>
          <TermField navy sharp />
        </div>
        <LensReticle innerRef={frameRef} circle width={234} height={234} markColor={'var(--blue-300)'}
          initialLeft="calc(72% - 117px)" initialTop="calc(52% - 117px)" />
      </div>
      <div style={{ position: 'relative', zIndex: 5, maxWidth: 'var(--container)', margin: '0 auto', padding: '144px 32px 128px', pointerEvents: 'none' }}>
        <div style={{ maxWidth: 600 }}>
          <Eyebrow tone="inverse">{t.eyebrow}</Eyebrow>
          <h1 style={{
            fontFamily: 'var(--font-sans)', fontSize: 'var(--fs-display)', lineHeight: 'var(--lh-tight)',
            letterSpacing: 'var(--ls-display)', fontWeight: 'var(--fw-bold)', color: 'var(--cream-50)',
            margin: '20px 0 0', maxWidth: 560, textWrap: 'balance',
          }}>
            {msg.h}
          </h1>
          <p style={{
            fontFamily: 'var(--font-sans)', fontSize: 'var(--fs-body-lg)', lineHeight: 'var(--lh-normal)',
            color: 'var(--blue-300)', margin: '24px 0 0', maxWidth: 440, textWrap: 'pretty',
          }}>
            {msg.sub}
          </p>
          <div style={{ display: 'flex', gap: 24, marginTop: 36, flexWrap: 'wrap', alignItems: 'center', pointerEvents: 'auto' }}>
            <Button size="lg" variant="inverse" onClick={() => scrollTo('contato')} style={{ whiteSpace: 'nowrap' }}>
              Solicitar orçamento
            </Button>
            <a href="https://wa.me/5534996847972" target="_blank" rel="noopener" style={{
              display: 'inline-flex', alignItems: 'center', gap: 9,
              fontFamily: 'var(--font-sans)', fontSize: 'var(--fs-body-lg)', fontWeight: 'var(--fw-semibold)',
              color: 'var(--cream-50)', textDecoration: 'none',
            }}>
              <Icon name="message-circle" size={18} color="var(--blue-300)" />
              Falar pelo WhatsApp
            </a>
          </div>
          <ProvaRow items={prova} tone="inverse" />
        </div>
      </div>
    </section>
  );
}

// ── Format C — Editorial: type-led, registration-mark title block ────────────
function EditorialHero({ t, scrollTo }) {
  const { Button } = window.MXDEngenharia_e41562;
  const msg = HEADLINES[t.headlineIndex] || HEADLINES[0];
  const heroImg = t.heroImage || '';
  const meta = ['CREA-SP 123.234', 'ART em todos os laudos', 'NBR 14653'];
  return (
    <section id="inicio" style={{
      position: 'relative', overflow: 'hidden', borderBottom: '1px solid var(--line-cool)',
      background: heroImg
        ? `center / cover no-repeat url("${heroImg}")`
        : 'repeating-linear-gradient(135deg, var(--blue-900) 0, var(--blue-900) 22px, #0d2034 22px, #0d2034 44px)',
    }}>
      {/* left-anchored scrim — image breathes to the right */}
      <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(100deg, rgba(8,17,30,0.90) 0%, rgba(8,17,30,0.74) 38%, rgba(8,17,30,0.40) 70%, rgba(8,17,30,0.22) 100%)' }} />
      <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(180deg, rgba(8,17,30,0.30) 0%, rgba(8,17,30,0) 30%, rgba(8,17,30,0.45) 100%)' }} />

      {!heroImg && (
        <div style={{
          position: 'absolute', top: 16, left: 16, fontFamily: 'var(--font-mono, monospace)',
          fontSize: 12, letterSpacing: '0.04em', color: 'rgba(255,255,255,0.6)', textTransform: 'uppercase',
        }}>
          foto de fundo aqui
        </div>
      )}

      <div style={{
        position: 'relative', maxWidth: 'var(--container)', margin: '0 auto',
        padding: '150px 32px 130px',
      }}>
        <div style={{ maxWidth: 620 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
            <span style={{
              fontFamily: 'var(--font-mono)', fontSize: 'var(--fs-eyebrow)', fontWeight: 'var(--fw-medium)',
              letterSpacing: 'var(--ls-eyebrow)', textTransform: 'uppercase', color: 'var(--blue-300)',
            }}>{t.eyebrow}</span>
          </div>
          <h1 style={{
            fontFamily: 'var(--font-sans)', fontSize: 'var(--fs-display)', lineHeight: 'var(--lh-tight)',
            letterSpacing: 'var(--ls-display)', fontWeight: 'var(--fw-bold)', color: '#fff',
            margin: '26px 0 0', maxWidth: 600, textWrap: 'balance',
          }}>
            {msg.h}
          </h1>
          <p style={{
            fontFamily: 'var(--font-sans)', fontSize: 'var(--fs-body-lg)', lineHeight: 'var(--lh-relaxed)',
            color: 'rgba(255,255,255,0.80)', margin: '24px 0 0', maxWidth: 480, textWrap: 'pretty',
          }}>
            {msg.sub}
          </p>
          <div style={{ display: 'flex', gap: 12, marginTop: 38, flexWrap: 'wrap' }}>
            <Button size="lg" onClick={() => scrollTo('contato')} iconRight={<Icon name="arrow-right" size={18} color="currentColor" />} style={{ whiteSpace: 'nowrap' }}>
              Solicitar orçamento
            </Button>
            <Button size="lg" variant="secondary" onClick={() => window.open('https://wa.me/5534996847972?text=' + encodeURIComponent('Olá! Vim pelo site da MXD Engenharia e gostaria de solicitar um orçamento de perícia/avaliação.'), '_blank', 'noopener')} iconLeft={<Icon name="message-circle" size={18} color="var(--blue-700)" />} style={{ background: '#fff', borderColor: '#fff', color: 'var(--blue-700)', whiteSpace: 'nowrap' }}>
              Falar pelo WhatsApp
            </Button>
          </div>
        </div>

      </div>
    </section>
  );
}

function Hero({ t, scrollTo }) {
  const fmt = t.heroFormat || 'Imersivo';
  if (fmt === 'Editorial') return <EditorialHero t={t} scrollTo={scrollTo} />;
  if (fmt === 'Painel') return <PanelHero t={t} scrollTo={scrollTo} />;
  return <ImmersiveHero t={t} scrollTo={scrollTo} />;
}
window.Hero = Hero;
