"use client";

import { useState, useRef, type FormEvent } from "react";
import { CheckIcon } from "./icons";
import type { HomeContent } from "@/lib/content";
import { trackEvent } from "@/components/Tracking";
import RecaptchaV2, { type RecaptchaHandle } from "@/components/RecaptchaV2";

declare var fbq: ((...args: unknown[]) => void) | undefined;
declare var gtag: (...args: unknown[]) => void;

const WP_SUBMIT_URL =
  (process.env.NEXT_PUBLIC_WORDPRESS_URL || "") +
  "/wp-json/sigma/v1/submit-lead";

type Status = "idle" | "sending" | "sent" | "error";

export default function LeadSection({ content }: { content: HomeContent }) {
  const { lead } = content;
  const [status, setStatus] = useState<Status>("idle");
  const [error, setError] = useState<string>("");
  const [formStarted, setFormStarted] = useState(false);
  const recaptchaRef = useRef<RecaptchaHandle>(null);

  async function onSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault();
    if (!formStarted) setFormStarted(true);
    setStatus("sending");
    setError("");

    const recaptchaToken = recaptchaRef.current?.getToken() ?? "";
    if (!recaptchaToken) {
      setStatus("error");
      setError("Please complete the reCAPTCHA verification.");
      return;
    }

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

    const payload: Record<string, unknown> = {
      firstName: data.get("firstName"),
      lastName: data.get("lastName"),
      company: data.get("company"),
      email: data.get("email"),
      phone: data.get("phone"),
      smsConsent: data.get("smsConsent") === "on",
      recaptcha_token: recaptchaToken,
    };

    try {
      const res = await fetch(WP_SUBMIT_URL, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });
      const raw = await res.text();
      const brace = raw.lastIndexOf("{");
      const json = (
        brace >= 0 ? JSON.parse(raw.slice(brace)) : { ok: false }
      ) as {
        ok: boolean;
        message?: string;
        duplicate?: boolean;
        entry_id?: number;
      };
      if (json.ok) {
        setStatus("sent");
        const gfTitle = lead.formTitle || "Request Information";
        window.dataLayer?.push({ event: "form_submit", form_name: gfTitle });
        window.dataLayer?.push({ event: "lead_submit", entry_id: json.entry_id ?? 0, is_duplicate: !!json.duplicate });
        if (typeof fbq !== "undefined") fbq("track", "Lead");
        if (typeof gtag !== "undefined") {
          gtag("event", "conversion", { send_to: "AW-979437692/QNq2CJXIoG0Q_JCE0wM" });
          gtag("event", "conversion", { send_to: "AW-979437692/92JCCJyWywcQ_JCE0wM", value: 1.0, currency: "USD" });
        }
      } else {
        trackEvent("form_submit", { form_name: lead.formTitle, status: "error", message: json.message });
        setStatus("error");
        setError(json.message ?? "Something went wrong. Please call us instead.");
      }
    } catch {
      setStatus("error");
      setError("Network error. Please try again or call us.");
    }
  }

  return (
    <section id="lead" style={{ padding: "110px 0" }}>
      <div className="container-lead">
        <div
          className="lead-grid"
          style={{
            position: "relative",
            borderRadius: 30,
            overflow: "hidden",
            boxShadow: "0 30px 70px rgba(2,47,49,.14)",
            border: "1px solid rgba(255,255,255,.7)",
          }}
        >
          {/* left: pitch */}
          <div
            className="lead-panel"
            style={{
              position: "relative",
              overflow: "hidden",
              background: "linear-gradient(160deg, rgba(19,163,166,.18), rgba(0,101,104,.10))",
              backdropFilter: "blur(16px)",
              WebkitBackdropFilter: "blur(16px)",
              padding: "56px 52px",
            }}
          >
            <div
              style={{
                position: "absolute",
                top: -90,
                right: -70,
                width: 300,
                height: 300,
                background: "radial-gradient(circle, rgba(234,213,145,.4), transparent 64%)",
              }}
            />
            <div style={{ position: "relative" }}>
              <div
                style={{
                  display: "inline-flex",
                  alignItems: "center",
                  gap: 8,
                  background: "rgba(255,255,255,.6)",
                  border: "1px solid rgba(255,255,255,.8)",
                  borderRadius: 999,
                  padding: "8px 16px",
                }}
              >
                <span style={{ width: 6, height: 6, borderRadius: "50%", background: "#c9a62f" }} />
                <span
                  style={{
                    fontSize: 11,
                    fontWeight: 700,
                    letterSpacing: ".14em",
                    textTransform: "uppercase",
                    color: "#006568",
                  }}
                >
                  {lead.badge}
                </span>
              </div>
              <h2
                style={{
                  fontWeight: 900,
                  fontSize: 36,
                  lineHeight: 1.08,
                  letterSpacing: "-.025em",
                  margin: "18px 0 0",
                  color: "#182233",
                }}
              >
                {lead.titleLead}
                <span style={{ color: "#006568" }}>{lead.titleAccent}</span>
              </h2>
              <p style={{ fontSize: 16, lineHeight: 1.6, color: "#4a545c", margin: "14px 0 0" }}>{lead.body}</p>
              <ul style={{ listStyle: "none", padding: 0, margin: "28px 0 0", display: "flex", flexDirection: "column", gap: 14 }}>
                {lead.benefits.map((b) => (
                  <li key={b} style={{ display: "flex", gap: 11, fontSize: 15, color: "#27333a" }}>
                    <span
                      style={{
                        flex: "0 0 auto",
                        width: 22,
                        height: 22,
                        borderRadius: "50%",
                        background: "#006568",
                        color: "#fff",
                        display: "flex",
                        alignItems: "center",
                        justifyContent: "center",
                      }}
                    >
                      <CheckIcon size={13} strokeWidth={3} />
                    </span>
                    <span>{b}</span>
                  </li>
                ))}
              </ul>
              <a
                href={lead.phoneHref}
                style={{
                  display: "inline-block",
                  marginTop: 30,
                  fontSize: 15,
                  fontWeight: 700,
                  color: "#006568",
                  borderBottom: "2px solid #c9a62f",
                  paddingBottom: 3,
                }}
              >
                Prefer to call? {lead.phoneDisplay}
              </a>
            </div>
          </div>

          {/* right: form */}
          <div
            className="lead-panel"
            style={{
              background: "rgba(255,255,255,.72)",
              backdropFilter: "blur(16px)",
              WebkitBackdropFilter: "blur(16px)",
              padding: "56px 52px",
            }}
          >
            <h3 style={{ fontWeight: 900, fontSize: 24, margin: "0 0 6px", color: "#182233" }}>{lead.formTitle}</h3>
            <p style={{ fontSize: 14, color: "#63686d", margin: "0 0 24px" }}>{lead.formSubtitle}</p>
            {status === "sent" ? (
              <div
                role="status"
                style={{
                  display: "flex",
                  alignItems: "center",
                  gap: 12,
                  background: "#e6f3f1",
                  border: "1px solid rgba(0,101,104,.25)",
                  borderRadius: 14,
                  padding: "18px 20px",
                  color: "#022f31",
                  fontSize: 15,
                }}
              >
                <span
                  style={{
                    flex: "0 0 auto",
                    width: 26,
                    height: 26,
                    borderRadius: "50%",
                    background: "#006568",
                    color: "#fff",
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                  }}
                >
                  <CheckIcon size={14} strokeWidth={3} />
                </span>
                Thanks — we received your request and will call within one business day.
              </div>
            ) : (
              <form onSubmit={onSubmit}>
                <div className="form-grid">
                  <input className="field" type="text" name="firstName" placeholder="First name" aria-label="First name" required onFocus={() => { if (!formStarted) { setFormStarted(true); trackEvent("form_start", { form_name: location.pathname === "/" ? "Home Form" : document.title }); } }} />
                  <input className="field" type="text" name="lastName" placeholder="Last name" aria-label="Last name" required />
                  <input className="field" type="text" name="company" placeholder="Company" aria-label="Company" style={{ gridColumn: "1 / -1" }} />
                  <input className="field" type="email" name="email" placeholder="Email" aria-label="Email" required />
                  <input className="field" type="tel" name="phone" placeholder="Phone" aria-label="Phone" required />
                </div>

                {formStarted && <RecaptchaV2 ref={recaptchaRef} />}

                <button
                  className="btn-teal"
                  type="submit"
                  disabled={status === "sending"}
                  style={{
                    width: "100%",
                    marginTop: 20,
                    fontSize: 16,
                    padding: 16,
                    boxShadow: "0 14px 30px rgba(0,101,104,.3)",
                  }}
                >
                  {status === "sending" ? "Sending…" : lead.submitLabel}
                </button>

                {status === "error" && (
                  <p role="alert" style={{ marginTop: 12, fontSize: 13, color: "#b3261e" }}>
                    {error}
                  </p>
                )}
                <label
                  style={{
                    display: "flex",
                    gap: 9,
                    alignItems: "flex-start",
                    marginTop: 16,
                    fontSize: 12,
                    lineHeight: 1.5,
                    color: "#63686d",
                  }}
                >
                  <input type="checkbox" name="smsConsent" style={{ marginTop: 3 }} />
                  <span>By checking this box, I agree to receive SMS messages about conversational from Sigma Tax Pro at the phone number provided above. The SMS frequency may vary. Data rates may apply. Text HELP to (561) 20450-6422 for assistance. Reply STOP to opt out of receiving SMS messages. Please review our Privacy Policy.</span>
                </label>
              </form>
            )}
          </div>
        </div>
      </div>
    </section>
  );
}
