/* global React */
const { useState: useState_b, useEffect: useEffect_b, useRef: useRef_b } = React;

/* ============================================================
   Social Proof + Testimonial carousel (Section 8)
   ============================================================ */
const Proof = ({ t }) => {
  const p = t.proof;
  const [idx, setIdx] = useState_b(0);
  const timer = useRef_b(null);
  const total = p.slides.length;

  useEffect_b(() => {
    timer.current = setInterval(() => setIdx(i => (i+1) % total), 7000);
    return () => clearInterval(timer.current);
  }, [total]);

  const go = (n) => {
    clearInterval(timer.current);
    setIdx((n + total) % total);
    timer.current = setInterval(() => setIdx(i => (i+1) % total), 7000);
  };
  const s = p.slides[idx];

  const clients = [
    { src: "assets/client-start55.avif",   name: "Start55",   preserve: true },
    { src: "assets/client-siebert.png",    name: "Siebert",   preserve: true },
    { src: "assets/client-habiitech.png",  name: "Habii.tech",preserve: true },
    { src: "assets/client-kabukenas.avif", name: "Rádio Kabukenas", preserve: true },
  ];

  return (
    <section className="section" id="clientes">
      <div className="wrap">
        <Reveal className="section-head">
          <div className="proof-head-meta">
            <strong>{p.meta.retainers}</strong>
            <span>{p.meta.retainersLabel}</span>
            <span className="bullet"></span>
            <span>{p.meta.projects}</span>
          </div>
          <span className="eyebrow">{p.eyebrow}</span>
          <h2>{p.h2}</h2>
          <p style={{ color: "var(--ink-muted)", fontSize: 14, fontStyle: "italic" }}>{p.sub}</p>
        </Reveal>

        <Reveal>
          <div className="testimonial-shell">
            <div className="testimonial-slide" key={idx} style={{ animation: "fadeUp .55s var(--ease) both" }}>
              <div className="testimonial-body">
                <div className="testimonial-tag">{s.tag}</div>
                <div className="testimonial-quote">{s.quote}</div>
                <div className="testimonial-author">
                  <span className="author-name">{s.name}</span>
                  <span className="author-role">{s.role}</span>
                </div>
              </div>
              <div className="testimonial-aside">
                <div className="testimonial-result">{p.meta.projects.split(" · ")[0]} ↗</div>
                <div className="testimonial-result-num">{s.resultNum}</div>
                <div className="testimonial-result-sub">
                  <div style={{ fontFamily:"var(--f-mono)", fontSize: 11, textTransform: "uppercase", letterSpacing: ".12em", color: "var(--ink-muted)", marginBottom: 6 }}>{s.resultLabel}</div>
                  {s.resultSub}
                </div>
              </div>
            </div>

            <div className="testimonial-controls">
              <div className="testimonial-dots">
                {p.slides.map((_, i) => (
                  <button key={i} className={`testimonial-dot ${i === idx ? "active" : ""}`} onClick={() => go(i)} aria-label={`Slide ${i+1}`}></button>
                ))}
              </div>
              <div className="testimonial-nav">
                <button onClick={() => go(idx - 1)} aria-label="Previous">
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M15 18l-6-6 6-6"/></svg>
                </button>
                <button onClick={() => go(idx + 1)} aria-label="Next">
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M9 6l6 6-6 6"/></svg>
                </button>
              </div>
            </div>
          </div>

          <div style={{ marginTop: 48, fontFamily: "var(--f-mono)", fontSize: 11, textTransform: "uppercase", letterSpacing: ".14em", color: "var(--ink-muted)" }}>
            {p.clientsLabel}
          </div>
          <div className="client-logos">
            {clients.map((c, i) => (
              <div className={`client-logo ${c.preserve ? "preserve" : ""}`} key={i}>
                <img src={c.src} alt={c.name} />
              </div>
            ))}
          </div>
        </Reveal>
      </div>
    </section>
  );
};

/* ============================================================
   Offer (Section 9)
   ============================================================ */
const Offer = ({ t, openModal }) => {
  const o = t.offer;
  return (
    <section className="section" id="oferta">
      <div className="wrap">
        <Reveal className="section-head">
          <span className="eyebrow">{o.eyebrow}</span>
        </Reveal>
        <Reveal>
          <div className="offer-card">
            <div className="offer-left">
              <h3>{o.h2}</h3>
              <p className="offer-lede">{o.lede}</p>
              <ul className="offer-features">
                {o.features.map((f, i) => (
                  <li key={i}>
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4">
                      <path d="M5 12l5 5L20 7"/>
                    </svg>
                    <span>{f}</span>
                  </li>
                ))}
              </ul>
            </div>
            <div className="offer-right">
              <div>
                <div className="offer-price-label">{o.priceLabel}</div>
                <div className="offer-price">{o.price}</div>
                <div className="offer-price-sub">{o.priceSub}</div>
                <div className="offer-meta">
                  {o.meta.map((m, i) => (
                    <div className="offer-meta-item" key={i}>
                      {m.l}
                      <strong>{m.v}</strong>
                    </div>
                  ))}
                </div>
              </div>
              <div>
                <button className="btn btn-primary btn-arrow" style={{ width:"100%", justifyContent:"center" }} onClick={openModal}>
                  {o.cta}
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M5 12h14M13 5l7 7-7 7"/></svg>
                </button>
                <div className="offer-extra">{o.extra}</div>
              </div>
            </div>
          </div>
        </Reveal>
      </div>
    </section>
  );
};

/* ============================================================
   Objections (Section 10) - accordion
   ============================================================ */
const Objections = ({ t }) => {
  const o = t.objections;
  const [open, setOpen] = useState_b(0);
  return (
    <section className="section">
      <div className="wrap">
        <Reveal className="section-head">
          <span className="eyebrow">{o.eyebrow}</span>
          <h2>{o.h2}</h2>
        </Reveal>
        <div className="obj-list">
          {o.items.map((it, i) => (
            <div key={i} className={`obj-item ${open === i ? "open" : ""}`}>
              <button className="obj-head" onClick={() => setOpen(open === i ? -1 : i)}>
                <span className="obj-quote-mark">{it.tag}</span>
                <span style={{ flex: 1 }}>{it.q}</span>
                <span className="obj-chev">
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M6 9l6 6 6-6"/></svg>
                </span>
              </button>
              <div className="obj-body">
                <div className="obj-body-inner">{it.a}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};

/* ============================================================
   Guarantee (Section 11)
   ============================================================ */
const Guarantee = ({ t }) => {
  const g = t.guarantee;
  return (
    <section className="section">
      <div className="wrap">
        <Reveal>
          <div className="guarantee">
            <div className="shield">
              <div className="shield-ring"></div>
              <div className="shield-core">
                <span className="shield-num">14</span>
                <span className="shield-unit">{g.unit}</span>
              </div>
            </div>
            <div className="guarantee-body">
              <span className="eyebrow" style={{ marginBottom: 16, display: "inline-flex" }}>{g.eyebrow}</span>
              <h3 style={{ marginTop: 12 }}>{g.title}</h3>
              <p>{g.body}</p>
            </div>
          </div>
        </Reveal>
      </div>
    </section>
  );
};

/* ============================================================
   Urgency (Section 12)
   ============================================================ */
const Urgency = ({ t }) => {
  const u = t.urgency;
  return (
    <section className="section">
      <div className="wrap">
        <Reveal className="section-head">
          <span className="eyebrow">{u.eyebrow}</span>
          <h2>{u.h2}</h2>
        </Reveal>
        <div className="urgency">
          {u.cards.map((c, i) => (
            <Reveal as="div" className="urgency-card" key={i} delay={i*80}>
              <div className="u-tag">{c.tag}</div>
              <h3>{c.h}</h3>
              <p>{c.p}</p>
              <div className="urgency-meter">
                {Array.from({ length: c.total }).map((_, j) => (
                  <span key={j} className={j < c.filled ? "filled" : ""}></span>
                ))}
              </div>
              <div style={{ marginTop: 12, fontFamily: "var(--f-mono)", fontSize: 11, color: "var(--ink-muted)", letterSpacing: ".12em", textTransform: "uppercase" }}>
                {c.filled} / {c.total}
              </div>
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
};

/* ============================================================
   FAQ (Section 13)
   ============================================================ */
const FAQ = ({ t, openModal }) => {
  const f = t.faq;
  const [open, setOpen] = useState_b(0);
  return (
    <section className="section" id="faq">
      <div className="wrap faq-layout">
        <div className="faq-aside">
          <span className="eyebrow">{f.eyebrow}</span>
          <h2>{f.h2}</h2>
          <p>{f.sub}</p>
          <button className="btn btn-ghost btn-arrow" onClick={openModal}>
            {t.nav.cta}
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M5 12h14M13 5l7 7-7 7"/></svg>
          </button>
        </div>
        <div className="faq-list">
          {f.items.map((it, i) => (
            <div className={`faq-item ${open === i ? "open" : ""}`} key={i}>
              <button className="faq-q" onClick={() => setOpen(open === i ? -1 : i)}>
                <span>{it.q}</span>
                <span className="plus"></span>
              </button>
              <div className="faq-a">
                <div className="faq-a-inner">{it.a}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};

/* ============================================================
   Final CTA (Section 14)
   ============================================================ */
const FinalCTA = ({ t, openModal }) => {
  const f = t.finalCta;
  return (
    <section className="final-cta">
      <div className="final-cta-bg"></div>
      <div className="wrap final-cta-inner">
        <Reveal>
          <span className="eyebrow" style={{ marginBottom: 20, display: "inline-flex" }}>{f.eyebrow}</span>
          <h2 style={{ marginTop: 12 }}>{f.h2}</h2>
          <p className="final-cta-lede">{f.lede}</p>
          <button className="btn btn-primary btn-arrow" onClick={openModal} style={{ fontSize: 17, padding: "20px 28px" }}>
            {f.cta}
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M5 12h14M13 5l7 7-7 7"/></svg>
          </button>
          <div className="final-cta-meta">
            {f.meta.map((m, i) => (
              <React.Fragment key={i}>
                {i > 0 && <span className="dot"></span>}
                <span>{m}</span>
              </React.Fragment>
            ))}
          </div>
        </Reveal>
      </div>
    </section>
  );
};

/* ============================================================
   PS (Section 15)
   ============================================================ */
const PS = ({ t, openModal }) => {
  const p = t.ps;
  return (
    <section style={{ padding: "0 0 80px" }}>
      <div className="wrap">
        <Reveal>
          <div className="ps-block">
            <div className="ps-label">{p.label}</div>
            <div className="ps-body">
              {p.body}{" "}
              <a href="#" onClick={(e) => { e.preventDefault(); openModal(); }}>{p.link}</a>
            </div>
          </div>
        </Reveal>
      </div>
    </section>
  );
};

/* ============================================================
   Footer
   ============================================================ */
const Footer = ({ t }) => {
  const f = t.footer;
  return (
    <footer className="footer">
      <div className="wrap">
        <div className="footer-grid">
          <div className="footer-brand">
            <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
              <img src="assets/logo-dx-color.png" alt="Dowsnux" className="footer-logo" />
              <span style={{ fontFamily: "var(--f-display)", fontWeight: 600, fontSize: 22, letterSpacing: "-0.01em" }}>DOWSNUX</span>
            </div>
            <p>{f.desc}</p>
            <div className="brand-tag" style={{ paddingLeft: 0, borderLeft: 0, marginLeft: 0 }}>{f.tag}</div>
          </div>
          {f.cols.map((c, i) => (
            <div className="footer-col" key={i}>
              <h4>{c.h}</h4>
              <ul>
                {c.links.map((l, j) => <li key={j}><a href="#">{l}</a></li>)}
              </ul>
            </div>
          ))}
        </div>
        <div className="footer-bottom">
          <span>{f.copy}</span>
          <div style={{ display: "flex", gap: 24 }}>
            {f.legal.map((l, i) => <a key={i} href="#" style={{ color: "var(--ink-soft)", textDecoration: "none" }}>{l}</a>)}
          </div>
        </div>
      </div>
    </footer>
  );
};

/* ============================================================
   Contact Modal
   ============================================================ */
const ContactModal = ({ t, open, close, lang }) => {
  const m = t.modal;
  const [form, setForm] = useState_b({ name: "", email: "", company: "", scope: "", message: "", hp: "" });
  const [errors, setErrors] = useState_b({});
  const [sent, setSent] = useState_b(false);
  const [submitting, setSubmitting] = useState_b(false);
  const [submitError, setSubmitError] = useState_b(null);

  useEffect_b(() => {
    if (!open) {
      setTimeout(() => {
        setSent(false);
        setSubmitting(false);
        setSubmitError(null);
        setForm({ name:"", email:"", company:"", scope:"", message:"", hp:"" });
        setErrors({});
      }, 350);
    }
    const onKey = (e) => { if (e.key === "Escape" && open) close(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open]);

  const setField = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const submit = async (e) => {
    e.preventDefault();
    const errs = {};
    if (!form.name.trim()) errs.name = m.errors.required;
    if (!form.email.trim()) errs.email = m.errors.required;
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) errs.email = m.errors.email;
    if (!form.scope) errs.scope = m.errors.required;
    setErrors(errs);
    if (Object.keys(errs).length > 0) return;

    setSubmitting(true);
    setSubmitError(null);
    try {
      const res = await fetch("/api/contact", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          ...form,
          lang,
          source: "lp-dowsnux",
        }),
      });
      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        throw new Error(data.error || `status_${res.status}`);
      }
      setSent(true);
      if (window.dataLayer) window.dataLayer.push({ event: "lead_submitted", source: "lp-dowsnux" });
    } catch (err) {
      console.error("Submit failed", err);
      setSubmitError(m.errors.network || (lang === "en"
        ? "Couldn't send. Try again — or write to contato@dowsnux.com.br."
        : "Não foi possível enviar. Tente de novo — ou escreva pra contato@dowsnux.com.br."));
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className={`modal-overlay ${open ? "open" : ""}`} onClick={close}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <button className="modal-close" onClick={close} aria-label="Close">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M6 6l12 12M18 6l-12 12"/></svg>
        </button>
        {!sent ? (
          <form onSubmit={submit} noValidate>
            <h3>{m.title}</h3>
            <p className="modal-lede">{m.lede}</p>

            {/* Honeypot — hidden from humans, irresistible to bots */}
            <div aria-hidden="true" style={{
              position: "absolute", left: "-9999px", width: 1, height: 1, overflow: "hidden",
            }}>
              <label>Don't fill this</label>
              <input
                tabIndex="-1"
                autoComplete="off"
                value={form.hp}
                onChange={e => setField("hp", e.target.value)}
              />
            </div>

            <div className={`field ${errors.name ? "error" : ""}`}>
              <label>{m.fields.name}</label>
              <input value={form.name} onChange={e => setField("name", e.target.value)} disabled={submitting} />
              {errors.name && <div className="field-error">{errors.name}</div>}
            </div>
            <div className={`field ${errors.email ? "error" : ""}`}>
              <label>{m.fields.email}</label>
              <input type="email" value={form.email} onChange={e => setField("email", e.target.value)} disabled={submitting} />
              {errors.email && <div className="field-error">{errors.email}</div>}
            </div>
            <div className="field">
              <label>{m.fields.company}</label>
              <input value={form.company} onChange={e => setField("company", e.target.value)} disabled={submitting} />
            </div>
            <div className={`field ${errors.scope ? "error" : ""}`}>
              <label>{m.fields.scope}</label>
              <select value={form.scope} onChange={e => setField("scope", e.target.value)} disabled={submitting}>
                <option value="">—</option>
                {m.fields.scopeOptions.map((o, i) => <option key={i} value={o}>{o}</option>)}
              </select>
              {errors.scope && <div className="field-error">{errors.scope}</div>}
            </div>
            <div className="field">
              <label>{m.fields.message}</label>
              <textarea rows="3" value={form.message} onChange={e => setField("message", e.target.value)} disabled={submitting}></textarea>
            </div>

            {submitError && (
              <div className="submit-error" role="alert">{submitError}</div>
            )}

            <button type="submit" className="btn btn-primary btn-arrow" disabled={submitting}>
              {submitting ? (lang === "en" ? "Sending…" : "Enviando…") : m.submit}
              {!submitting && (
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M5 12h14M13 5l7 7-7 7"/></svg>
              )}
            </button>
            <div className="lgpd-note">{m.lgpd}</div>
          </form>
        ) : (
          <div className="modal-success">
            <div className="ok-ring">
              <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3"><path d="M5 12l5 5L20 7"/></svg>
            </div>
            <h3>{m.successTitle}</h3>
            <p className="modal-lede" style={{ marginTop: 12 }}>{m.successBody}</p>
            <button className="btn btn-ghost" onClick={close} style={{ marginTop: 8 }}>OK</button>
          </div>
        )}
      </div>
    </div>
  );
};

Object.assign(window, {
  Proof, Offer, Objections, Guarantee, Urgency, FAQ, FinalCTA, PS, Footer, ContactModal,
});
