/* global React */
(function () {
const { useState, useEffect } = React;

// ============ Router (hash-based) ============
function useRoute() {
  const get = () => (location.hash.replace(/^#\/?/, '') || 'home').split('?')[0];
  const [route, setRoute] = useState(get);
  useEffect(() => {
    const on = () => { setRoute(get()); window.scrollTo({ top: 0, behavior: 'instant' }); };
    window.addEventListener('hashchange', on);
    return () => window.removeEventListener('hashchange', on);
  }, []);
  return route;
}

function navigate(route) {
  location.hash = '/' + route;
}

// ============ Theme ============
function useTheme() {
  const [theme, setTheme] = useState(() => {
    try { return localStorage.getItem('pc-theme') || 'light'; } catch { return 'light'; }
  });
  useEffect(() => {
    document.documentElement.setAttribute('data-theme', theme);
    try { localStorage.setItem('pc-theme', theme); } catch {}
  }, [theme]);
  return [theme, setTheme];
}

// ============ Nav ============
function Nav({ route }) {
  const [theme, setTheme] = window.useTheme();
  const items = [
    { id: 'home', label: 'Início' },
    { id: 'servicos', label: 'Serviços' },
    { id: 'sobre', label: 'Sobre' },
    { id: 'contato', label: 'Contato' },
  ];
  return (
    <nav className="nav">
      <div className="nav-inner">
        <a href="#/home" className="brand" onClick={(e) => { e.preventDefault(); navigate('home'); }}>
          {/* <div className="brand-mark">PC</div> */}
          <div className="brand-name">
            <img src="images/Logo_reduzida.png"
            alt="Logo empresa"
            style={{height: 48, width: "auto", objectFit: "contain"}}
            />
          </div>
          <div className="brand-name">
            <strong>Perfect Consulting</strong>
            <span>Engenharia &middot; Automação &middot; Licitações</span>
          </div>
        </a>
        <ul className="nav-links">
          {items.map(it => (
            <li key={it.id}>
              <a
                href={'#/' + it.id}
                onClick={(e) => { e.preventDefault(); navigate(it.id); }}
                className={route === it.id ? 'active' : ''}
              >
                {it.label}
              </a>
            </li>
          ))}
        </ul>
        <div className="nav-right">
          <button
            className="theme-toggle"
            aria-label="Alternar tema"
            onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}
            title={theme === 'light' ? 'Modo escuro' : 'Modo claro'}
          >
            {theme === 'light' ? (
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z" />
              </svg>
            ) : (
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <circle cx="12" cy="12" r="4" />
                <line x1="12" y1="2" x2="12" y2="5" />
                <line x1="12" y1="19" x2="12" y2="22" />
                <line x1="4.93" y1="4.93" x2="7.05" y2="7.05" />
                <line x1="16.95" y1="16.95" x2="19.07" y2="19.07" />
                <line x1="2" y1="12" x2="5" y2="12" />
                <line x1="19" y1="12" x2="22" y2="12" />
                <line x1="4.93" y1="19.07" x2="7.05" y2="16.95" />
                <line x1="16.95" y1="7.05" x2="19.07" y2="4.93" />
              </svg>
            )}
          </button>
          <button className="btn btn--ink" onClick={() => navigate('contato')}>
            Solicitar orçamento <span className="arr">→</span>
          </button>
        </div>
      </div>
    </nav>
  );
}

// ============ Footer ============
function Footer() {
  return (
    <footer className="footer">
      <div className="footer-inner">
        <div className="footer-top">
          <div>
            <div className="brand" style={{ marginBottom: 20 }}>
              <div className="brand-mark">PC</div>
              <div className="brand-name">
                <strong>Perfect Consulting</strong>
                <span>Desde 2025 &middot; Belo Horizonte &middot; MG</span>
              </div>
            </div>
            <div className="footer-slogan">
              Mitigando <em>riscos</em>, maximizando <em>resultados</em>.
            </div>
          </div>
          <div>
            <h4>Navegação</h4>
            <ul>
              <li onClick={() => navigate('home')}>Início</li>
              <li onClick={() => navigate('servicos')}>Serviços</li>
              <li onClick={() => navigate('sobre')}>Sobre nós</li>
              <li onClick={() => navigate('contato')}>Contato</li>
            </ul>
          </div>
          <div>
            <h4>Serviços</h4>
            <ul>
              <li onClick={() => navigate('servicos')}>Licitações públicas</li>
              <li onClick={() => navigate('servicos')}>Orçamentos em BIM</li>
              <li onClick={() => navigate('servicos')}>Auditoria de obras</li>
              <li onClick={() => navigate('servicos')}>Consultoria contínua</li>
            </ul>
          </div>
          <div>
            <h4>Contato</h4>
            <ul>
              <li>comercial@perfectconsulting.com.br</li>
              <li>(31) 98881-7140</li>
              {/* <li>Av. Paulista, 000 — São Paulo</li> */}{/*SOMENTE INSERIR APÓS TER ENDEREÇO FISICO*/}
            </ul>
          </div>
        </div>
        <div className="footer-bot">
          <span>© 2026 Perfect Consulting · CNPJ 61.122.302/0001-27</span>
          <span className="footer-lgpd">
            <a onClick={() => navigate('privacidade')}>Política de privacidade</a>
            <span aria-hidden="true">·</span>
            <a onClick={() => { try { localStorage.removeItem('pc-cookies'); location.reload(); } catch {} }}>Cookies</a>
          </span>
          {/* <span>Site v1 · mai/2026</span> */}{/*VERSÃO DO SITE*/}
        </div>
      </div>
    </footer>
  );
}

// ============ Reveal-on-scroll wrapper ============
function Reveal({ children, delay = 0, as: As = 'div', className = '', ...rest }) {
  const ref = React.useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const obs = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting) {
          setTimeout(() => e.target.classList.add('in'), delay);
          obs.unobserve(e.target);
        }
      });
    }, { threshold: 0.12 });
    obs.observe(el);
    return () => obs.disconnect();
  }, [delay]);
  return <As ref={ref} className={('reveal ' + className).trim()} {...rest}>{children}</As>;
}

// ============ Placeholder image ============
function Placeholder({ label, height = '100%', stripe = 'diag', tone = 'ink' }) {
  // tone: 'ink' (neutral) or 'orange'
  const stripeColor = tone === 'orange'
    ? 'color-mix(in oklab, var(--orange) 22%, transparent)'
    : 'color-mix(in oklab, var(--ink) 8%, transparent)';
  const bgTint = tone === 'orange'
    ? 'color-mix(in oklab, var(--orange) 6%, var(--bg-elev))'
    : 'color-mix(in oklab, var(--ink) 3%, var(--bg-elev))';
  const angle = stripe === 'reverse' ? 45 : 135;
  return (
    <div style={{
      position: 'relative',
      width: '100%',
      height,
      background: `repeating-linear-gradient(${angle}deg, transparent 0 14px, ${stripeColor} 14px 15px), ${bgTint}`,
      border: '1px solid var(--line)',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
    }}>
      <span style={{
        fontFamily: 'var(--mono)',
        fontSize: 10,
        letterSpacing: '0.2em',
        textTransform: 'uppercase',
        color: 'var(--muted)',
        background: 'var(--bg)',
        padding: '6px 12px',
        border: '1px solid var(--line)',
      }}>{label}</span>
    </div>
  );
}

// ============ Animated counter ============
function Counter({ value, suffix = '', prefix = '', duration = 1600 }) {
  const ref = React.useRef(null);
  const [shown, setShown] = useState('0');
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    let started = false;
    const obs = new IntersectionObserver((entries) => {
      if (started || !entries[0].isIntersecting) return;
      started = true;
      const start = performance.now();
      const isFloat = /\./.test(String(value));
      const target = parseFloat(value);
      function tick(now) {
        const t = Math.min(1, (now - start) / duration);
        const eased = 1 - Math.pow(1 - t, 3);
        const cur = target * eased;
        setShown(isFloat ? cur.toFixed(1) : Math.round(cur).toLocaleString('pt-BR'));
        if (t < 1) requestAnimationFrame(tick);
        else setShown(value.toLocaleString ? value.toLocaleString('pt-BR') : String(value));
      }
      requestAnimationFrame(tick);
    }, { threshold: 0.4 });
    obs.observe(el);
    return () => obs.disconnect();
  }, [value, duration]);
  return <span ref={ref}>{prefix}{shown}{suffix}</span>;
}

// ============ BIM Comparator (real drag) ============
function Compare({ heightPx = 520 }) {
  const ref = React.useRef(null);
  const imgRef = React.useRef(null);
  const [pos, setPos] = useState(100);
  const dragging = React.useRef(false);
  const animated = React.useRef(false);
  const minPosRef = React.useRef(0);

  // Calculates the minimum bar position: the point where the right image
  // exactly fills the visible area with no striped background showing.
  const calcMinPos = () => {
    const container = ref.current;
    const img = imgRef.current;
    if (!container || !img || !img.naturalWidth) return;
    const cw = container.getBoundingClientRect().width;
    const imgAspect = img.naturalWidth / img.naturalHeight;
    const boxAspect = cw / heightPx;
    const renderedW = imgAspect <= boxAspect ? heightPx * imgAspect : cw;
    const newMin = Math.max(0, (1 - renderedW / cw) * 100);
    minPosRef.current = newMin;
    setPos(p => Math.max(p, newMin));
  };

  const move = (clientX) => {
    const el = ref.current;
    if (!el) return;
    const r = el.getBoundingClientRect();
    const p = Math.max(minPosRef.current, Math.min(100, ((clientX - r.left) / r.width) * 100));
    setPos(p);
  };

  // Auto-animate on first viewport entry to hint interactivity
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const obs = new IntersectionObserver((entries) => {
      if (animated.current || !entries[0].isIntersecting) return;
      animated.current = true;
      obs.unobserve(el);

      // Animate within the valid range [minPos, 100]
      // Targets as fractions of the range above minPos
      const rawTargets = [0.05, 0.65, 0.4];
      const durations  = [1100, 950, 800];
      let cur = 100;
      let step = 0;

      function runStep() {
        if (step >= rawTargets.length || dragging.current) return;
        const range = 100 - minPosRef.current;
        const target = minPosRef.current + rawTargets[step] * range;
        const duration = durations[step];
        const from = cur;
        const t0 = performance.now();
        function frame(now) {
          if (dragging.current) return;
          const t = Math.min(1, (now - t0) / duration);
          const e = t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t;
          cur = from + (target - from) * e;
          setPos(cur);
          if (t < 1) requestAnimationFrame(frame);
          else { cur = target; setPos(target); step++; setTimeout(runStep, 200); }
        }
        requestAnimationFrame(frame);
      }

      setTimeout(runStep, 700);
    }, { threshold: 0.35 });
    obs.observe(el);
    return () => obs.disconnect();
  }, []);

  useEffect(() => {
    window.addEventListener('resize', calcMinPos);
    return () => window.removeEventListener('resize', calcMinPos);
  }, []);

  useEffect(() => {
    const onMove = (e) => { if (dragging.current) move(e.clientX ?? (e.touches?.[0]?.clientX)); };
    const onUp = () => { dragging.current = false; };
    window.addEventListener('mousemove', onMove);
    window.addEventListener('mouseup', onUp);
    window.addEventListener('touchmove', onMove);
    window.addEventListener('touchend', onUp);
    return () => {
      window.removeEventListener('mousemove', onMove);
      window.removeEventListener('mouseup', onUp);
      window.removeEventListener('touchmove', onMove);
      window.removeEventListener('touchend', onUp);
    };
  }, []);

  return (
    <div
      className="compare"
      ref={ref}
      onMouseDown={(e) => { dragging.current = true; move(e.clientX); }}
      onTouchStart={(e) => { dragging.current = true; move(e.touches[0].clientX); }}
      style={{ height: heightPx }}
    >
      <div className="compare-pane compare-pane--before">
        <img src="images/Obra_ref.jpeg" alt="Obra de referência" className="compare-pane-img" />
        <span className="compare-label compare-label--left">Modelo 3D · BIM</span>
        <div style={{ position: 'absolute', left: 24, bottom: 24, fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--muted)' }}>
          Render arquitetônico
        </div>
      </div>
      <div className="compare-pane compare-pane--after" style={{ left: `${pos}%` }}>
        <img
          ref={imgRef}
          src="images/Orçamento_ref.jpeg"
          alt="Orçamento de referência"
          className="compare-pane-img"
          onLoad={calcMinPos}
          style={{
            right: 'auto',
            width: `${(100 / Math.max(100 - pos, 0.1)) * 100}%`,
            objectFit: 'contain',
            objectPosition: 'left center',
          }}
        />
      </div>
      <span className="compare-label compare-label--right">Quantitativos extraídos</span>
      <div style={{ position: 'absolute', right: 24, bottom: 24, fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--orange)', zIndex: 3, pointerEvents: 'none' }}>
        → Planilha orçamentária
      </div>
      <div className="compare-line" style={{ left: pos + '%' }}></div>
      <button
        className="compare-handle"
        style={{ left: pos + '%' }}
        aria-label="Arraste para comparar"
        onMouseDown={(e) => { e.stopPropagation(); dragging.current = true; }}
      >⇆</button>
      <div className="compare-hint">arraste &larr;  &rarr;</div>
    </div>
  );
}

// ============ Cookie banner (LGPD) ============
function CookieBanner() {
  const [shown, setShown] = useState(false);
  const [expanded, setExpanded] = useState(false);
  const [prefs, setPrefs] = useState({ necessary: true, analytics: false });

  useEffect(() => {
    let stored;
    try { stored = localStorage.getItem('pc-cookies'); } catch {}
    if (!stored) setShown(true);
  }, []);

  const persist = (choice) => {
    try { localStorage.setItem('pc-cookies', JSON.stringify({ ...choice, ts: Date.now() })); } catch {}
    setShown(false);
  };

  if (!shown) return null;

  return (
    <div className="cookie-banner" role="dialog" aria-label="Aviso de cookies">
      <div className="cookie-banner-inner">
        <div className="cookie-banner-head">
          <span className="muted-meta">⚲ LGPD · cookies</span>
          <h3>Usamos cookies para fazer este site funcionar.</h3>
          <p>
            Cookies estritamente necessários estão sempre ativos. Para cookies analíticos
            (estatísticas anônimas de uso), precisamos da sua autorização — conforme a Lei nº 13.709/2018.
            Leia nossa <a onClick={(e) => { e.preventDefault(); persist({ necessary: true, analytics: false }); navigate('privacidade'); }} href="#/privacidade">Política de Privacidade</a>.
          </p>
        </div>
        {expanded && (
          <div className="cookie-prefs">
            <label className="cookie-pref">
              <input type="checkbox" checked disabled />
              <div>
                <strong>Estritamente necessários</strong>
                <span>Sessão, preferência de tema. Sempre ativos — dispensam consentimento.</span>
              </div>
            </label>
            <label className="cookie-pref">
              <input
                type="checkbox"
                checked={prefs.analytics}
                onChange={(e) => setPrefs({ ...prefs, analytics: e.target.checked })}
              />
              <div>
                <strong>Analíticos</strong>
                <span>Métricas anônimas de páginas mais visitadas. Pode revogar a qualquer tempo.</span>
              </div>
            </label>
          </div>
        )}
        <div className="cookie-actions">
          {!expanded ? (
            <>
              <button className="btn btn--ghost cookie-btn-sm" onClick={() => setExpanded(true)}>Personalizar</button>
              <button className="btn btn--ghost cookie-btn-sm" onClick={() => persist({ necessary: true, analytics: false })}>Rejeitar não necessários</button>
              <button className="btn btn--ghost cookie-btn-sm" onClick={() => persist({ necessary: true, analytics: true })}>Aceitar todos</button>
            </>
          ) : (
            <>
              <button className="btn btn--ghost cookie-btn-sm" onClick={() => setExpanded(false)}>Voltar</button>
              <button className="btn cookie-btn-sm" onClick={() => persist(prefs)}>Salvar escolhas</button>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

// ============ WhatsApp button ============
function WhatsAppButton() {
  const phone = '5531988817140';
  const message = encodeURIComponent('Olá! Gostaria de solicitar um orçamento.');
  return (
    <a
      href={`https://wa.me/${phone}?text=${message}`}
      target="_blank"
      rel="noopener noreferrer"
      aria-label="Fale conosco pelo WhatsApp"
      style={{
        position: 'fixed',
        bottom: 28,
        right: 28,
        zIndex: 999,
        width: 56,
        height: 56,
        borderRadius: '50%',
        background: '#25D366',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        boxShadow: '0 4px 16px rgba(0,0,0,0.18)',
        textDecoration: 'none',
        transition: 'transform 0.2s, box-shadow 0.2s',
      }}
      onMouseEnter={e => { e.currentTarget.style.transform = 'scale(1.1)'; e.currentTarget.style.boxShadow = '0 6px 20px rgba(0,0,0,0.24)'; }}
      onMouseLeave={e => { e.currentTarget.style.transform = 'scale(1)'; e.currentTarget.style.boxShadow = '0 4px 16px rgba(0,0,0,0.18)'; }}
    >
      <svg xmlns="http://www.w3.org/2000/svg" width="28" height="28" viewBox="0 0 24 24" fill="white">
        <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z"/>
      </svg>
    </a>
  );
}

// Expose everything
Object.assign(window, { useRoute, navigate, useTheme, Nav, Footer, Reveal, Placeholder, Counter, Compare, CookieBanner, WhatsAppButton });
})();
