"use client";
import { useEffect, useRef, useState } from "react";

declare global {
  interface Window {
    turnstile?: {
      render: (el: HTMLElement, options: any) => void;
    };
  }
}

export default function ContatosPage() {
  const [verified, setVerified] = useState(false);
  const widgetRef = useRef<HTMLDivElement | null>(null);

  useEffect(() => {
    const script = document.createElement("script");
    script.src = "https://challenges.cloudflare.com/turnstile/v0/api.js";
    script.async = true;
    script.defer = true;
    script.onload = () => {
      if (widgetRef.current && window.turnstile) {
        window.turnstile.render(widgetRef.current, {
          sitekey: process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY,
          callback: () => setVerified(true),
        });
      }
    };
    document.body.appendChild(script);
    return () => {
      document.body.removeChild(script);
    };
  }, []);

  return (
    <section aria-labelledby="contatos-title">
      <h1 id="contatos-title" className="text-2xl font-bold">Contatos</h1>
      {!verified ? (
        <div>
          <p className="mb-3">Complete o desafio para revelar os contatos:</p>
          <div ref={widgetRef} className="cf-turnstile" />
        </div>
      ) : (
        <div aria-live="polite">
          <h2 className="text-xl font-semibold">Informação de contato</h2>
          <ul className="mt-2">
            <li>Email: <a href="mailto:website@powerlifting.pt">website@powerlifting.pt</a></li>
            <li>Obtenha uma resposta mais rápida no <a href="https://www.instagram.com/aportugalpowerlifting">Instagram</a></li>
          </ul>
        </div>
      )}
    </section>
  );
}
