// Shared components for the Silverio Estaleiro prototype.
// Exposes: Header, Footer, Placeholder, Eyebrow, ContactModal, useI18n,
// SectionHead, useScrollFade, ProjectsCarousel, ServiceCard, etc.

const { useState, useEffect, useRef, useCallback, createContext, useContext } = React;

// ---------- I18N ----------
const STRINGS = {
  pt: {
    nav: {
      services: "Serviços",
      construction: "Construção",
      refit: "Refit",
      design: "Design & Engenharia",
      projects: "Projetos",
      b2b: "B2B",
      about: "Sobre",
      contact: "Contato"
    },
    hero: {
      eyebrow: "01 — APRESENTAÇÃO",
      title: "Seu barco sempre em boas mãos.",
      sub: "Gestão, projeto, construção e reforma de embarcações.",
      cta: "Conheça nossos projetos",
      ctaSec: "Falar com a equipe",
      slideOf: "de",
      next: "Próximo",
      prev: "Anterior"
    },
    pillars: {
      eyebrow: "02 — PROPOSTA DE VALOR",
      title: "Três pilares numa única mesa.",
      sub: "Design, gestão e engenharia operam integrados — sem ruído entre disciplinas, com decisão técnica coerente do primeiro traço à entrega.",
      items: [
      { idx: "01", label: "Engenharia & Design", body: "Equipe familiarizada com cálculos para embarcações de performance e certificações internacionais, tais como DNV e Bureau Veritas." },
      { idx: "02", label: "Gestão de Obras", body: "Controle de obras consolidado na indústria naval e aplicado em ERP próprio que integra cronograma físico-financeiro, fornecedores e produção." },
      { idx: "03", label: "Execução Especializada", body: "Primeiro estaleiro a produzir móveis 100% em compósito. Infusão a vácuo e fibras especiais são o dia a dia da produção." }]

    },
    services: {
      eyebrow: "03 — SERVIÇOS",
      title: "Quatro frentes, um mesmo padrão técnico.",
      sub: "Todos os nossos produtos são resultado de desenvolvimento contínuo, e hoje possuem validação pelo mercado — venha conhecer de perto.",
      list: [
      { code: "S/01", name: "Construções One-off e Seriadas", body: "De embarcações completas a peças especiais: qualificação para entrega de leveza e segurança.", link: "Ver linha de construção" },
      { code: "S/02", name: "Refit & Reformas", body: "Reconfiguração de layouts, ergonomia aplicada, reconstrução de partes ou reformas completas com o mesmo padrão das construções.", link: "Ver portfólio de refit" },
      { code: "S/03", name: "Design & Engenharia", body: "Projetos de embarcações completas ou módulos, tais como hard tops, espaços gourmet, projetos luminotécnicos e revisão de layouts.", link: "Ver capacidades" },
      { code: "S/04", name: "Gestão & Consultoria B2B", body: "Escritório e ERP próprios para controle de obras náuticas e navais; metodologia e construção de treinamentos para outros estaleiros.", link: "Soluções para estaleiros" }]

    },
    diff: {
      eyebrow: "04 — DIFERENCIAIS",
      title: "O que separa um estaleiro técnico de um genérico.",
      list: [
      { n: "01", t: "Pioneirismo em mobiliário 100% em compósito", b: "Primeiro estaleiro do Brasil a produzir mobiliário integralmente em compósito. Menos peso, mais durabilidade." },
      { n: "02", t: "Integração total entre design, engenharia e execução", b: "Decisões técnicas tomadas de forma integrada, com alinhamento direto entre concepção e construção, reduzindo retrabalho e aumentando a qualidade final." },
      { n: "03", t: "Construção one-off com domínio de infusão em epóxi", b: "Especialização em embarcações sob medida com controle estrutural, leveza e precisão, utilizando processos avançados de compósitos." },
      { n: "04", t: "Forte atuação em refit e transformação estrutural", b: "Capacidade de intervir em embarcações existentes com segurança técnica, melhorando ergonomia, desempenho e uso real." }]

    },
    projects: {
      eyebrow: "05 — PORTFÓLIO",
      title: "Projetos em produção e entregues.",
      sub: "Veleiros, catamarãs e trawlers — one-off, série limitada e refits completos.",
      view: "Ver projeto"
    },
    b2b: {
      eyebrow: "06 — B2B / SOLUÇÕES PARA ESTALEIROS",
      title: "O que aprendemos construindo, transferimos para quem constrói.",
      sub: "Quatro produtos pensados para estaleiros pares e clientes internacionais.",
      list: [
      { code: "B/01", t: "Metodologia de Ensino", b: "Currículo aplicado em técnica e gestão naval, validado em operação real." },
      { code: "B/02", t: "Cursos In Company", b: "Treinamento da sua equipe na sua planta — ou no nosso galpão em Tijucas." },
      { code: "B/03", t: "Estruturação de Gestão", b: "Implantação de ERP e metodologia de obra com previsibilidade física e financeira." },
      { code: "B/04", t: "Gestão de Obras Internacionais", b: "Coordenação de obras navais para clientes internacionais sob normas classificadoras." }]

    },
    about: {
      eyebrow: "07 — SOBRE",
      title: "Estaleiro em operação contínua há 8 anos em Tijucas, SC.",
      body: "O Silverio Estaleiro nasceu da convicção de que a construção náutica e naval no Brasil precisa elevar seu padrão técnico. Operamos com processos controlados, engenharia aplicada e foco em leveza, precisão e confiabilidade estrutural. Design, gestão e engenharia ficam na mesma mesa — Silvana (25 anos de design), Heros (sócio fundador, gestão e construção).",
      stats: [
      { n: "8", l: "anos em operação contínua" },
      { n: "100%", l: "compósito em mobiliário pioneiro" },
      { n: "3", l: "sociedades classificadoras" },
      { n: "1", l: "ERP proprietário em produção" }],

      cta: "Conheça a equipe"
    },
    cta: {
      eyebrow: "08 — PRÓXIMO PASSO",
      title: "Vamos avaliar seu projeto.",
      sub: "Conte sobre sua embarcação. Retornamos em até 48 horas com uma agenda de conversa técnica — não comercial.",
      btn: "Iniciar conversa",
      btnSec: "Visitar o estaleiro"
    },
    footer: {
      tagline: "Seu barco sempre em boas mãos.",
      address: "Rua Eloi Francisco dos Anjos, 443 — Galpão 8 · Sul do Rio · Tijucas, SC · 88205-340 · Brasil",
      addressUrl: "https://www.google.com/maps/search/?api=1&query=Rua+Eloi+Francisco+dos+Anjos+443+Galp%C3%A3o+8+Sul+do+Rio+Tijucas+SC+88205-340",
      cols: [
      { h: "Serviços", links: [
        { label: "Construção One-off", href: "construcao.html" },
        { label: "Refit & Transformações", href: "refit.html" },
        { label: "Design & Engenharia", href: "design.html" },
        { label: "Consultoria B2B", href: "b2b.html" }] },
      { h: "Estaleiro", links: [
        { label: "Quem Somos", href: "quemsomos.html" },
        { label: "Carreiras", href: "carreiras.html" }] },
      { h: "Contato", links: [
        { label: "WhatsApp", href: "https://wa.me/5547991208818" },
        { label: "E-mail", href: "mailto:silvana.silverio@silverioestaleiro.com.br" },
        { label: "Instagram", href: "https://instagram.com/silverio_estaleiro" },
        { label: "Facebook", href: "https://facebook.com/silverio_estaleiro" },
        { label: "LinkedIn", href: "https://linkedin.com/company/silverioestaleiro" },
        { label: "YouTube", href: "https://youtube.com/@silverio_estaleiro" }] }],

      legal: "© 2026 Silverio Estaleiro · CNPJ 50.180.768/0001-62"
    },
    visit: {
      title: "Visitar o estaleiro.",
      sub: "Recebemos clientes e parceiros mediante agendamento. Envie seu pedido e confirmamos a janela em até 48h.",
      address: "Rua Eloi Francisco dos Anjos, 443 — Galpão 8 · Sul do Rio · Tijucas, SC · 88205-340 · Brasil",
      hours: "Seg – Sex · 09h00 – 17h00",
      submit: "Solicitar visita",
      sent: "Recebido. Confirmamos sua visita em até 48h."
    },
    contact: {
      title: "Iniciar uma conversa.",
      sub: "Preencha abaixo. Resposta em até 48h por e-mail ou WhatsApp.",
      name: "Nome completo",
      email: "E-mail",
      phone: "Telefone / WhatsApp",
      type: "Tipo de projeto",
      types: ["Construção one-off", "Refit / transformação", "Design & engenharia", "Consultoria B2B / cursos", "Outro"],
      msg: "Sobre o projeto (embarcação, prazo, escopo)",
      submit: "Enviar pedido",
      sent: "Recebido. Retornamos em até 48h."
    }
  },
  en: {
    nav: {
      services: "Services",
      construction: "Construction",
      refit: "Refit",
      design: "Design & Engineering",
      projects: "Projects",
      b2b: "B2B",
      about: "About",
      contact: "Contact"
    },
    hero: {
      eyebrow: "01 — INTRODUCTION",
      title: "Your boat, always in good hands.",
      sub: "Management, design, construction and refit of boats.",
      cta: "See our projects",
      ctaSec: "Talk to the team",
      slideOf: "of",
      next: "Next",
      prev: "Previous"
    },
    pillars: {
      eyebrow: "02 — VALUE PROPOSITION",
      title: "Three pillars at one table.",
      sub: "Design, management and engineering operate integrated — no friction between disciplines, coherent technical decisions from first sketch to delivery.",
      items: [
      { idx: "01", label: "Engineering & Design", body: "A team fluent in calculations for performance vessels and international certifications such as DNV and Bureau Veritas." },
      { idx: "02", label: "Project Management", body: "Construction control consolidated in the naval industry and applied through our in-house ERP, integrating physical-financial scheduling, suppliers and production." },
      { idx: "03", label: "Specialized Execution", body: "First shipyard to produce 100% composite furniture. Vacuum infusion and special fibers are part of daily production." }]

    },
    services: {
      eyebrow: "03 — SERVICES",
      title: "Four fronts, one technical standard.",
      sub: "All our products are the result of continuous development and are now validated by the market — come and see them up close.",
      list: [
      { code: "S/01", name: "One-off & Series Construction", body: "From complete vessels to special parts: qualification to deliver lightness and safety.", link: "Construction line" },
      { code: "S/02", name: "Refit & Renovations", body: "Layout reconfiguration, applied ergonomics, partial rebuilds or complete refits to the same standard as our builds.", link: "Refit portfolio" },
      { code: "S/03", name: "Design & Engineering", body: "Complete vessel projects or modules — hard tops, gourmet areas, lighting design, layout reviews.", link: "Capabilities" },
      { code: "S/04", name: "B2B Management & Consulting", body: "In-house office and ERP for naval and shipyard project control; methodology and training development for other shipyards.", link: "Shipyard solutions" }]

    },
    diff: {
      eyebrow: "04 — DIFFERENTIATORS",
      title: "What separates a technical shipyard from a generic one.",
      list: [
      { n: "01", t: "Pioneers in 100% composite furniture", b: "First Brazilian shipyard to produce furniture entirely in composite. Less weight, more durability." },
      { n: "02", t: "Full integration of design, engineering and execution", b: "Technical decisions made in an integrated way, with direct alignment between concept and construction — reducing rework and raising final quality." },
      { n: "03", t: "One-off construction with epoxy infusion mastery", b: "Specialization in custom vessels with structural control, lightness and precision, using advanced composite processes." },
      { n: "04", t: "Strong refit and structural transformation practice", b: "Capable of intervening in existing vessels with technical safety, improving ergonomics, performance and real-world use." }]

    },
    projects: {
      eyebrow: "05 — PORTFOLIO",
      title: "Projects in production and delivered.",
      sub: "Sailboats, catamarans and trawlers — one-off, limited series and complete refits.",
      view: "View project"
    },
    b2b: {
      eyebrow: "06 — B2B / SHIPYARD SOLUTIONS",
      title: "What we learned building, we transfer to those who build.",
      sub: "Four products designed for peer shipyards and international clients.",
      list: [
      { code: "B/01", t: "Teaching Methodology", b: "Applied curriculum in naval technique and management, validated in real operation." },
      { code: "B/02", t: "In-company Courses", b: "Training your team at your facility — or at our shipyard in Tijucas." },
      { code: "B/03", t: "Management Structuring", b: "ERP rollout and construction methodology with physical and financial predictability." },
      { code: "B/04", t: "International Project Management", b: "Coordination of naval projects for international clients under classification standards." }]

    },
    about: {
      eyebrow: "07 — ABOUT",
      title: "A continuously operating shipyard for 8 years in Tijucas, Brazil.",
      body: "Silverio Estaleiro was born from the conviction that naval construction in Brazil needs to raise its technical bar. We operate with controlled processes, applied engineering and a focus on lightness, precision and structural reliability. Design, management and engineering share one table — Silvana (24 years in design), Heros (founding partner, management and construction) and Emilio (20 years in naval engineering with ABS/DNV/BV).",
      stats: [
      { n: "8", l: "years in continuous operation" },
      { n: "100%", l: "composite in pioneering furniture" },
      { n: "3", l: "classification societies" },
      { n: "1", l: "proprietary ERP in production" }],

      cta: "Meet the team"
    },
    cta: {
      eyebrow: "08 — NEXT STEP",
      title: "Let's evaluate your project.",
      sub: "Tell us about your boat. We respond within 48 hours with a technical conversation agenda — not a sales pitch.",
      btn: "Start a conversation",
      btnSec: "Visit the shipyard"
    },
    footer: {
      tagline: "Your boat, always in good hands.",
      address: "Rua Eloi Francisco dos Anjos, 443 — Galpão 8 · Sul do Rio · Tijucas, SC · 88205-340 · Brazil",
      addressUrl: "https://www.google.com/maps/search/?api=1&query=Rua+Eloi+Francisco+dos+Anjos+443+Galp%C3%A3o+8+Sul+do+Rio+Tijucas+SC+88205-340",
      cols: [
      { h: "Services", links: [
        { label: "One-off Construction", href: "construcao.html" },
        { label: "Refit & Transformation", href: "refit.html" },
        { label: "Design & Engineering", href: "design.html" },
        { label: "B2B Consulting", href: "b2b.html" }] },
      { h: "Shipyard", links: [
        { label: "About", href: "quemsomos.html" },
        { label: "Careers", href: "carreiras.html" }] },
      { h: "Contact", links: [
        { label: "WhatsApp", href: "https://wa.me/5547991208818" },
        { label: "Email", href: "mailto:silvana.silverio@silverioestaleiro.com.br" },
        { label: "Instagram", href: "https://instagram.com/silverio_estaleiro" },
        { label: "Facebook", href: "https://facebook.com/silverio_estaleiro" },
        { label: "LinkedIn", href: "https://linkedin.com/company/silverioestaleiro" },
        { label: "YouTube", href: "https://youtube.com/@silverio_estaleiro" }] }],

      legal: "© 2026 Silverio Estaleiro · CNPJ 50.180.768/0001-62"
    },
    visit: {
      title: "Visit the shipyard.",
      sub: "We host clients and partners by appointment. Submit your request and we'll confirm the window within 48h.",
      address: "Rua Eloi Francisco dos Anjos, 443 — Galpão 8 · Sul do Rio · Tijucas, SC · 88205-340 · Brazil",
      hours: "Mon – Fri · 9:00 – 17:00",
      submit: "Request a visit",
      sent: "Received. We'll confirm your visit within 48h."
    },
    contact: {
      title: "Start a conversation.",
      sub: "Fill below. Reply within 48h by email or WhatsApp.",
      name: "Full name",
      email: "Email",
      phone: "Phone / WhatsApp",
      type: "Project type",
      types: ["One-off construction", "Refit / transformation", "Design & engineering", "B2B consulting / courses", "Other"],
      msg: "About the project (vessel, timeline, scope)",
      submit: "Send request",
      sent: "Received. We'll reply within 48h."
    }
  }
};

const I18nCtx = createContext(null);

function useI18n() {return useContext(I18nCtx);}

function I18nProvider({ children }) {
  const [lang, setLang] = useState(() => {
    try {return localStorage.getItem('silverio-lang') || 'pt';} catch {return 'pt';}
  });
  useEffect(() => {try {localStorage.setItem('silverio-lang', lang);} catch {}}, [lang]);
  const t = STRINGS[lang];
  return React.createElement(I18nCtx.Provider, { value: { lang, setLang, t } }, children);
}

// ---------- HEADER ----------
function Header({ active, onContact, onDark = false }) {
  const { lang, setLang, t } = useI18n();
  const isInternal = active && active !== "home";
  const prefix = isInternal ? "index.html" : "";
  const navItems = [
  { id: "services", href: prefix + "#services", label: t.nav.services },
  { id: "projects", href: prefix + "#projects", label: t.nav.projects },
  { id: "b2b", href: prefix + "#b2b", label: t.nav.b2b },
  { id: "about", href: "quemsomos.html", label: t.nav.about }];

  const items = navItems;

  return (
    <header className={"site-header" + (onDark ? " on-dark" : "")}>
      <div className="shell">
        <div className="header-row">
          <a className="brand-mark" href="index.html" aria-label="Silverio Estaleiro">
            <img src="assets/logo.png" alt="Silverio Estaleiro" className="brand-logo" />
          </a>
          <nav className="primary-nav" aria-label="Primary">
            {items.map((it) =>
            <a key={it.id} href={it.href} className={active === it.id ? "active" : ""}>{it.label}</a>
            )}
          </nav>
          <div className="header-utilities">
            <div className="lang-switch" role="tablist" aria-label="Language">
              {['pt', 'en'].map((L) =>
              <button key={L} role="tab" aria-selected={lang === L}
              className={lang === L ? 'active' : ''}
              onClick={() => setLang(L)}>
                  {L.toUpperCase()}
                </button>
              )}
            </div>
            <button className="btn btn-ghost" style={{ padding: '10px 18px', fontSize: 13 }} onClick={onContact}>
              {t.nav.contact}<span className="arrow"></span>
            </button>
          </div>
        </div>
      </div>
    </header>);

}

// ---------- FOOTER ----------
function Footer() {
  const { t } = useI18n();
  return (
    <footer className="site-footer">
      <div className="shell">
        <div className="row">
          <div>
            <div className="brand-mark" style={{ color: 'var(--paper)', marginBottom: 24 }}>
              <img src="assets/logo-white.png" alt="Silverio Estaleiro" className="brand-logo brand-logo-footer" style={{ objectFit: "scale-down" }} />
            </div>
            <div className="h-3" style={{ maxWidth: '12ch', color: 'var(--paper)', marginBottom: 24, fontWeight: "500", height: "70.5833px", fontSize: "20px", width: "202px" }}>
              {t.footer.tagline}
            </div>
            <div className="tech" style={{ color: 'inherit' }}>
              <a href={t.footer.addressUrl} target="_blank" rel="noopener noreferrer" style={{ color: 'inherit', textDecoration: 'none', borderBottom: '1px solid color-mix(in srgb, currentColor 30%, transparent)' }}>
                {t.footer.address}
              </a>
            </div>
          </div>
          {t.footer.cols.map((c, i) =>
          <div key={i}>
              <h5>{c.h}</h5>
              <ul>{c.links.map((l) => <li key={l.label}><a href={l.href} target={l.href && l.href.startsWith('http') ? '_blank' : undefined} rel={l.href && l.href.startsWith('http') ? 'noopener noreferrer' : undefined}>{l.label}</a></li>)}</ul>
            </div>
          )}
        </div>
        <div className="legal">
          <span>{t.footer.legal}</span>
          <span>BR · TIJUCAS · SC · CEP 88205-340</span>
        </div>
      </div>
    </footer>);

}

// ---------- PLACEHOLDER ----------
function Placeholder({ label, code, meta, ratio = "16/9", light = false, height, children, style }) {
  const s = { aspectRatio: height ? undefined : ratio, height: height, ...style };
  return (
    <div className={"ph" + (light ? " light" : "")} style={s}>
      <span className="corner-bl"></span>
      <span className="corner-br"></span>
      {code && <div className="ph-tl">{code}</div>}
      {meta && <div className="ph-tr">{meta}</div>}
      <div className="ph-center">{label}</div>
      {children}
    </div>);

}

// ---------- MEDIA (real image/video w/ technical overlay metadata) ----------
function Media({ src, video, code, meta, ratio = "16/9", height, alt = "", style, dark = true, objectPosition = "center" }) {
  const s = { aspectRatio: height ? undefined : ratio, height: height, ...style };
  const isVideo = !!video;
  return (
    <div className={"media" + (dark ? " media-dark" : "")} style={s}>
      <span className="corner-bl"></span>
      <span className="corner-br"></span>
      {isVideo ?
      <video src={video} autoPlay muted loop playsInline preload="metadata" style={{ objectPosition }} /> :

      <img src={src} alt={alt} loading="lazy" style={{ objectPosition, objectFit: "cover" }} />
      }
      {code && <div className="media-tl" style={{ opacity: "0" }}>{code}</div>}
      {meta && <div className="media-tr" style={{ opacity: "0" }}>{meta}</div>}
    </div>);

}

// ---------- SECTION HEAD ----------
function SectionHead({ eyebrow, title, sub, action }) {
  return (
    <div className="section-head">
      <div className="left">
        <div className="eyebrow" style={{ marginBottom: 24 }}>{eyebrow}</div>
        <h2 className="h-1" style={{ margin: 0, maxWidth: '15ch' }}>{title}</h2>
      </div>
      <div className="right body-lg">
        {sub}
        {action && <div style={{ marginTop: 28 }}>{action}</div>}
      </div>
    </div>);

}

// ---------- SCROLL FADE ----------
function useScrollFade() {
  useEffect(() => {
    const els = document.querySelectorAll('.fade');
    const vh = window.innerHeight || document.documentElement.clientHeight;
    // Reveal anything already in/near viewport on attach
    els.forEach((el) => {
      const r = el.getBoundingClientRect();
      if (r.top < vh * 0.95 && r.bottom > 0) el.classList.add('in');
    });
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) {e.target.classList.add('in');io.unobserve(e.target);}
      });
    }, { rootMargin: '0px 0px -5% 0px', threshold: 0.01 });
    els.forEach((el) => {if (!el.classList.contains('in')) io.observe(el);});
    // Failsafe: after 2s, reveal anything still hidden so nothing is permanently invisible
    const fail = setTimeout(() => {
      document.querySelectorAll('.fade:not(.in)').forEach((el) => el.classList.add('in'));
    }, 2000);
    return () => {io.disconnect();clearTimeout(fail);};
  }, []);
}

// ---------- CONTACT MODAL ----------
function ContactModal({ open, onClose }) {
  const { t } = useI18n();
  const [sent, setSent] = useState(false);
  useEffect(() => {
    if (!open) return;
    const onKey = (e) => {if (e.key === 'Escape') onClose();};
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open, onClose]);
  useEffect(() => {if (open) setSent(false);}, [open]);

  return (
    <div className={"modal-back" + (open ? " open" : "")} onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <button className="close" onClick={onClose} aria-label="Close">
          <svg width="14" height="14" viewBox="0 0 14 14"><path d="M1 1l12 12M13 1L1 13" stroke="currentColor" strokeWidth="1.4" fill="none" /></svg>
        </button>
        {!sent ?
        <>
            <div className="eyebrow" style={{ marginBottom: 16 }}>09 — CONTATO</div>
            <h3 className="h-2" style={{ margin: '0 0 12px', maxWidth: '14ch' }}>{t.contact.title}</h3>
            <p className="body" style={{ margin: 0 }}>{t.contact.sub}</p>
            <form onSubmit={(e) => {e.preventDefault();setSent(true);}}>
              <div className="form-grid">
                <div><label>{t.contact.name}</label><input required /></div>
                <div><label>{t.contact.email}</label><input type="email" required /></div>
                <div><label>{t.contact.phone}</label><input /></div>
                <div>
                  <label>{t.contact.type}</label>
                  <select>{t.contact.types.map((x) => <option key={x}>{x}</option>)}</select>
                </div>
                <div className="full"><label>{t.contact.msg}</label><textarea rows="3"></textarea></div>
              </div>
              <button type="submit" className="btn btn-primary">{t.contact.submit}<span className="arrow"></span></button>
            </form>
          </> :

        <div style={{ padding: '24px 0' }}>
            <div className="eyebrow" style={{ marginBottom: 16, color: 'var(--green-deep)' }}>OK · 200</div>
            <h3 className="h-2" style={{ margin: '0 0 16px' }}>{t.contact.sent}</h3>
            <button className="btn-link" onClick={onClose}>← {t.nav.contact}</button>
          </div>
        }
      </div>
    </div>);

}


// ---------- VISIT MODAL (map + form) ----------
function VisitModal({ open, onClose }) {
  const { t } = useI18n();
  const [sent, setSent] = useState(false);
  useEffect(() => {
    if (!open) return;
    const onKey = (e) => {if (e.key === 'Escape') onClose();};
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open, onClose]);
  useEffect(() => {if (open) setSent(false);}, [open]);

  return (
    <div className={"modal-back" + (open ? " open" : "")} onClick={onClose}>
      <div className="modal modal-wide" onClick={(e) => e.stopPropagation()}>
        <button className="close" onClick={onClose} aria-label="Close">
          <svg width="14" height="14" viewBox="0 0 14 14"><path d="M1 1l12 12M13 1L1 13" stroke="currentColor" strokeWidth="1.4" fill="none" /></svg>
        </button>
        {!sent ?
        <div className="visit-grid">
            <div className="visit-map">
              <iframe
              src="https://www.google.com/maps?q=Rua+Eloi+Francisco+dos+Anjos+443+Galp%C3%A3o+8+Sul+do+Rio+Tijucas+SC+88205-340&z=16&output=embed"
              title="Silverio Estaleiro — Tijucas, SC"
              loading="lazy"
              referrerPolicy="no-referrer-when-downgrade"
              allowFullScreen />
            
              <div className="visit-meta">
                <div className="mono visit-meta-k">TIJUCAS · SC</div>
                <div className="visit-meta-v">{t.visit.address}</div>
                <div className="visit-meta-v" style={{ marginTop: 4 }}>{t.visit.hours}</div>
                <div className="visit-meta-v mono" style={{ marginTop: 12, fontSize: 11, opacity: 0.6 }}>CEP 88205-340</div>
              </div>
            </div>
            <div className="visit-form">
              <div className="eyebrow" style={{ marginBottom: 16 }}>VISITA · AGENDAMENTO</div>
              <h3 className="h-2" style={{ margin: '0 0 12px', maxWidth: '14ch' }}>{t.visit.title}</h3>
              <p className="body" style={{ margin: '0 0 24px' }}>{t.visit.sub}</p>
              <form onSubmit={(e) => {e.preventDefault();setSent(true);}}>
                <div className="form-grid">
                  <div className="full"><label>{t.contact.name}</label><input required /></div>
                  <div><label>{t.contact.email}</label><input type="email" required /></div>
                  <div><label>{t.contact.phone}</label><input /></div>
                  <div className="full"><label>{t.contact.msg}</label><textarea rows="3"></textarea></div>
                </div>
                <button type="submit" className="btn btn-primary">{t.visit.submit}<span className="arrow"></span></button>
              </form>
            </div>
          </div> :

        <div style={{ padding: '24px 0' }}>
            <div className="eyebrow" style={{ marginBottom: 16, color: 'var(--green-deep)' }}>OK · 200</div>
            <h3 className="h-2" style={{ margin: '0 0 16px' }}>{t.visit.sent}</h3>
            <button className="btn-link" onClick={onClose}>← {t.nav.contact}</button>
          </div>
        }
      </div>
    </div>);

}

// ---------- STANDARD CONTACT BLOCK (shared by service pages) ----------
const CONTACT_CHANNELS = [
  { kpt: "WhatsApp · Telefone", ken: "WhatsApp · Phone", v: "+55 47 99120-8818", href: "https://wa.me/5547991208818" },
  { kpt: "E-mail · Gestão & comercial", ken: "Email · Management & sales", v: "heros.silverio@silverioestaleiro.com.br", href: "mailto:heros.silverio@silverioestaleiro.com.br" },
  { kpt: "E-mail · Projetos & design", ken: "Email · Projects & design", v: "silvana.silverio@silverioestaleiro.com.br", href: "mailto:silvana.silverio@silverioestaleiro.com.br" },
];
const CONTACT_ASSUNTOS = {
  pt: ["Refit & Reformas", "Design & Engenharia", "Gestão & Consultoria B2B", "Construções", "Visita técnica", "Outro"],
  en: ["Refit & Refurbishment", "Design & Engineering", "B2B Management & Consulting", "New builds", "Technical visit", "Other"],
};
const CONTACT_CB = {
  pt: {
    eyebrow: "CONTATO · FALE COM A ENGENHARIA",
    directTitle: "Prefere falar direto?",
    directSub: "Atendemos por WhatsApp, e-mail ou telefone — ou receba uma visita técnica ao galpão em Tijucas.",
    pin: "Tijucas · SC",
    address: "Rua Eloi Francisco dos Anjos, 443 · Galpão 8 · CEP 88205-340",
    name: "Nome", company: "Empresa", companyOpt: "(opcional)",
    email: "E-mail", phone: "Telefone / WhatsApp", subject: "Assunto", message: "Mensagem",
    msgPlaceholder: "Conte sobre a embarcação, prazo e o que precisa.",
    submit: "Enviar mensagem",
    consent: "Ao enviar, você concorda em ser contatado pela nossa equipe sobre esta solicitação.",
    sentEyebrow: "OK · 200 — MENSAGEM ENVIADA",
    sentTitle: "Recebemos seu contato.",
    sentSub: "A engenharia retorna em até 24h úteis. Se for urgente, chame no WhatsApp.",
    openWa: "Abrir WhatsApp", again: "← Enviar outra mensagem",
  },
  en: {
    eyebrow: "CONTACT · TALK TO ENGINEERING",
    directTitle: "Prefer to talk directly?",
    directSub: "Reach us on WhatsApp, email or phone — or book a technical visit to our hangar in Tijucas.",
    pin: "Tijucas · SC",
    address: "Rua Eloi Francisco dos Anjos, 443 · Hangar 8 · CEP 88205-340",
    name: "Name", company: "Company", companyOpt: "(optional)",
    email: "Email", phone: "Phone / WhatsApp", subject: "Subject", message: "Message",
    msgPlaceholder: "Tell us about the vessel, timeline and what you need.",
    submit: "Send message",
    consent: "By submitting, you agree to be contacted by our team about this request.",
    sentEyebrow: "OK · 200 — MESSAGE SENT",
    sentTitle: "We received your message.",
    sentSub: "Engineering replies within 24 business hours. If it's urgent, reach us on WhatsApp.",
    openWa: "Open WhatsApp", again: "← Send another message",
  },
};

function ContactBlock({ subject = 0 }) {
  const { lang } = useI18n();
  const c = CONTACT_CB[lang] || CONTACT_CB.pt;
  const assuntos = CONTACT_ASSUNTOS[lang] || CONTACT_ASSUNTOS.pt;
  const [sent, setSent] = useState(false);
  const wa = CONTACT_CHANNELS[0].href;

  return (
    <section className="contact" id="contato">
      <div className="shell">
        <div className="eyebrow" style={{ marginBottom: 8 }}>{c.eyebrow}</div>

        {!sent ?
        <div className="contact-grid">
          <div>
            <h2 className="h-3" style={{ margin: '0 0 8px', maxWidth: '16ch' }}>{c.directTitle}</h2>
            <p className="body" style={{ margin: '0 0 28px', maxWidth: '40ch' }}>{c.directSub}</p>
            <div className="channels">
              {CONTACT_CHANNELS.map((ch, i) =>
              <a key={ch.v} className="channel" href={ch.href} target={ch.href.startsWith('http') ? '_blank' : undefined} rel={ch.href.startsWith('http') ? 'noopener noreferrer' : undefined}>
                  <span className="ix">{String(i + 1).padStart(2, '0')}</span>
                  <span className="body">
                    <span className="k">{lang === 'en' ? ch.ken : ch.kpt}</span>
                    <span className="v">{ch.v}</span>
                  </span>
                  <span className="arrow"></span>
                </a>
              )}
            </div>
            <div className="contact-map">
              <span className="pin">{c.pin}</span>
              <iframe
                src="https://www.google.com/maps?q=Rua+Eloi+Francisco+dos+Anjos+443+Galp%C3%A3o+8+Sul+do+Rio+Tijucas+SC+88205-340&z=15&output=embed"
                title="Silverio Estaleiro — Tijucas, SC" loading="lazy" referrerPolicy="no-referrer-when-downgrade"></iframe>
            </div>
            <div className="reassure"><span className="dot"></span>{c.address}</div>
          </div>

          <div>
            <form className="cform" onSubmit={(e) => {e.preventDefault();setSent(true);}}>
              <div className="grid">
                <div><label>{c.name}</label><input required /></div>
                <div><label>{c.company} <span style={{ textTransform: 'none', letterSpacing: 0 }}>{c.companyOpt}</span></label><input /></div>
                <div><label>{c.email}</label><input type="email" required /></div>
                <div><label>{c.phone}</label><input /></div>
                <div className="full">
                  <label>{c.subject}</label>
                  <select defaultValue={assuntos[subject]} key={assuntos[subject]}>
                    {assuntos.map((a) => <option key={a}>{a}</option>)}
                  </select>
                </div>
                <div className="full"><label>{c.message}</label><textarea rows="4" placeholder={c.msgPlaceholder}></textarea></div>
              </div>
              <div className="actions">
                <button type="submit" className="btn btn-primary">{c.submit}<span className="arrow"></span></button>
                <p className="consent">{c.consent}</p>
              </div>
            </form>
          </div>
        </div> :

        <div className="form-sent">
          <div className="eyebrow" style={{ marginBottom: 16, color: 'var(--green-deep)' }}>{c.sentEyebrow}</div>
          <h2 className="h-2" style={{ margin: '0 0 16px', maxWidth: '16ch' }}>{c.sentTitle}</h2>
          <p className="body-lg" style={{ margin: '0 0 32px', maxWidth: '46ch' }}>{c.sentSub}</p>
          <div style={{ display: 'flex', gap: 16, flexWrap: 'wrap' }}>
            <a className="btn btn-primary" href={wa} target="_blank" rel="noopener noreferrer">{c.openWa}<span className="arrow"></span></a>
            <button className="btn-link" onClick={() => setSent(false)}>{c.again}</button>
          </div>
        </div>
        }
      </div>
    </section>);

}

Object.assign(window, {
  I18nProvider, useI18n,
  Header, Footer, Placeholder, Media, SectionHead, ContactModal, VisitModal, ContactBlock, useScrollFade
});