"use client";
import Image from "next/image";
import Link from "next/link";
import { useState } from "react";
export {};

declare global {
  interface Window {
    grecaptcha: {
      ready: (cb: () => void) => void;
      execute: (
        siteKey: string,
        options: { action: string }
      ) => Promise<string>;
    };
  }
}


export default function GetInTouch() {
  const [loading, setLoading] = useState(false);
  const [status, setStatus] = useState<"idle" | "success" | "error">("idle");
  const [message, setMessage] = useState("");
  const [errors, setErrors] = useState<{
    email?: string;
    phone?: string;
  }>({});

  const validateEmail = (email: string) => {
    return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
  };

  // Accepts: +91XXXXXXXXXX, 10-digit India, international
  const validatePhone = (phone: string) => {
    return /^(\+?\d{1,3}[\s-]?)?\d{10}$/.test(phone.replace(/\s+/g, ""));
  };
  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setErrors({});
    setLoading(true);
    setStatus("idle");

    const form = e.currentTarget;
    const formData = new FormData(form);

    const email = String(formData.get("your-email") || "");
    const phone = String(formData.get("phone-number") || "");

    const newErrors: typeof errors = {};

    if (!validateEmail(email)) {
      newErrors.email = "Please enter a valid email address";
    }

    if (!validatePhone(phone)) {
      newErrors.phone = "Please enter a valid phone number";
    }

    if (Object.keys(newErrors).length > 0) {
      setErrors(newErrors);
      setLoading(false);
      return; // ⛔ stop submit
    }

    // reCAPTCHA MUST run only after validation
    if (!window.grecaptcha) {
      setStatus("error");
      setMessage("reCAPTCHA not loaded. Please refresh.");
      setLoading(false);
      return;
    }

    const token = await window.grecaptcha.execute(
      "6LfTiLIqAAAAALtd7H1aR7425htCZgH-v9z_IkY0",
      { action: "contactform" }
    );

    // Required CF7 fields
    formData.append("_wpcf7", "52431");
    formData.append("_wpcf7_unit_tag", "wpcf7-f52431-o1");
    formData.append("_wpcf7_recaptcha_response", token);

    try {
      const res = await fetch(
        "https://www.togwe.com/backend/wp-json/contact-form-7/v1/contact-forms/52431/feedback",
        {
          method: "POST",
          body: formData,
        }
      );

      const data = await res.json();

      if (data.status === "mail_sent") {
        setStatus("success");
        form.reset();
      } else {
        setStatus("error");
        setMessage(data.message || "Something went wrong");
      }
    } catch {
      setStatus("error");
      setMessage("Network error. Please try again.");
    } finally {
      setLoading(false);
    }
  }


  return (
    <section className="bg-[#f3f3f3] py-16 relative overflow-hidden">
      <div className="container mx-auto px-4 relative z-11">
        <div className="bg-white rounded-2xl border border-[#202020]/15 p-5 pb-0 lg:pb-0 lg:p-16 grid grid-cols-1 lg:grid-cols-12 gap-16 items-start">

          {/* LEFT – FORM */}
          <div className="lg:col-span-8">
            <h2 className="text-2xl md:text-[40px] font-mono font-medium text-[#202020] mb-10">
              Do you have a project in mind?
              Talk to the experts.
            </h2>

            <form onSubmit={handleSubmit} className="space-y-4 text-[#202020] text-sm">
              {/* Name */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <label className="block mb-1">First Name</label>
                  <input
                    type="text"
                    name="your-name"
                    required
                    placeholder="Enter your first name"
                    className="w-full rounded border border-[#202020]/15 bg-[#f3f3f3] px-4 py-3 focus:outline-none focus:ring-1 focus:ring-black"
                  />
                </div>

                <div>
                  <label className="block text-sm mb-1">Last Name</label>
                  <input
                    type="text"
                    name="last-name"
                    placeholder="Enter your last name"
                    className="w-full rounded border border-[#202020]/15 bg-[#f3f3f3] px-4 py-3 focus:outline-none focus:ring-1 focus:ring-black"
                  />
                </div>
              </div>

              {/* Company */}
              <div>
                <label className="block text-sm mb-1">
                  Company Name
                </label>
                <input
                  type="text"
                  name="company-name"
                  required
                  placeholder="Enter your company name"
                  className="w-full rounded border border-[#202020]/15 bg-[#f3f3f3] px-4 py-3 focus:outline-none focus:ring-1 focus:ring-black"
                />
              </div>

              {/* Email */}
              <div>
                <label className="block text-sm mb-1">Email</label>
                <input
                  type="email"
                  name="your-email"
                  required
                  placeholder="Enter your email"
                  className={`w-full rounded border px-4 py-3 focus:outline-none focus:ring-1
                    ${errors.email ? "border-red-500" : "border-[#202020]/15"}
                  bg-[#f3f3f3]`}
                />

                {errors.email && (
                  <p className="text-red-600 text-xs mt-1">{errors.email}</p>
                )}
              </div>

              {/* Phone + Services */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <label className="block text-sm mb-1">Phone Number</label>
                  <input
                    type="tel"
                    name="phone-number"
                    required
                    placeholder="+91 869 3114 xxx"
                    className={`w-full rounded border px-4 py-3 focus:outline-none focus:ring-1
                      ${errors.phone ? "border-red-500" : "border-[#202020]/15"}
                    bg-[#f3f3f3]`}
                  />

                  {errors.phone && (
                    <p className="text-red-600 text-xs mt-1">{errors.phone}</p>
                  )}
                </div>

                <div>
                  <label htmlFor="services" className="block text-sm mb-1">
                    Services
                  </label>

                  <select
                    id="services"
                    name="services-list"
                    required
                    className="w-full rounded border border-[#202020]/15 bg-[#f3f3f3] px-4 py-3 focus:outline-none focus:ring-1 focus:ring-black"
                  >
                    <option value="">Select services</option>
                    <option value="Sports App Development">Sports App Development</option>
                    <option value="Digital Marketing">Digital Marketing</option>
                    <option value="Content Creation">Content Creation</option>
                    <option value="Customer Support">Customer Support</option>
                    <option value="Branding & Advertising">Branding & Advertising</option>
                    <option value="Sports Sponsorship Management">
                      Sports Sponsorship Management
                    </option>
                  </select>

                </div>
              </div>

              {/* Message */}
              <div>
                <label className="block text-sm mb-1">Message</label>
                <textarea
                  rows={4}
                  name="your-message"
                  placeholder="Tell us what we can help you with"
                  className="w-full rounded border border-[#202020]/15 bg-[#f3f3f3] px-4 py-3 focus:outline-none focus:ring-1 focus:ring-black resize-none"
                />
              </div>

              {/* Submit */}
              <button
                type="submit"
                disabled={loading}
                className="w-full bg-[#202020] text-white py-4 rounded-md font-semibold text-lg hover:bg-black transition disabled:opacity-60 disabled:cursor-not-allowed"
              >
                {loading ? "Submitting..." : "SUBMIT"}
              </button>

              {status === "success" && (
                <p className="text-sm text-green-600 font-medium mt-2">
                  ✅ Thank you! Your message has been sent.
                </p>
              )}

              {status === "error" && (
                <p className="text-sm text-red-600 font-medium mt-2">
                  ❌ {message}
                </p>
              )}

            </form>
          </div>

          {/* RIGHT – CONTACT INFO */}
          <div className="lg:col-span-4 flex flex-col items-start">
            <h3 className="text-2xl md:text-[40px] font-mono font-medium text-[#202020] mb-2">
              Get in Touch
            </h3>

            <p className="text-lg text-[#202020]/70">
              Reach us directly through
            </p>
            <hr className="w-full border-[#202020]/10 my-6" />
            
            <h3 className="text-xl md:text-2xl font-medium text-[#202020] mb-2">
              General Inquiries
            </h3>
            <div className="space-y-3 mb-10">
              <Link href="mailto:hello@togwe.com" className="flex items-center gap-3 text-[16px] text-[#202020] transition">
                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 16 16"><path fill="currentColor" d="M4 3a2 2 0 0 0-2 2v.201l6 3.231l6-3.23V5a2 2 0 0 0-2-2zm10 3.337L8.237 9.44a.5.5 0 0 1-.474 0L2 6.337V11a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2z"/></svg>
                <span>hello@togwe.com</span>
              </Link>
              <Link href="tel:+919091234111" className="flex items-center gap-3 text-[16px] text-[#202020] transition">
                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path fill="currentColor" d="m7.772 2.439l1.077-.344c1.008-.322 2.086.199 2.518 1.217l.86 2.028c.375.883.167 1.922-.514 2.568L9.82 9.706q.175 1.614 1.084 3.177a8.7 8.7 0 0 0 2.271 2.595l2.276-.76c.862-.287 1.801.044 2.33.821l1.232 1.81c.616.904.505 2.15-.258 2.916l-.818.821c-.814.817-1.976 1.114-3.052.778q-3.808-1.188-7.003-7.053q-3.199-5.875-2.258-9.968c.264-1.148 1.082-2.063 2.15-2.404"/></svg>
                <span>+91 909 1234 111</span>
              </Link>
            </div>

            {/* Image */}
            <Image
              src="/contact-us-girl.webp" // replace with your image
              alt="Get in touch"
              width={360}
              height={420}
              className="object-contain"
              priority
            />
          </div>

        </div>
      </div>
      {/* OVERLAY */}
      <div className="absolute bottom-0 left-0 right-0 h-[200px] bg-black z-10" />
    </section>
  );
}
