// Tendências — módulo compartilhado (constantes, navegação, navbar, footer, whatsapp)
const WA_LINK = "https://wa.me/5511963052949?text=Ol%C3%A1!%20Gostaria%20de%20um%20or%C3%A7amento.";
const WA_TEC = "https://wa.me/5511963052949?text=Ol%C3%A1!%20Sou%20arquiteto(a)%2C%20construtora%20ou%20designer%20e%20gostaria%20de%20falar%20com%20o%20time%20t%C3%A9cnico.";
const INSTA = "https://instagram.com/tendenciasbp";
const EMAIL = "contato@tendenciasbp.com.br";
const EMAIL_LINK = "mailto:contato@tendenciasbp.com.br";
const ADDRESS = "R. Fernão Dias, 356 - Pinheiros, São Paulo - SP, 05427-000";
const MAPS_DIR = "https://www.google.com/maps/dir/?api=1&destination=R.%20Fern%C3%A3o%20Dias%2C%20356%20-%20Pinheiros%2C%20S%C3%A3o%20Paulo%20-%20SP%2C%2005427-000";
// Embed oficial do Perfil da Empresa no Google: mostra o card do negocio
// com nome, avaliacao e horario, em vez de apenas um marcador no mapa.
const MAPS_EMBED = "https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d7314.234905837669!2d-46.69819132489093!3d-23.5642247787978!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x94ce5790aa29367d%3A0x8dd24fb76fd4bfec!2sTend%C3%AAncias%20Box%20%26%20Persianas!5e0!3m2!1spt-BR!2sbr!4v1786555172101!5m2!1spt-BR!2sbr";
const HOME = "index.html";
const PAGE_CLIENTE = "cliente-final.html";
const PAGE_OBRAS = "obras-corporativas.html";
const IS_HOME = !!window.IS_HOME;

function scrollToId(id) {
  const el = document.getElementById(id);
  if (!el) return;
  const y = el.getBoundingClientRect().top + window.scrollY - 80;
  window.scrollTo({ top: y, behavior: "smooth" });
}

// Robust scroll-reveal: reveals in-view elements immediately, observes the rest,
// and a safety timeout guarantees nothing stays hidden. Returns a cleanup fn.
function setupReveal() {
  const els = Array.from(document.querySelectorAll(".reveal"));
  document.body.classList.add("anim");
  const reveal = (el) => el.classList.remove("pre");
  const inView = (el) => {
    const r = el.getBoundingClientRect();
    return r.top < window.innerHeight * 0.9 && r.bottom > 0;
  };
  els.forEach((el) => {if (inView(el)) reveal(el);else el.classList.add("pre");});
  const obs = new IntersectionObserver((entries) => {
    entries.forEach((e) => {if (e.isIntersecting) {reveal(e.target);obs.unobserve(e.target);}});
  }, { threshold: 0.12, rootMargin: "0px 0px -8% 0px" });
  els.forEach((el) => {if (el.classList.contains("pre")) obs.observe(el);});
  const safety = setTimeout(() => els.forEach(reveal), 2500);
  return () => {obs.disconnect();clearTimeout(safety);};
}

// Link to a section that lives on the home page (scroll if already home, else navigate)
function SectionLink({ id, children, className, onNav }) {
  const href = IS_HOME ? "#" + id : HOME + "#" + id;
  return (
    <a className={className} href={href} onClick={(e) => {
      if (IS_HOME) {e.preventDefault();scrollToId(id);}
      if (onNav) onNav();
    }}>{children}</a>);

}

const PRODUCTS = [
{ id: "persianas", name: "Persianas e Cortinas", desc: "Tecidos e componentes Amorim Cortinas. Veja todos os modelos e decida qual combina mais com o seu projeto.", img: "assets/persianas/persiana_rolo_stillo.webp", page: "persianas.html" },
{ id: "box", name: "Box de Vidro Temperado", desc: "Box sob medida em vidro temperado Blindex, instalado pela nossa equipe.", img: "assets/produtos-box.webp", page: "box.html" },
{ id: "espelhos", name: "Espelhos", desc: "Espelhos lapidados sob medida para banheiros, salas, halls, lojas e academias.", img: "assets/produtos-espelho.webp", page: "espelhos.html" },
{ id: "engenharias", name: "Engenharias e Projetos Especiais", desc: "Guarda-corpo, fechamentos de área, divisórias, prateleiras, tampos e mesas. Projetos feitos sob medida.", img: "assets/engenharias/eng-divisoria.webp", page: "engenharias.html" },
{ id: "peliculas", name: "Películas", desc: "Segurança (PS04), Privacidade e Controle Térmico.", img: "assets/engenharias/eng-pelicula.webp", page: "peliculas.html" },
{ id: "manutencao", name: "Manutenção", desc: "Ajustes, regulagens e troca de peças em boxes e persianas já instalados.", img: "assets/proc-5.webp", page: "manutencao.html" }];

const INDEX_TREE = [
  { label: "Tendências Box e Persianas", href: "index.html" },
  { label: "Produtos e Serviços", sectionId: "produtos-home", defaultOpen: true, children: [
    { label: "Persianas", href: "persianas.html", children: [
      { label: "Rolô", href: "persianas.html#cat-rolo" },
      { label: "Rolô Stillo", href: "persianas.html#cat-rolo-stillo" },
      { label: "Romana", href: "persianas.html#cat-romana" },
      { label: "Illuminê", href: "persianas.html#cat-illumine" },
      { label: "Lumière", href: "persianas.html#cat-lumiere" },
      { label: "Melíade", href: "persianas.html#cat-meliade" },
      { label: "Eternity", href: "persianas.html#cat-eternity" },
      { label: "Eternity Line", href: "persianas.html#cat-eternity-line" },
      { label: "Infinity", href: "persianas.html#cat-infinity" },
      { label: "Celular", href: "persianas.html#cat-celular" },
      { label: "Plissada", href: "persianas.html#cat-plissada" },
      { label: "Passione", href: "persianas.html#cat-passione" },
      { label: "Galaxy", href: "persianas.html#cat-galaxy" },
      { label: "Sublime", href: "persianas.html#cat-sublime" },
      { label: "Painel", href: "persianas.html#cat-painel" },
      { label: "Vertical", href: "persianas.html#cat-vertical" },
      { label: "PH Alumínio", href: "persianas.html#cat-ph-aluminio" },
      { label: "PH Curve", href: "persianas.html#cat-ph-curve" },
      { label: "Bambu, Madeira e Sintética", href: "persianas.html#cat-bambu-madeira-e-sintetica" },
      { label: "Cortina de Teto", href: "persianas.html#cat-cortina-de-teto" }
    ]},
    { label: "Box de Vidro Temperado", href: "box.html", children: [
      { label: "Box de Correr", href: "box.html?cfg=correr", children: [
        { label: "2 peças", href: "box.html?cfg=correr_2" },
        { label: "3 peças", href: "box.html?cfg=correr_3" },
        { label: "4 peças", href: "box.html?cfg=correr_4" }
      ]},
      { label: "Box de Abrir", href: "box.html?cfg=abrir", children: [
        { label: "Com transpasse", href: "box.html?cfg=abrir_comtranspasse" },
        { label: "Sem transpasse", href: "box.html?cfg=abrir_semtranspasse" }
      ]},
      { label: "Box Articulado", href: "box.html?cfg=articulado" },
      { label: "Box Transfer", href: "box.html?cfg=transfer" },
      { label: "Box de Canto", href: "box.html?cfg=canto" }
    ]},
    { label: "Espelhos", href: "espelhos.html", children: [
      { label: "Bisotê", href: "espelhos.html#cat-bisote" },
      { label: "Orgânico / Redondo", href: "espelhos.html#cat-organico_redondo" },
      { label: "Junções", href: "espelhos.html#cat-juncoes" }
    ]},
    { label: "Películas", href: "peliculas.html", children: [
      { label: "Bronze Natural", href: "peliculas.html#cat-bronze-natural" },
      { label: "Espelhada", href: "peliculas.html#cat-espelhada" },
      { label: "Privacidade", href: "peliculas.html#cat-privacidade" },
      { label: "Fumê", href: "peliculas.html#cat-fume" }
    ]},
    { label: "Engenharias e Projetos Especiais", href: "engenharias.html", children: [
      { label: "Projetos Especiais", href: "engenharias.html#projetos-especiais" },
      { label: "Guarda-Corpo", href: "engenharias.html#engenharias" },
      { label: "Fechamento de Área", href: "engenharias.html#engenharias" },
      { label: "Divisórias", href: "engenharias.html#engenharias" },
      { label: "Prateleiras", href: "engenharias.html#decoracoes" },
      { label: "Tampos", href: "engenharias.html#decoracoes" },
      { label: "Mesas", href: "engenharias.html#decoracoes" }
    ]},
    { label: "Manutenção", href: "manutencao.html", children: [
      { label: "Manutenção de Box", href: "manutencao.html#serv-box" },
      { label: "Manutenção de Persiana Rolô", href: "manutencao.html#serv-rolo" }
    ]}
  ]},
  { label: "Cliente Final", href: "cliente-final.html" },
  { label: "Obras Corporativas", href: "obras-corporativas.html", children: [
    { label: "Quem Atendemos", href: "obras-corporativas.html#quem-atendemos" },
    { label: "Por que a Tendências", href: "obras-corporativas.html#por-que-tendencias" }
  ]},
  { label: "Nossa História", sectionId: "historia" },
  { label: "Depoimentos", sectionId: "depoimentos" },
  { label: "Showroom", sectionId: "showroom" },
  { label: "Contato", sectionId: "contato" },
  { label: "WhatsApp", href: WA_LINK, external: true }
];

function IndexNode({ node, depth, onClose }) {
  const [expanded, setExpanded] = React.useState(!!node.defaultOpen);
  const hasChildren = node.children && node.children.length > 0;
  const label = node.sectionId
    ? <SectionLink id={node.sectionId} className="idx-link" onNav={onClose}>{node.label}</SectionLink>
    : node.external
    ? <a className="idx-link" href={node.href} target="_blank" rel="noopener" onClick={onClose}>{node.label}</a>
    : node.href
    ? <a className="idx-link" href={node.href} onClick={onClose}>{node.label}</a>
    : <span className="idx-link idx-static">{node.label}</span>;
  return (
    <li className="idx-node">
      <div className="idx-row" style={{ paddingLeft: (depth * 16) + "px" }}>
        {label}
        {hasChildren &&
          <button
            className={"idx-toggle" + (expanded ? " is-open" : "")}
            aria-label={expanded ? "Recolher" : "Expandir"}
            aria-expanded={expanded}
            onClick={() => setExpanded(!expanded)}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" aria-hidden="true">
              <path d="M8 10l4 4 4-4" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
            </svg>
          </button>
        }
      </div>
      {hasChildren && expanded &&
        <ul className="idx-children">
          {node.children.map((c, i) => <IndexNode key={i} node={c} depth={depth + 1} onClose={onClose} />)}
        </ul>
      }
    </li>);
}

function SiteIndex() {
  const [open, setOpen] = React.useState(false);
  const close = () => setOpen(false);
  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") setOpen(false); };
    document.addEventListener("keydown", onKey);
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => { document.removeEventListener("keydown", onKey); document.body.style.overflow = prev; };
  }, [open]);
  return (
    <React.Fragment>
      <button className="nav-index-btn" aria-label="Índice do site" aria-expanded={open} onClick={() => setOpen(true)}>
        <span></span><span></span><span></span>
      </button>
      {open &&
        <div className="idx-overlay" onClick={close}>
          <aside className="idx-panel" role="dialog" aria-label="Índice do site" onClick={(e) => e.stopPropagation()}>
            <div className="idx-panel-head">
              <span className="idx-panel-title">Navegação</span>
              <button className="idx-close" aria-label="Fechar" onClick={close}>×</button>
            </div>
            <nav className="idx-tree">
              <ul>{INDEX_TREE.map((n, i) => <IndexNode key={i} node={n} depth={0} onClose={close} />)}</ul>
            </nav>
          </aside>
        </div>
      }
    </React.Fragment>);
}

function Navbar() {
  return (
    <header className="nav">
      <div className="nav-inner">
        <a className="nav-logo" href={HOME} onClick={(e) => {
          if (IS_HOME) {e.preventDefault();window.scrollTo({ top: 0, behavior: "smooth" });}
        }}>
          <img src="assets/logo-color.png" alt="Tendências — Box e Persianas" />
        </a>
        <nav className="nav-links">
          <SectionLink id="produtos-home">Produtos e Serviços</SectionLink>
          <a href={PAGE_CLIENTE}>Cliente Final</a>
          <a href={PAGE_OBRAS}>Obras Corporativas</a>
          <SectionLink id="historia">Nossa História</SectionLink>
          <a href={IS_HOME ? "#contato" : HOME + "#contato"} onClick={(e) => { if (IS_HOME) { e.preventDefault(); scrollToId("contato"); } }}>Contato</a>
        </nav>
        <div style={{ display: "flex", alignItems: "center", gap: "8px" }}>
          <a className="nav-whatsapp" href={WA_LINK} target="_blank" rel="noopener" style={{ background: "var(--vermelho)", color: "#fff", borderRadius: "6px", padding: "6px 16px", fontWeight: 600, fontSize: "0.875rem", whiteSpace: "nowrap", textDecoration: "none" }}>WhatsApp</a>
          <SiteIndex />
        </div>
      </div>
    </header>);

}

function Footer() {
  return (
    <footer className="footer" data-screen-label="Footer">
      <div className="wrap">
        <div className="footer-grid">
          <div className="footer-logo">
            <img src="assets/logo-footer.png" alt="Tendências" loading="lazy" />
            <p>Empresa referência com 23 anos de mercado e equipe própria.</p>
            <a className="footer-ig" href={INSTA} target="_blank" rel="noopener" aria-label="Instagram da Tendências">
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" aria-hidden="true">
                <rect x="3" y="3" width="18" height="18" rx="5" stroke="currentColor" strokeWidth="1.6"></rect>
                <circle cx="12" cy="12" r="4" stroke="currentColor" strokeWidth="1.6"></circle>
                <circle cx="17.2" cy="6.8" r="1.1" fill="currentColor"></circle>
              </svg>
              <span>@tendenciasbp</span>
            </a>
          </div>
          <div>
            <h4>Atendimento</h4>
            <ul>
              <li><a href={PAGE_CLIENTE}>Cliente Final</a></li>
              <li><a href={PAGE_OBRAS}>Obras Corporativas</a></li>
              <li><a href={WA_LINK} target="_blank" rel="noopener">Pedir orçamento</a></li>
            </ul>
          </div>
          <div>
            <h4>Empresa</h4>
            <ul>
              <li><SectionLink id="historia">Nossa História</SectionLink></li>
              <li><SectionLink id="depoimentos">Depoimentos</SectionLink></li>
            </ul>
          </div>
          <div>
            <h4>Contato</h4>
            <ul>
              <li><a href={WA_LINK} target="_blank" rel="noopener">WhatsApp</a></li>
              <li><a href={EMAIL_LINK}>{EMAIL}</a></li>
              <li><a href={INSTA} target="_blank" rel="noopener">Instagram</a></li>
              <li><SectionLink id="contato">Endereço e horários</SectionLink></li>
            </ul>
          </div>
        </div>
        <div className="footer-bottom">
          <span>© 2026 Tendências Box &amp; Persianas · Desde 2003</span>
          <span><a href={EMAIL_LINK} style={{ color: "inherit", textDecoration: "none" }}>{EMAIL}</a> · <a href={WA_LINK} target="_blank" rel="noopener" style={{ color: "inherit", textDecoration: "none" }}>WhatsApp (11) 96305-2949</a></span>
        </div>
      </div>
    </footer>);

}

function WaFloat() {
  return (
    <a className="wa-float" href={WA_LINK} target="_blank" rel="noopener" aria-label="WhatsApp" title="Falar no WhatsApp">
      <svg width="26" height="26" viewBox="0 0 24 24" fill="none" aria-hidden="true">
        <path d="M12 3a9 9 0 0 0-7.8 13.5L3 21l4.7-1.2A9 9 0 1 0 12 3Z" stroke="#F5F0EB" strokeWidth="1.6" strokeLinejoin="round"></path>
        <path d="M9 8.5c.4 2.8 3.7 6 6.4 6.4l.9-1.6-2-1.2-1 .7c-.9-.4-2-1.5-2.4-2.4l.7-1-1.2-2-1.4.5Z" fill="#F5F0EB"></path>
      </svg>
    </a>);

}

Object.assign(window, { Navbar, Footer, WaFloat, SectionLink, scrollToId, setupReveal, PRODUCTS, WA_LINK, WA_TEC, INSTA, EMAIL, EMAIL_LINK, ADDRESS, MAPS_DIR, MAPS_EMBED, HOME, PAGE_CLIENTE, PAGE_OBRAS, IS_HOME });