// Contato — página de contato + kit de imprensa do ecossistema BlockUrb.
// Site estático: o formulário monta um mailto: (sem backend). Press kit lista
// os ativos de marca disponíveis no próprio domínio.
const CONTACT_EMAIL = "info@blockurb.ee";
const HEADER_OFFSET = 80;

// Estilo compartilhado dos campos — segue os tokens do design (sem CSS novo).
const fieldStyle = {
  width: "100%",
  padding: "14px 16px",
  background: "var(--bg-elev)",
  border: "1px solid var(--line)",
  borderRadius: 6,
  color: "var(--ink)",
  fontFamily: "var(--font-mono)",
  fontSize: 14,
  lineHeight: 1.5,
  outline: "none",
  boxSizing: "border-box",
};

function ContactForm() {
  const { tr } = useT();
  const [nome, setNome] = React.useState("");
  const [email, setEmail] = React.useState("");
  const [mensagem, setMensagem] = React.useState("");

  const onSubmit = (e) => {
    e.preventDefault();
    const subject = tr(`Contato pelo site — ${nome || "sem nome"}`, `Website contact — ${nome || "no name"}`);
    const body = tr(
      `Nome: ${nome}\nE-mail: ${email}\n\n${mensagem}`,
      `Name: ${nome}\nEmail: ${email}\n\n${mensagem}`
    );
    window.location.href =
      `mailto:${CONTACT_EMAIL}?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(body)}`;
  };

  const labelStyle = { display: "block", marginBottom: 8 };

  return (
    <section id="contato" style={{padding:"160px var(--gutter) 100px", borderBottom:"1px solid var(--line)", scrollMarginTop: 80}}>
      <div className="shell">
        <div style={{display:"flex", justifyContent:"space-between", marginBottom: 64}}>
          <Reveal as="span" className="coord">DOC. 006/CONTATO · REV 04.26</Reveal>
          <Reveal as="span" className="coord">TALLINN · 59.4370° N, 24.7536° E</Reveal>
        </div>
        <Reveal as="span" className="eyebrow" style={{display:"inline-flex", marginBottom: 40}}>{tr("FALE COM A BLOCKURB","TALK TO BLOCKURB","HABLA CON BLOCKURB")}</Reveal>
        <h1 className="display" style={{fontSize:"clamp(56px, 8vw, 116px)", margin:"0 0 40px", letterSpacing:"-0.03em"}}>
          <SplitReveal text={tr(["Vamos construir", {em:" a próxima cidade."}],["Let's build", {em:" the next city."}],["Construyamos", {em:" la próxima ciudad."}],["Ehitame", {em:" järgmise linna."}],["让我们建造", {em:" 下一座城市。"}])}/>
        </h1>

        <div style={{display:"grid", gridTemplateColumns:"1fr 1fr", gap: 64, alignItems:"start", marginTop: 24}}>
          <Reveal delay={200}>
            <p style={{maxWidth: 440, fontSize: 19, lineHeight: 1.55, color:"var(--ink-soft)", margin:"0 0 32px"}}>
              {tr(
                "Investidores, municípios, parceiros e imprensa: envie sua mensagem e nossa equipe responde diretamente.",
                "Investors, municipalities, partners and press: send your message and our team replies directly.",
                "Inversores, municipios, socios y prensa: envíe su mensaje y nuestro equipo responde directamente."
              )}
            </p>
            <div className="mono" style={{lineHeight: 1.9, color:"var(--ink-soft)"}}>
              <div>{tr("E-MAIL","EMAIL","CORREO")}</div>
              <a href={`mailto:${CONTACT_EMAIL}`} style={{color:"var(--accent-ink)"}}>{CONTACT_EMAIL}</a>
              <div style={{marginTop: 16}}>{tr("ENDEREÇO","ADDRESS","DIRECCIÓN")}</div>
              <div>BlockUrb OÜ · Ahtri tn 12 · 15551 Tallinn · {tr("Estônia","Estonia","Estonia")}</div>
            </div>
          </Reveal>

          <Reveal delay={300}>
            <form onSubmit={onSubmit} style={{display:"flex", flexDirection:"column", gap: 20, maxWidth: 520}}>
              <div>
                <label className="mono" htmlFor="cf-nome" style={labelStyle}>{tr("NOME","NAME","NOMBRE")}</label>
                <input id="cf-nome" type="text" required value={nome} onChange={(e)=>setNome(e.target.value)} style={fieldStyle} placeholder={tr("Seu nome","Your name","Tu nombre")} />
              </div>
              <div>
                <label className="mono" htmlFor="cf-email" style={labelStyle}>{tr("E-MAIL","EMAIL","CORREO")}</label>
                <input id="cf-email" type="email" required value={email} onChange={(e)=>setEmail(e.target.value)} style={fieldStyle} placeholder="voce@empresa.com" />
              </div>
              <div>
                <label className="mono" htmlFor="cf-msg" style={labelStyle}>{tr("MENSAGEM","MESSAGE","MENSAJE")}</label>
                <textarea id="cf-msg" required rows={6} value={mensagem} onChange={(e)=>setMensagem(e.target.value)} style={{...fieldStyle, resize:"vertical"}} placeholder={tr("Como podemos ajudar?","How can we help?","¿Cómo podemos ayudar?")} />
              </div>
              <button type="submit" className="btn btn--ink" style={{alignSelf:"flex-start"}}>
                {tr("Enviar mensagem","Send message","Enviar mensaje")} <span className="arrow">→</span>
              </button>
            </form>
          </Reveal>
        </div>
      </div>
    </section>
  );
}

function PressKitSection() {
  const { tr } = useT();
  const assets = [
    { label: tr("Logo · símbolo (PNG)","Logo · symbol (PNG)","Logo · símbolo (PNG)"), file: "logo-coin.png" },
    { label: tr("Logo · marca completa (PNG)","Logo · full wordmark (PNG)","Logo · marca completa (PNG)"), file: "logo-frame-1.png" },
    { label: tr("Ícone do app (512px)","App icon (512px)","Ícono de app (512px)"), file: "android-chrome-512x512.png" },
  ];
  return (
    <section id="imprensa" className="section section--dark" style={{borderTop:"1px solid var(--line)", scrollMarginTop: 80}}>
      <div className="shell">
        <div style={{display:"grid", gridTemplateColumns:"180px 1fr", gap: 48, marginBottom: 56}}>
          <Reveal as="div" className="mono" style={{paddingTop: 8, color:"color-mix(in srgb, #F4F1EA 60%, transparent)"}}>
            PRESS · KIT<br/><span style={{opacity:0.6}}>{tr("IMPRENSA","PRESS","PRENSA")}</span>
          </Reveal>
          <div>
            <h2 className="display" style={{fontSize:"clamp(40px, 5vw, 72px)", margin:"0 0 24px", color:"#F4F1EA"}}>
              <SplitReveal text={[tr("Kit de imprensa","Press kit","Kit de prensa")]}/>
            </h2>
            <Reveal delay={150}>
              <p style={{fontSize: 19, lineHeight: 1.5, fontFamily:"var(--font-display)", color:"#F4F1EA", maxWidth: 720, margin: 0}}>
                {tr(
                  "Ativos de marca, logotipos e contato de imprensa da BlockUrb OÜ. Para entrevistas, dados e materiais adicionais, fale com nossa equipe.",
                  "BlockUrb OÜ brand assets, logos and press contact. For interviews, data and additional materials, reach our team.",
                  "Activos de marca, logotipos y contacto de prensa de BlockUrb OÜ. Para entrevistas, datos y materiales adicionales, contáctenos."
                )}
              </p>
            </Reveal>
          </div>
        </div>

        <div style={{display:"grid", gridTemplateColumns:"180px 1fr 1fr", gap: 48, alignItems:"start"}}>
          <div></div>
          <Reveal>
            <div className="mono" style={{marginBottom: 16, color:"color-mix(in srgb, #F4F1EA 60%, transparent)"}}>{tr("DOWNLOADS","DOWNLOADS","DESCARGAS")}</div>
            <ul style={{listStyle:"none", padding:0, margin:0}}>
              {assets.map((a, i) => (
                <li key={i} style={{padding:"14px 0", borderTop:"1px solid #28322C", display:"grid", gridTemplateColumns:"24px 1fr auto", gap: 12, fontSize: 14, lineHeight: 1.55, color:"color-mix(in srgb, #F4F1EA 85%, transparent)"}}>
                  <span className="mono" style={{opacity: 0.6}}>{String(i+1).padStart(2,"0")}</span>
                  <span>{a.label}</span>
                  <a href={a.file} download style={{color:"oklch(0.78 0.08 145)"}}>{tr("baixar ↓","download ↓","descargar ↓")}</a>
                </li>
              ))}
            </ul>
          </Reveal>
          <Reveal delay={150}>
            <div className="mono" style={{marginBottom: 16, color:"color-mix(in srgb, #F4F1EA 60%, transparent)"}}>{tr("CONTATO DE IMPRENSA","PRESS CONTACT","CONTACTO DE PRENSA")}</div>
            <div style={{fontSize: 15, lineHeight: 1.8, color:"color-mix(in srgb, #F4F1EA 85%, transparent)"}}>
              <a href={`mailto:${CONTACT_EMAIL}?subject=${encodeURIComponent(tr("Imprensa — BlockUrb","Press — BlockUrb"))}`} style={{color:"oklch(0.78 0.08 145)"}}>{CONTACT_EMAIL}</a><br/>
              BlockUrb OÜ · Reg. 16487991<br/>
              Ahtri tn 12 · 15551 Tallinn · {tr("Estônia","Estonia","Estonia")}
            </div>
          </Reveal>
        </div>
      </div>
    </section>
  );
}

function ContatoPage() {
  // Mesmo problema de âncora das outras páginas: o conteúdo é montado pelo React
  // depois do browser processar o #hash (#imprensa). Rola após a montagem.
  React.useEffect(() => {
    let raf1, raf2, timer;
    const scrollToHash = () => {
      const hash = window.location.hash;
      if (!hash || hash.length < 2) return;
      const id = decodeURIComponent(hash.slice(1));
      const tryScroll = (attemptsLeft) => {
        const el = document.getElementById(id);
        if (el) {
          const y = el.getBoundingClientRect().top + window.pageYOffset - HEADER_OFFSET;
          window.scrollTo({ top: y, behavior: "smooth" });
        } else if (attemptsLeft > 0) {
          timer = setTimeout(() => tryScroll(attemptsLeft - 1), 60);
        }
      };
      raf1 = requestAnimationFrame(() => { raf2 = requestAnimationFrame(() => tryScroll(20)); });
    };
    scrollToHash();
    window.addEventListener("hashchange", scrollToHash);
    return () => {
      window.removeEventListener("hashchange", scrollToHash);
      cancelAnimationFrame(raf1); cancelAnimationFrame(raf2); clearTimeout(timer);
    };
  }, []);

  return (
    <Page>
      <TopNav active="" />
      <main>
        <ContactForm />
        <PressKitSection />
      </main>
      <Footer />
    </Page>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<ContatoPage />);
