// Shared chrome — Header, Footer, WhatsApp float, router hook
// Loaded as text/babel.

const WHATSAPP_URL = 'https://wa.me/5511999905029?text=Ol%C3%A1!%20Gostaria%20de%20um%20or%C3%A7amento.';

// Clean-URL routing (History API). Legacy #/ URLs are rewritten to paths in index.html.
function currentPath() {
  return window.FaukoSEO.route();
}

function useHashRoute() {
  const [route, setRoute] = React.useState(currentPath());
  React.useEffect(() => {
    const onNav = () => setRoute(currentPath());
    window.addEventListener('popstate', onNav);
    window.addEventListener('fauko:route', onNav);
    return () => {
      window.removeEventListener('popstate', onNav);
      window.removeEventListener('fauko:route', onNav);
    };
  }, []);
  return route;
}

function navigate(path) {
  if (currentPath() !== path) {
    window.history.pushState(null, '', window.FaukoSEO.href(path));
    window.dispatchEvent(new Event('fauko:route'));
    window.scrollTo({ top: 0, behavior: 'instant' });
  }
}

function Link({ to, children, className, onClick, ...rest }) {
  return (
    <a
      href={window.FaukoSEO.href(to)}
      className={className}
      onClick={(e) => {
        // let the browser handle new-tab / new-window clicks
        if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey || e.button !== 0) return;
        e.preventDefault();
        navigate(to);
        onClick && onClick(e);
      }}
      {...rest}
    >
      {children}
    </a>
  );
}

const NAV_ITEMS = [
  { to: '/', label: 'Home' },
  { to: '/produtos', label: 'Produtos' },
  { to: '/quem-somos', label: 'Quem Somos' },
];

function Header() {
  const route = useHashRoute();
  const [open, setOpen] = React.useState(false);
  const isActive = (to) => {
    if (to === '/') return route === '/' || route === '';
    return route.startsWith(to);
  };
  return (
    <React.Fragment>
      <header className="fk-header">
        <div className="container fk-header__inner">
          <Link to="/" aria-label="Fauko Import — Home">
            <img src="assets/fauko-logo.png" alt="Fauko Import" className="fk-logo" />
          </Link>
          <nav className="fk-nav" aria-label="Principal">
            {NAV_ITEMS.map(item => (
              <Link key={item.to} to={item.to} className={isActive(item.to) ? 'active' : ''}>
                {item.label}
              </Link>
            ))}
          </nav>
          <div className="fk-header__cta">
            <a className="btn btn--whats" href={WHATSAPP_URL} target="_blank" rel="noopener">
              <WhatsIcon /> Orçamento
            </a>
          </div>
          <button className="fk-burger" aria-label="Abrir menu" onClick={() => setOpen(true)}>
            <svg viewBox="0 0 24 24" fill="none" strokeWidth="2" strokeLinecap="round">
              <path d="M4 7h16M4 12h16M4 17h16" />
            </svg>
          </button>
        </div>
      </header>
      <MobileMenu open={open} onClose={() => setOpen(false)} isActive={isActive} />
    </React.Fragment>
  );
}

function MobileMenu({ open, onClose, isActive }) {
  return (
    <div className={'fk-mobile-menu' + (open ? ' open' : '')}>
      <div className="fk-mobile-menu__head">
        <img src="assets/fauko-logo-white.png" alt="Fauko" />
        <button className="fk-mobile-menu__close" onClick={onClose} aria-label="Fechar menu">
          <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
            <path d="M6 6l12 12M18 6l-12 12" />
          </svg>
        </button>
      </div>
      {NAV_ITEMS.map(item => (
        <Link key={item.to} to={item.to} onClick={onClose}>
          {item.label}
        </Link>
      ))}
      <a className="btn btn--light" style={{ marginTop: 24, justifyContent: 'center' }}
        href={WHATSAPP_URL} target="_blank" rel="noopener">
        <WhatsIcon /> Falar no WhatsApp
      </a>
      <div style={{ marginTop: 'auto', fontSize: 13, color: 'rgba(255,255,255,0.7)', paddingTop: 32 }}>
        Av. Padre Arlindo Vieira, 213 - 12<br />
        Vila Vermelha, São Paulo - SP
      </div>
    </div>
  );
}

function Footer() {
  return (
    <footer className="fk-footer">
      <div className="container fk-footer__inner">
        <div className="fk-footer__grid">
          <div>
            <img src="assets/fauko-logo-white.png" alt="Fauko Import" className="fk-footer__logo" />
            <p style={{ fontSize: 14, lineHeight: 1.6, maxWidth: 320 }}>
              Importadora oficial FILL-RITE e Adam Pumps. Equipamentos para abastecimento
              de combustíveis, ARLA 32 e lubrificantes desde 1990.
            </p>
            <div className="fk-footer__social">
              <a href="https://instagram.com/fauko.import" target="_blank" rel="noopener" aria-label="Instagram @fauko.import">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8">
                  <rect x="3" y="3" width="18" height="18" rx="5" />
                  <circle cx="12" cy="12" r="4" />
                  <circle cx="17.5" cy="6.5" r="1" fill="currentColor" />
                </svg>
              </a>
              <a href="mailto:comercial@fauko.com.br" aria-label="E-mail">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8">
                  <rect x="3" y="5" width="18" height="14" rx="2" />
                  <path d="M3 7l9 6 9-6" />
                </svg>
              </a>
              <a href={WHATSAPP_URL} target="_blank" rel="noopener" aria-label="WhatsApp">
                <WhatsIcon />
              </a>
            </div>
          </div>
          <div>
            <h4>Navegação</h4>
            <ul>
              {NAV_ITEMS.map(it => <li key={it.to}><Link to={it.to}>{it.label}</Link></li>)}
              <li><Link to="/produtos?cat=Bombas">Bombas</Link></li>
              <li><Link to="/produtos?cat=Medidores de Vazão">Medidores</Link></li>
            </ul>
          </div>
          <div>
            <h4>Contato</h4>
            <ul>
              <li>comercial@fauko.com.br</li>
              <li>(11) 4210-2755 · (11) 99990-5029</li>
              <li>Segunda à sexta, 08h00 às 18h00</li>
              <li>Av. Padre Arlindo Vieira, 213 - 12<br/>Vila Vermelha</li>
              <li>São Paulo - SP, 04297-000</li>
            </ul>
          </div>
          <div>
            <h4>Marcas</h4>
            <ul>
              <li>FILL-RITE (EUA)</li>
              <li>Adam Pumps</li>
              <li>GPI · Wertco · Gespasa</li>
            </ul>
          </div>
        </div>
        <div className="fk-footer__bottom">
          <span>© {new Date().getFullYear()} Fauko Import — Todos os direitos reservados.</span>
          <span>Petroserv Comercial Ltda · CNPJ 64.955.255/0001-90 · Distribuidor oficial FILL-RITE & Adam Pumps</span>
        </div>
        <div className="fk-footer__credit" style={{
          marginTop: 20, paddingTop: 18, borderTop: '1px solid rgba(255,255,255,0.08)',
          textAlign: 'center', fontSize: 13, color: 'rgba(255,255,255,0.55)'
        }}>
          <a href="https://wa.me/551129752348?text=Ol%C3%A1!%20Estava%20vendo%20o%20site%20da%20Fauko%20Import%20e%20gostaria%20de%20fazer%20um%20or%C3%A7amento%20de%20site." target="_blank" rel="noopener" style={{ color: 'inherit' }}>
            Desenvolvido por V4 Antunes Bueno &amp; Co
          </a>
        </div>
      </div>
    </footer>
  );
}

function WhatsIcon() {
  return (
    <svg viewBox="0 0 24 24" fill="currentColor" width="18" height="18" aria-hidden="true">
      <path d="M17.5 14.4c-.3-.2-1.7-.9-2-1-.3-.1-.5-.2-.7.2-.2.3-.7 1-.9 1.2-.2.2-.3.2-.6.1-.3-.2-1.3-.5-2.4-1.5-.9-.8-1.5-1.8-1.7-2.1-.2-.3 0-.5.1-.7.1-.1.3-.3.5-.5.1-.2.2-.3.3-.5.1-.2 0-.4 0-.6 0-.2-.7-1.7-1-2.3-.2-.6-.5-.5-.7-.5h-.6c-.2 0-.5.1-.8.4-.3.3-1 1-1 2.5s1.1 2.9 1.2 3.1c.1.2 2.1 3.2 5.1 4.5.7.3 1.3.5 1.7.6.7.2 1.4.2 1.9.1.6-.1 1.7-.7 2-1.4.2-.7.2-1.2.2-1.4-.1-.2-.3-.3-.6-.4z M12 2.2C6.6 2.2 2.2 6.6 2.2 12c0 1.7.4 3.3 1.3 4.7L2 22l5.4-1.4c1.4.7 2.9 1.1 4.6 1.1 5.4 0 9.8-4.4 9.8-9.8 0-2.6-1-5-2.9-6.9C17 3.1 14.6 2.2 12 2.2z m0 17.8c-1.5 0-2.9-.4-4.2-1.2l-.3-.2-3.1.8.8-3-.2-.3C4.2 14.8 3.8 13.4 3.8 12 3.8 7.5 7.5 3.8 12 3.8c2.2 0 4.2.9 5.8 2.4 1.5 1.5 2.4 3.6 2.4 5.8 0 4.5-3.7 8.2-8.2 8.2z"/>
    </svg>
  );
}

function WhatsFloat() {
  return (
    <a className="fk-whats-float" href={WHATSAPP_URL} target="_blank" rel="noopener" aria-label="Falar no WhatsApp">
      <WhatsIcon />
    </a>
  );
}

// Scroll to top on route change
function ScrollToTop() {
  const route = useHashRoute();
  React.useEffect(() => { window.scrollTo({ top: 0, behavior: 'instant' }); }, [route]);
  return null;
}

// Spec value formatter: "70.0" → "70", "1.5" → "1.5", "1/3 HP" / "110/220" / texts pass through untouched.
function formatSpec(v) {
  if (v == null) return v;
  const s = String(v).trim();
  return /^-?\d+([.,]\d+)?$/.test(s) ? String(parseFloat(s.replace(',', '.'))) : v;
}

// Split a "combustível compatível" field into clean, capitalized chips.
// Collapses newlines, keeps parenthetical qualifiers attached to their term
// (e.g. "Solventes (sob consulta)") and never splits on " e " inside parentheses.
function parseFluids(raw) {
  if (!raw) return [];
  let s = String(raw).replace(/\s+/g, ' ').replace(/\s*\(/g, ' (').trim();
  const held = [];
  s = s.replace(/\([^)]*\)/g, m => { held.push(m); return '\u0000' + (held.length - 1) + '\u0000'; });
  return s.split(/[,;·]|\se\s/i)
    .map(t => t.replace(/\u0000(\d+)\u0000/g, (_, i) => held[+i]).trim())
    .map(t => t.replace(/^[.–-]+|[.]+$/g, '').trim())
    .filter(t => t && t !== '(' && t.length > 1)
    .map(t => t.charAt(0).toUpperCase() + t.slice(1));
}

window.FaukoChrome = { Header, Footer, WhatsFloat, Link, navigate, useHashRoute, ScrollToTop, WhatsIcon, WHATSAPP_URL, formatSpec, parseFluids };
