/* ============================================================
   TRAW — Process, About, Projects, CTA (com formulário), Footer
   ============================================================ */
const { useState: useStateCTA, useRef: useRefProj, useEffect: useEffectProj } = React;

/* ---------------- PROCESS ---------------- */
const STEPS = [
  { n: "01", t: "Briefing & Estratégia", d: "Entendemos seu negócio, público e objetivos para traçar a melhor direção." },
  { n: "02", t: "Design & Protótipo", d: "Criamos o layout sob medida e validamos cada tela antes de programar." },
  { n: "03", t: "Desenvolvimento", d: "Codificamos um site rápido, responsivo e otimizado para buscadores." },
  { n: "04", t: "Lançamento & Suporte", d: "Publicamos, acompanhamos os resultados e evoluímos o site com você." },
];

function Process() {
  const ref = useReveal();
  return (
    <section className="section process" id="processo" ref={ref}>
      <div className="wrap">
        <div className="sec-head center" data-reveal>
          <span className="eyebrow center">Como trabalhamos</span>
          <h2 className="sec-title">Um processo claro,<br />do briefing ao resultado</h2>
          <p className="sec-sub">Método objetivo e transparente em cada etapa — você sabe exatamente o que esperar e quando.</p>
        </div>
        <div className="proc-grid">
          <div className="proc-line" aria-hidden="true"></div>
          {STEPS.map((s, i) => (
            <div className="proc-step" key={s.n} data-reveal data-delay={i * 100}>
              <div className="proc-num">{s.n}</div>
              <h3>{s.t}</h3>
              <p>{s.d}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------------- ABOUT ---------------- */
const ABOUT_LIST = [
  "Websites responsivos e otimizados para SEO",
  "Aplicações web modernas com React e Next.js",
  "Consultoria em UX/UI e otimização de conversão",
  "Automação de processos e integrações",
];
const ABOUT_CARDS = [
  { ic: "users", t: "Atendimento personalizado", d: "Estratégias feitas sob medida para o momento e os objetivos do seu negócio." },
  { ic: "target", t: "Know-how especializado", d: "Experiência prática em soluções digitais que realmente entregam resultado." },
  { ic: "shield", t: "Confiança comprovada", d: "Casos de sucesso em diferentes setores, do institucional ao e-commerce." },
];

function About() {
  const ref = useReveal();
  return (
    <section className="section about" id="sobre" ref={ref}>
      <div className="wrap about-grid">
        <div className="about-copy">
          <span className="eyebrow" data-reveal>Quem somos</span>
          <h2 className="sec-title" data-reveal data-delay="60">A agência que<br />transforma negócios</h2>
          <p data-reveal data-delay="120">
            Somos a <strong>Traw</strong>, especializada em transformar a presença online de
            empresas em uma máquina de vendas eficiente e escalável. Unimos criatividade e
            tecnologia para criar sites que conectam sua marca às pessoas certas.
          </p>
          <p data-reveal data-delay="160">
            Ter um site hoje não é luxo: é a base para que sua empresa seja
            encontrada, lembrada e escolhida.
          </p>
          <ul className="about-list">
            {ABOUT_LIST.map((s, i) => (
              <li key={s} data-reveal data-delay={200 + i * 60}>
                <span className="ck"><Icon name="check" size={15} /></span>{s}
              </li>
            ))}
          </ul>
        </div>
        <div className="about-cards">
          {ABOUT_CARDS.map((c, i) => (
            <div className="about-c" key={c.t} data-reveal data-delay={i * 110}>
              <div className="top">
                <div className="ic"><Icon name={c.ic} size={22} /></div>
                <h4>{c.t}</h4>
              </div>
              <p>{c.d}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------------- PROJECTS ---------------- */
const PROJECTS = [
  { img: "assets/merielli.jpeg", tag: "Institucional", t: "Merielli Arquitetura", d: "Site institucional elegante para apresentar projetos e portfólio com sofisticação.", url: "https://merielliarquitetura.com.br/" },
  { img: "assets/synorit.png",   tag: "Tecnologia",   t: "SynorIT",             d: "Presença digital robusta para uma empresa de soluções e serviços de TI.",          url: "https://www.synorit.com.br/" },
  { img: "assets/traw-erp.png",  tag: "Software",     t: "Traw ERP",            d: "Site do nosso sistema de gestão empresarial, focado em clareza e conversão.",       url: "https://www.traw.com.br" },
];

function Projects() {
  const ref = useReveal();
  const gridRef = useRefProj(null);
  const [activeIdx, setActiveIdx] = useStateCTA(0);
  const drag = useRefProj({ active: false, startX: 0, scrollLeft: 0 });
  const timerRef = useRefProj(null);
  const pausedRef = useRefProj(false);

  const scrollTo = (i) => {
    const el = gridRef.current;
    if (!el) return;
    el.scrollTo({ left: el.offsetWidth * i, behavior: "smooth" });
  };

  const startAutoplay = () => {
    clearInterval(timerRef.current);
    timerRef.current = setInterval(() => {
      if (pausedRef.current) return;
      const el = gridRef.current;
      if (!el) return;
      const next = (Math.round(el.scrollLeft / el.offsetWidth) + 1) % PROJECTS.length;
      scrollTo(next);
    }, 3000);
  };

  useEffectProj(() => {
    const el = gridRef.current;
    if (!el) return;

    const onScroll = () => {
      const idx = Math.round(el.scrollLeft / el.offsetWidth);
      setActiveIdx(Math.min(idx, PROJECTS.length - 1));
    };
    el.addEventListener("scroll", onScroll, { passive: true });

    /* só ativa autoplay em mobile */
    const mq = window.matchMedia("(max-width: 760px)");
    if (mq.matches) startAutoplay();
    const onMqChange = (e) => { e.matches ? startAutoplay() : clearInterval(timerRef.current); };
    mq.addEventListener("change", onMqChange);

    return () => {
      el.removeEventListener("scroll", onScroll);
      mq.removeEventListener("change", onMqChange);
      clearInterval(timerRef.current);
    };
  }, []);

  const pauseAutoplay = () => { pausedRef.current = true; };
  const resumeAutoplay = () => { pausedRef.current = false; };

  const onMouseDown = (e) => {
    pauseAutoplay();
    const el = gridRef.current;
    drag.current = { active: true, startX: e.pageX - el.offsetLeft, scrollLeft: el.scrollLeft };
    el.style.cursor = "grabbing";
    el.style.userSelect = "none";
  };
  const onMouseMove = (e) => {
    if (!drag.current.active) return;
    e.preventDefault();
    const el = gridRef.current;
    const x = e.pageX - el.offsetLeft;
    el.scrollLeft = drag.current.scrollLeft - (x - drag.current.startX) * 1.2;
  };
  const onMouseUp = () => {
    drag.current.active = false;
    const el = gridRef.current;
    el.style.cursor = "";
    el.style.userSelect = "";
    resumeAutoplay();
  };

  return (
    <section className="section projects" id="projetos" ref={ref}>
      <div className="wrap">
        <div className="sec-head center" data-reveal>
          <span className="eyebrow center">Nossos projetos</span>
          <h2 className="sec-title">Projetos que viraram<br />presença de verdade</h2>
          <p className="sec-sub">Uma seleção de sites que desenvolvemos para marcas de diferentes segmentos.</p>
        </div>
        <div
          className="proj-grid"
          ref={gridRef}
          onMouseDown={onMouseDown}
          onMouseMove={onMouseMove}
          onMouseUp={onMouseUp}
          onMouseLeave={onMouseUp}
          onTouchStart={pauseAutoplay}
          onTouchEnd={resumeAutoplay}
        >
          {PROJECTS.map((p, i) => (
            <a className="proj-card" key={p.t} href={p.url} target="_blank" rel="noopener noreferrer" data-reveal data-delay={(i % 3) * 90}>
              <div className="proj-shot">
                <span className="proj-tag">{p.tag}</span>
                <img src={p.img} alt={"Site " + p.t + " desenvolvido pela Traw"} loading="lazy" />
              </div>
              <div className="proj-body">
                <h3>{p.t}</h3>
                <p>{p.d}</p>
                <span className="proj-link">Ver site <Icon name="arrowUR" size={16} /></span>
              </div>
            </a>
          ))}
        </div>
        <div className="proj-dots">
          {PROJECTS.map((_, i) => (
            <button
              key={i}
              className={"proj-dot" + (i === activeIdx ? " active" : "")}
              onClick={() => scrollTo(i)}
              aria-label={"Ver projeto " + (i + 1)}
            />
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------------- FORMULÁRIO DE CONTATO ---------------- */
const SERVICES_LIST = [
  "Desenvolvimento Web",
  "Design & UX/UI",
  "Landing Page",
  "SEO & Performance",
  "E-commerce",
  "Manutenção & Suporte",
];

const API_URL = "";

function ContactForm() {
  const [form, setForm] = useStateCTA({
    nome: "", email: "", telefone: "", servico: "", mensagem: "",
  });
  const [status, setStatus]  = useStateCTA("idle"); // idle | loading | success | error
  const [errMsg, setErrMsg]  = useStateCTA("");

  const set = (key) => (e) => setForm((f) => ({ ...f, [key]: e.target.value }));

  const handleSubmit = async (e) => {
    e.preventDefault();
    setStatus("loading");
    setErrMsg("");
    try {
      const res  = await fetch(API_URL + "/api/contact", {
        method:  "POST",
        headers: { "Content-Type": "application/json" },
        body:    JSON.stringify(form),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Erro ao enviar. Tente novamente.");
      setStatus("success");
      setForm({ nome: "", email: "", telefone: "", servico: "", mensagem: "" });
    } catch (err) {
      setStatus("error");
      setErrMsg(err.message);
    }
  };

  if (status === "success") {
    return (
      <div className="cf-success">
        <div className="cf-success-ic"><Icon name="check" size={28} /></div>
        <h3>Mensagem enviada!</h3>
        <p>Em breve entraremos em contato. Você também pode falar com a gente pelo WhatsApp.</p>
        <button className="btn btn-ghost" onClick={() => setStatus("idle")}>Enviar outra mensagem</button>
      </div>
    );
  }

  return (
    <form className="contact-form" onSubmit={handleSubmit} noValidate>
      <div className="cf-row">
        <div className="cf-field">
          <label htmlFor="cf-nome">Nome *</label>
          <input
            id="cf-nome" type="text" autoComplete="name"
            value={form.nome} onChange={set("nome")}
            placeholder="Seu nome completo" required
          />
        </div>
        <div className="cf-field">
          <label htmlFor="cf-email">E-mail *</label>
          <input
            id="cf-email" type="email" autoComplete="email"
            value={form.email} onChange={set("email")}
            placeholder="seu@email.com" required
          />
        </div>
      </div>
      <div className="cf-row">
        <div className="cf-field">
          <label htmlFor="cf-tel">Telefone</label>
          <input
            id="cf-tel" type="tel" autoComplete="tel"
            value={form.telefone} onChange={set("telefone")}
            placeholder="(00) 00000-0000"
          />
        </div>
        <div className="cf-field">
          <label htmlFor="cf-svc">Serviço de interesse</label>
          <select id="cf-svc" value={form.servico} onChange={set("servico")}>
            <option value="">Selecione...</option>
            {SERVICES_LIST.map((s) => <option key={s} value={s}>{s}</option>)}
          </select>
        </div>
      </div>
      <div className="cf-field">
        <label htmlFor="cf-msg">Mensagem *</label>
        <textarea
          id="cf-msg" rows={4}
          value={form.mensagem} onChange={set("mensagem")}
          placeholder="Conte um pouco sobre seu projeto..."
          required
        ></textarea>
      </div>

      {status === "error" && (
        <p className="cf-error">
          <Icon name="shield" size={15} /> {errMsg}
        </p>
      )}

      <button
        className="btn btn-primary cf-submit"
        type="submit"
        disabled={status === "loading"}
      >
        {status === "loading"
          ? "Enviando..."
          : <React.Fragment><Icon name="chat" size={18} /> Enviar mensagem</React.Fragment>
        }
      </button>
    </form>
  );
}

/* ---------------- CTA FINAL / CONTATO ---------------- */
function CTA() {
  const ref = useReveal();
  return (
    <section className="section cta" id="contato" ref={ref}>
      <div className="wrap">
        <div className="cta-band" data-reveal>
          <div className="glow g1" aria-hidden="true"></div>
          <div className="glow g2" aria-hidden="true"></div>
          <div className="cta-grid">

            <div className="cta-info">
              <span className="eyebrow">Vamos começar</span>
              <h2>Pronto para ter um site<br />à altura da sua marca?</h2>
              <p>Preencha o formulário ao lado ou fale diretamente pelo WhatsApp. Respondemos rápido com um orçamento sem compromisso.</p>
              <div className="cta-contact">
                <a href={waLink()} target="_blank" rel="noopener noreferrer">
                  <span className="ic"><Icon name="phone" size={17} /></span> (18) 99747-2540
                </a>
                <a href="mailto:contato@traw.com.br">
                  <span className="ic"><Icon name="mail" size={17} /></span> contato@traw.com.br
                </a>
              </div>
              <div className="cta-wa">
                <a className="btn btn-on-dark" href={waLink("Olá! Quero solicitar um orçamento de site com a Traw.")} target="_blank" rel="noopener noreferrer">
                  <Icon name="chat" size={18} /> Falar pelo WhatsApp
                </a>
              </div>
            </div>

            <div className="cta-form-wrap">
              <ContactForm />
            </div>

          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------------- FOOTER ---------------- */
function Footer() {
  const go = (e, id) => { e.preventDefault(); const el = document.getElementById(id); if (el) el.scrollIntoView({ behavior: "smooth" }); };
  return (
    <footer className="footer">
      <div className="wrap">
        <div className="footer-top">
          <div className="footer-brand">
            <img src="assets/logotipotraw.png" alt="Traw" />
            <p>Agência de marketing digital especializada em desenvolvimento de sites que geram autoridade e resultado.</p>
          </div>
          <div className="footer-cols">
            <div className="footer-col">
              <h5>Navegação</h5>
              <a href="#servicos" onClick={(e) => go(e, "servicos")}>Serviços</a>
              <a href="#processo" onClick={(e) => go(e, "processo")}>Processo</a>
              <a href="#sobre"    onClick={(e) => go(e, "sobre")}>Quem Somos</a>
              <a href="#projetos" onClick={(e) => go(e, "projetos")}>Projetos</a>
            </div>
            <div className="footer-col">
              <h5>Serviços</h5>
              <a href="#servicos" onClick={(e) => go(e, "servicos")}>Desenvolvimento Web</a>
              <a href="#servicos" onClick={(e) => go(e, "servicos")}>Design UX/UI</a>
              <a href="#servicos" onClick={(e) => go(e, "servicos")}>Landing Pages</a>
              <a href="#servicos" onClick={(e) => go(e, "servicos")}>SEO &amp; Performance</a>
            </div>
            <div className="footer-col">
              <h5>Contato</h5>
              <a href={waLink()} target="_blank" rel="noopener noreferrer">(18) 99747-2540</a>
              <a href="mailto:contato@traw.com.br">contato@traw.com.br</a>
              <a href={waLink()} target="_blank" rel="noopener noreferrer">WhatsApp</a>
            </div>
          </div>
        </div>
        <div className="footer-bottom">
          <span>© {new Date().getFullYear()} Traw — Agência de Marketing Digital. Todos os direitos reservados.</span>
          <div className="socials">
            <a href={waLink()} target="_blank" rel="noopener noreferrer" aria-label="WhatsApp"><Icon name="chat" size={18} /></a>
            <a href="https://www.instagram.com" target="_blank" rel="noopener noreferrer" aria-label="Instagram"><Icon name="insta" size={18} /></a>
            <a href="mailto:contato@traw.com.br" aria-label="E-mail"><Icon name="mail" size={18} /></a>
          </div>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { Process, About, Projects, CTA, Footer });
