/* global React, IG_POSTS, CONTACT, Ico, WA_LINK */
const { useState: useState2 } = React;

const FORMSPREE_ID = "meedwzpp";

/* ============================ NOTÍCIAS / INSTAGRAM ============================ */
function Noticias() {
  return (
    <section className="section" id="noticias">
      <div className="wrap">
        <div className="ig-head">
          <div>
            <p className="eyebrow">Notícias &amp; Conteúdo</p>
            <h2 className="section-title" style={{ maxWidth: "15ch" }}>
              Acompanhe de perto no <span className="gold-text">Instagram</span>.
            </h2>
          </div>
          <a className="btn btn-gold" href="https://instagram.com/clefiaadvocacia"
            target="_blank" rel="noopener">
            Seguir @clefiaadvocacia <Ico.arrow className="ar" />
          </a>
        </div>

        <div className="ig-handle" style={{ marginBottom: 34 }}>
          <div className="ava">CS</div>
          <div>
            <b className="gold-text">@clefiaadvocacia</b>
            <span>Dicas jurídicas, bastidores e novidades do escritório</span>
          </div>
        </div>

        <behold-widget feed-id="cuWIlKCviCZo47hDLPHI"></behold-widget>
      </div>
    </section>
  );
}

/* ============================ CONTATO ============================ */
function Contact() {
  const [sent, setSent] = useState2(false);
  const [sending, setSending] = useState2(false);
  const [error, setError] = useState2(null);
  const [form, setForm] = useState2({ nome: "", email: "", tel: "", area: "", msg: "" });
  const set = (k) => (e) => setForm({ ...form, [k]: e.target.value });
  const submit = async (e) => {
    e.preventDefault();
    setSending(true);
    setError(null);
    try {
      const res = await fetch(`https://formspree.io/f/${FORMSPREE_ID}`, {
        method: "POST",
        headers: { "Content-Type": "application/json", Accept: "application/json" },
        body: JSON.stringify({
          nome: form.nome,
          email: form.email,
          telefone: form.tel,
          area: form.area,
          mensagem: form.msg,
        }),
      });
      if (res.ok) {
        setSent(true);
      } else {
        setError("Não foi possível enviar. Tente novamente ou entre em contato pelo WhatsApp.");
      }
    } catch {
      setError("Erro de conexão. Verifique sua internet e tente novamente.");
    } finally {
      setSending(false);
    }
  };
  return (
    <section className="section contact" id="contato">
      <div className="wrap">
        <p className="eyebrow center" style={{ display: "flex", justifyContent: "center" }}>
          Fale Conosco
        </p>
        <h2 className="section-title" style={{ textAlign: "center", marginBottom: 60 }}>
          Vamos conversar sobre <span className="gold-text">o seu caso</span>.
        </h2>
        <div className="contact-grid">
          <div className="contact-info">
            {CONTACT.map((c, ci) => {
              const I = Ico[c.ico];
              const body = (
                <div>
                  <b>{c.label}</b>
                  {c.lines.map((l, k) => <p key={k}>{l}</p>)}
                </div>
              );
              return (
                <div className="ci-item" key={ci}>
                  <span className="ci-ico"><I /></span>
                  {c.href
                    ? <a href={c.href} target="_blank" rel="noopener">{body}</a>
                    : body}
                </div>
              );
            })}
            <p style={{ color: "var(--muted)", fontSize: 14.5, marginTop: 26, lineHeight: 1.6 }}>
              Atendimento com hora marcada, de segunda a sexta.
              Resposta rápida pelo WhatsApp.
            </p>
          </div>

          <div className="form">
            {!sent ? (
              <form onSubmit={submit}>
                <h3>Solicite uma orientação</h3>
                <p className="fp">Preencha os campos abaixo. Entraremos em contato o quanto antes.</p>
                <div className="field">
                  <label>Nome completo</label>
                  <input required value={form.nome} onChange={set("nome")} placeholder="Seu nome" />
                </div>
                <div className="field row">
                  <div className="field">
                    <label>E-mail</label>
                    <input type="email" required value={form.email} onChange={set("email")} placeholder="voce@email.com" />
                  </div>
                  <div className="field">
                    <label>Telefone</label>
                    <input value={form.tel} onChange={set("tel")} placeholder="(71) 90000-0000" />
                  </div>
                </div>
                <div className="field">
                  <label>Área de interesse</label>
                  <select required value={form.area} onChange={set("area")}>
                    <option value="">Selecione…</option>
                    <option>Direito Trabalhista</option>
                    <option>Direito do Consumidor</option>
                    <option>Direito Previdenciário</option>
                    <option>Direito de Família</option>
                    <option>Direito Criminal</option>
                    <option>Direito Civil</option>
                    <option>Direito Tributário</option>
                    <option>Outro</option>
                  </select>
                </div>
                <div className="field">
                  <label>Como podemos ajudar?</label>
                  <textarea value={form.msg} onChange={set("msg")} placeholder="Conte-nos brevemente sobre o seu caso…"></textarea>
                </div>
                {error && (
                  <p style={{ color: "var(--err, #c0392b)", fontSize: 14, marginBottom: 12 }}>{error}</p>
                )}
                <button className="btn btn-gold" type="submit" disabled={sending}
                  style={{ opacity: sending ? 0.7 : 1, cursor: sending ? "wait" : "pointer" }}>
                  {sending ? "Enviando…" : <span>Enviar solicitação <Ico.arrow className="ar" /></span>}
                </button>
              </form>
            ) : (
              <div className="form-success">
                <div className="ok"><Ico.check /></div>
                <h3 className="gold-text">Mensagem enviada!</h3>
                <p className="fp" style={{ marginBottom: 26 }}>
                  Obrigada pelo contato, {form.nome ? form.nome.split(" ")[0] : ""}.
                  Retornaremos em breve. Para atendimento imediato, fale pelo WhatsApp.
                </p>
                <a className="btn btn-gold" href={WA_LINK} target="_blank" rel="noopener"
                  style={{ justifyContent: "center" }}>
                  Falar agora no WhatsApp <Ico.arrow className="ar" />
                </a>
              </div>
            )}
          </div>
        </div>
      </div>
    </section>
  );
}

/* ============================ FOOTER ============================ */
function Footer() {
  const go = (e, id) => { e.preventDefault();
    document.getElementById(id)?.scrollIntoView({ behavior: "smooth" }); };
  return (
    <footer className="footer">
      <div className="wrap">
        <div className="footer-grid">
          <div>
            <a href="#inicio" className="brand" onClick={(e) => go(e, "inicio")}>
              <img src="assets/logo-clefia.png" alt="Cléfia Santos Advocacia" />
            </a>
            <p style={{ color: "var(--muted)", maxWidth: "34ch", marginTop: 18 }}>
              Advocacia especializada com atendimento humano e personalizado.
              Defesa séria e dedicada dos seus direitos, em Salvador e em todo o Brasil.
            </p>
          </div>
          <div className="footer-col">
            <h4>Navegação</h4>
            {window.NAV.map((n) => (
              <a key={n.id} href={"#" + n.id} onClick={(e) => go(e, n.id)}>{n.label}</a>
            ))}
          </div>
          <div className="footer-col">
            <h4>Contato</h4>
            <a href={WA_LINK} target="_blank" rel="noopener">(71) 98716-0302</a>
            <a href="tel:+557141030302">(71) 4103-0302</a>
            <a href="mailto:contato@clefiasantos.adv.br">contato@clefiasantos.adv.br</a>
            <a href="https://instagram.com/clefiaadvocacia" target="_blank" rel="noopener">@clefiaadvocacia</a>
            <p style={{ marginTop: 14 }}>Av. Estados Unidos, nº 58 — Ed. Cidade de Aracaju, sala 611. Comércio, Salvador — BA.</p>
            <p style={{ marginTop: 8 }}>A. Sete de Setembro, 400 — Ed. Fundação Politécnica, sala 93 A. Centro, Salvador — BA.</p>
          </div>
        </div>
        <div className="footer-bottom">
          <p>© {new Date().getFullYear()} Cléfia Santos Advocacia &amp; Consultoria. Todos os direitos reservados.</p>
          <p className="oab">Desenvolvido por Maxicode Soluções em Tecnologia</p>
        </div>
      </div>
    </footer>
  );
}

/* ============================ WHATSAPP FLOAT ============================ */
function WhatsAppFloat() {
  return (
    <a className="wa-float" href={WA_LINK} target="_blank" rel="noopener" aria-label="Falar no WhatsApp">
      <span className="wa-tip">Fale com a <b>Dra. Cléfia</b></span>
      <span className="wa-btn">
        <span className="wa-pulse"></span>
        <Ico.wa width="34" height="34" />
      </span>
    </a>
  );
}

/* ============================ NOTÍCIAS JURÍDICAS ============================ */
const CONJUR_RSS = "https://www.conjur.com.br/rss.xml";
const PROXIES = [
  `https://api.codetabs.com/v1/proxy?quest=${encodeURIComponent(CONJUR_RSS)}`,
  `https://api.allorigins.win/raw?url=${encodeURIComponent(CONJUR_RSS)}`,
];

function parseRSS(xml) {
  const parser = new DOMParser();
  const doc = parser.parseFromString(xml, "text/xml");
  const get = (el, tag) => el.getElementsByTagName(tag)[0]?.textContent?.trim() || "";
  return Array.from(doc.getElementsByTagName("item")).slice(0, 6).map((item) => ({
    title: get(item, "title"),
    link: get(item, "link"),
    pubDate: get(item, "pubDate"),
  }));
}

async function fetchRSS(proxies) {
  for (const url of proxies) {
    try {
      const r = await fetch(url);
      if (!r.ok) continue;
      const xml = await r.text();
      const items = parseRSS(xml);
      if (items.length) return items;
    } catch { /* tenta o próximo */ }
  }
  return [];
}

function NoticiasJuridicas() {
  const [posts, setPosts] = useState2([]);
  const [status, setStatus] = useState2("loading");

  React.useEffect(() => {
    fetchRSS(PROXIES).then((items) => {
      if (items.length) {
        setPosts(items);
        setStatus("ok");
      } else {
        setStatus("error");
      }
    });
  }, []);

  const fmt = (dateStr) => {
    const d = new Date(dateStr);
    return d.toLocaleDateString("pt-BR", { day: "2-digit", month: "short", year: "numeric" });
  };

  return (
    <section className="section" id="noticias-juridicas">
      <div className="wrap">
        <p className="eyebrow center" style={{ display: "flex", justifyContent: "center" }}>Atualização Jurídica</p>
        <h2 className="section-title" style={{ textAlign: "center", marginBottom: 48 }}>
          Notícias
        </h2>

        {status === "loading" && (
          <div className="news-loading">
            {Array.from({ length: 6 }).map((_, i) => <div className="news-skel" key={i}></div>)}
          </div>
        )}

        {status === "error" && (
          <p style={{ textAlign: "center", color: "var(--muted)", padding: "40px 0" }}>
            Não foi possível carregar as notícias. Tente novamente mais tarde.
          </p>
        )}

        {status === "ok" && (
          <div className="news-grid">
            {posts.map((p, i) => (
              <a className="news-card" key={i} href={p.link} target="_blank" rel="noopener noreferrer">
                <span className="news-date">{p.pubDate ? fmt(p.pubDate) : ""}</span>
                <h3 className="news-title">{p.title}</h3>
                <span className="news-more">Ler no Conjur <Ico.arrow className="ar" /></span>
              </a>
            ))}
          </div>
        )}

        <p style={{ textAlign: "center", marginTop: 36 }}>
          <a className="btn btn-outline" href="https://www.conjur.com.br" target="_blank" rel="noopener">
            Ver mais no Conjur <Ico.arrow className="ar" />
          </a>
        </p>
      </div>
    </section>
  );
}

/* ============================ LGPD COOKIE BANNER ============================ */
function CookieBanner() {
  const [visible, setVisible] = useState2(() => !localStorage.getItem("lgpd_ok"));
  if (!visible) return null;
  const accept = () => { localStorage.setItem("lgpd_ok", "1"); setVisible(false); };
  return (
    <div className="cookie-banner">
      <p className="cookie-text">
        Este site utiliza cookies e coleta dados pessoais (nome, e-mail, telefone) exclusivamente
        para responder às suas solicitações de contato, em conformidade com a{" "}
        <strong>LGPD — Lei nº 13.709/2018</strong>.
      </p>
      <div className="cookie-actions">
        <button className="btn btn-gold cookie-btn" onClick={accept}>Aceitar e fechar</button>
      </div>
    </div>
  );
}

window.Sections2 = { Noticias, NoticiasJuridicas, Contact, Footer, WhatsAppFloat, CookieBanner };
