"use client";

import Link from "next/link";
import { useEffect, useRef, useState } from "react";

export default function Footer() {
  const [submitted, setSubmitted] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [errors, setErrors] = useState<Record<string, boolean>>({});
  const [backToTopVisible, setBackToTopVisible] = useState(false);
  const formRef = useRef<HTMLFormElement>(null);

  useEffect(() => {
    function onScroll() {
      setBackToTopVisible(window.scrollY > 600);
    }
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    const form = e.currentTarget;
    const name = (form.elements.namedItem("name") as HTMLInputElement).value.trim();
    const phone = (form.elements.namedItem("phone") as HTMLInputElement).value.trim();
    const service = (form.elements.namedItem("service") as HTMLSelectElement).value;
    const email = (form.elements.namedItem("email") as HTMLInputElement).value.trim();
    const message = (form.elements.namedItem("message") as HTMLTextAreaElement).value.trim();

    const nextErrors: Record<string, boolean> = {};
    if (!name) nextErrors.name = true;
    if (!phone) nextErrors.phone = true;
    if (!service) nextErrors.service = true;
    if (!message) nextErrors.message = true;
    if (Object.keys(nextErrors).length) {
      setErrors(nextErrors);
      return;
    }

    setSubmitting(true);
    setErrors({});
    const token = (() => {
      try {
        return sessionStorage.getItem("tsl_token") || "";
      } catch {
        return "";
      }
    })();
    const payload = { name, phone, email, service, message, subject: service };
    const headers: Record<string, string> = { "Content-Type": "application/json" };
    if (token) headers.Authorization = `Bearer ${token}`;

    fetch("/api/contact", {
      method: "POST",
      headers,
      body: JSON.stringify(payload),
    })
      .then(async (r) => {
        const data = await r.json().catch(() => ({}));
        if (data.needsLogin) {
          const wa =
            "Hello, I am " +
            name +
            ". " +
            message +
            " (Phone: " +
            phone +
            (email ? ", Email: " + email : "") +
            ", Service: " +
            service +
            ")";
          window.open(
            "https://wa.me/919836233354?text=" + encodeURIComponent(wa),
            "_blank",
            "noopener,noreferrer"
          );
          setSubmitted(true);
          form.reset();
          return;
        }
        if (!r.ok || !data.success) {
          throw new Error(
            data.error ||
              "Could not send your message. Please try again or WhatsApp us on 9836233354."
          );
        }
        setSubmitted(true);
        form.reset();
      })
      .catch((err: Error) => {
        setErrors({ form: true });
        alert(err.message || "Could not send your message. Please WhatsApp us on 9836233354.");
      })
      .finally(() => {
        setSubmitting(false);
      });
  }

  function clearError(field: string) {
    if (errors[field]) setErrors((e) => ({ ...e, [field]: false }));
  }

  return (
    <>
      <footer
        className="site-footer"
        role="contentinfo"
        itemScope
        itemType="https://schema.org/LocalBusiness"
      >
        {/* Hidden SEO links */}
        <div className="seo-hidden" aria-hidden="true">
          <Link href="/laundry">On Demand Laundry Services Kolkata</Link>
          <Link href="/express-services">Same Day Laundry Service Kolkata</Link>
          <Link href="/express-services">Laundry Delivery in 24 Hours</Link>
          <Link href="/laundry">Express Laundry Service India</Link>
          <Link href="/laundry">Standard Laundry Delivery</Link>
          <Link href="/pickup">Doorstep Laundry Pickup Delivery Kolkata</Link>
          <Link href="/laundry">Laundry Services India</Link>
          <Link href="/our-process">Laundry Facilities</Link>
          <Link href="/our-process">Laundry Machine</Link>
          <Link href="/our-process">Laundry Chemical</Link>
          <Link href="/our-process">Laundry Service Process</Link>
          <Link href="/carpet-home-care">Carpet Cleaning Kolkata</Link>
          <Link href="/membership">Laundry Membership Card</Link>
          <Link href="/price-list">Laundry Price List Kolkata</Link>
          <Link href="/reviews">Laundry Service Feedback</Link>
          <Link href="/contact">Digital Payment Laundry</Link>
          <Link href="/referral">Laundry Referral Program India</Link>
          <Link href="/our-process">Laundry Software</Link>
          <Link href="/franchise">Laundry Service Franchise India</Link>
          <Link href="/about">About The Swiss Laundry Kolkata</Link>
          <Link href="/gift-cards">Gift Cards Wedding India</Link>
          <Link href="/offers">Laundry Dry Cleaning Offers Kolkata</Link>
          <Link href="/what-is-steam-pressing">Steam Ironing Service Kolkata</Link>
          <Link href="/stain-removal">Stain Removal Service India</Link>
          <span itemProp="name">The Swiss Laundry</span>
          <span itemProp="telephone">+91-8335888167</span>
          <span itemProp="email">info@theswisslaundry.com</span>
        </div>

        {/* CONTACT FORM STRIP */}
        <div className="footer-form-strip">
          <div className="footer-form-wrap">
            <div className="footer-form-header">
              <p className="footer-form-eye">Get In Touch</p>
              <h3 className="footer-form-title">
                Have garments to be dry cleaned or a query about our service?
                <br />
                Our team will get back to you as soon as we can.
              </h3>
            </div>
            {!submitted ? (
              <form
                className="footer-form"
                ref={formRef}
                onSubmit={handleSubmit}
                noValidate
              >
                <div className="footer-form-row">
                  <div className="footer-form-field">
                    <label htmlFor="fc-name" className="footer-form-label">
                      Full Name
                    </label>
                    <input
                      type="text"
                      id="fc-name"
                      name="name"
                      placeholder="Your name"
                      autoComplete="name"
                      required
                      onInput={() => clearError("name")}
                      style={errors.name ? { borderColor: "rgba(192,65,90,0.7)" } : undefined}
                    />
                  </div>
                  <div className="footer-form-field">
                    <label htmlFor="fc-phone" className="footer-form-label">
                      Phone Number
                    </label>
                    <input
                      type="tel"
                      id="fc-phone"
                      name="phone"
                      placeholder="+91 XXXXX XXXXX"
                      autoComplete="tel"
                      required
                      onInput={() => clearError("phone")}
                      style={errors.phone ? { borderColor: "rgba(192,65,90,0.7)" } : undefined}
                    />
                  </div>
                  <div className="footer-form-field">
                    <label htmlFor="fc-email" className="footer-form-label">
                      Email Address
                    </label>
                    <input
                      type="email"
                      id="fc-email"
                      name="email"
                      placeholder="your@email.com"
                      autoComplete="email"
                    />
                  </div>
                  <div className="footer-form-field">
                    <label htmlFor="fc-service" className="footer-form-label">
                      Service Required
                    </label>
                    <select
                      id="fc-service"
                      name="service"
                      required
                      defaultValue=""
                      onChange={() => clearError("service")}
                      style={errors.service ? { borderColor: "rgba(192,65,90,0.7)" } : undefined}
                    >
                      <option value="" disabled>
                        Select a service
                      </option>
                      <option value="dry-cleaning">Dry Cleaning</option>
                      <option value="laundry">Laundry</option>
                      <option value="carpet-home-care">Carpet &amp; Home Care</option>
                      <option value="stain-removal">Stain Removal</option>
                      <option value="steam-ironing">Steam Ironing</option>
                      <option value="same-day">Same Day Service</option>
                      <option value="other">Other</option>
                    </select>
                  </div>
                </div>
                <div className="footer-form-field footer-form-field-full">
                  <label htmlFor="fc-message" className="footer-form-label">
                    Message
                  </label>
                  <textarea
                    id="fc-message"
                    name="message"
                    placeholder="Tell us about your garments — fabric, occasion, any special requirements..."
                    rows={3}
                  />
                </div>
                <div className="footer-form-submit-row">
                  <p className="footer-form-legal">
                    Protected by reCAPTCHA.{" "}
                    <a href="https://policies.google.com/privacy" target="_blank" rel="noopener">
                      Privacy
                    </a>{" "}
                    ·{" "}
                    <a href="https://policies.google.com/terms" target="_blank" rel="noopener">
                      Terms
                    </a>
                  </p>
                  <button
                    type="submit"
                    className="footer-form-btn"
                    disabled={submitting}
                    style={submitting ? { opacity: 0.6 } : undefined}
                  >
                    <span className="footer-form-btn-txt">Send Message</span>
                    <span className="footer-form-btn-arrow">→</span>
                  </button>
                </div>
              </form>
            ) : (
              <div className="footer-form-success">
                <p>Thank you. We will be in touch within the hour.</p>
              </div>
            )}
          </div>
        </div>

        {/* MAIN FOOTER COLUMNS */}
        <div className="footer-main">
          <div className="footer-col footer-col-brand">
            <Link href="/" aria-label="The Swiss Laundry — Home">
              <img
                src="/images/section1-img-11.png"
                alt="The Swiss Laundry logo"
                className="footer-logo"
                loading="lazy"
              />
            </Link>
            <p
              className="footer-seo-text footer-seo-hidden"
              aria-hidden="true"
              style={{
                position: "absolute",
                width: 1,
                height: 1,
                overflow: "hidden",
                clip: "rect(0,0,0,0)",
                whiteSpace: "nowrap",
                pointerEvents: "none",
              }}
            >
              The Swiss Laundry is a professional dry cleaning and laundry service provider
              based in Kolkata, India. We specialise in dry cleaning of wedding dresses, bridal
              lehengas, sherwanis, leather jackets and heavy embroidered garments. Our services
              include professional laundry, carpet cleaning, upholstery cleaning, stain removal,
              steam ironing, laundry consultancy and laundry franchise across India. We use both
              Perc-based and Hydrocarbon-based dry cleaning machines with eco-friendly solvents.
              Doorstep pickup and delivery, online laundry booking, cashless digital payment and
              express laundry delivery available across Kolkata and India.
            </p>
            <p className="footer-brand-statement">
              Extraordinary garment care,
              <br />
              delivered to your door.
            </p>
          </div>

          <div className="footer-col">
            <h4 className="footer-col-title">Our Services</h4>
            <ul className="footer-links">
              <li><Link href="/dry-cleaning">Dry Cleaning</Link></li>
              <li><Link href="/laundry">Laundry</Link></li>
              <li><Link href="/carpet-home-care">Carpet &amp; Home Care</Link></li>
              <li><Link href="/what-is-steam-pressing">Steam Ironing</Link></li>
              <li><Link href="/stain-removal">Stain Removal</Link></li>
              <li><Link href="/express-services">Same Day Delivery</Link></li>
              <li><Link href="/laundry">Express Laundry</Link></li>
              <li><Link href="/pickup">Doorstep Pickup &amp; Delivery</Link></li>
              <li><Link href="/dry-cleaning">Our Process</Link></li>
              <li><Link href="/price-list">Price List</Link></li>
            </ul>
          </div>

          <div className="footer-col">
            <h4 className="footer-col-title">Company</h4>
            <ul className="footer-links">
              <li><Link href="/about">About Us</Link></li>
              <li><Link href="/faq">FAQ</Link></li>
              <li><Link href="/track-order">Track Your Order</Link></li>
              <li><Link href="/membership">Membership Card</Link></li>
              <li><Link href="/gift-cards">Gift Cards</Link></li>
              <li><Link href="/offers">Coupons &amp; Offers</Link></li>
              <li><Link href="/referral">Referral Program</Link></li>
              <li><Link href="/franchise">Franchise India</Link></li>
              <li><Link href="/careers">Careers</Link></li>
              <li><Link href="/csr">CSR</Link></li>
            </ul>
          </div>

          <div className="footer-col footer-col-contact">
            <h4 className="footer-col-title">Contact Us</h4>

            <div
              className="footer-contact-compact"
              itemProp="address"
              itemScope
              itemType="https://schema.org/PostalAddress"
            >
              <p className="footer-contact-row">
                <span className="fcc-lbl">📍</span>
                <span itemProp="streetAddress">
                  P-4 Kasba Industrial Estate, E.M. Bypass (East), Kolkata
                </span>
                <span itemProp="postalCode" style={{ display: "none" }}>700107</span>
                <span itemProp="addressCountry" style={{ display: "none" }}>India</span>
              </p>
              <p className="footer-contact-row">
                <span className="fcc-lbl">📞</span>
                <a href="tel:+918335888167" itemProp="telephone">8335888167</a>
                <span className="fcc-sep">·</span>
                <a href="tel:+919836233354">9836233354</a>
              </p>
              <p className="footer-contact-row">
                <span className="fcc-lbl">✉</span>
                <a href="mailto:info@theswisslaundry.com" itemProp="email">
                  info@theswisslaundry.com
                </a>
              </p>
              <p className="footer-contact-row" itemProp="openingHours" content="Mo-Sa 10:00-17:00">
                <span className="fcc-lbl">🕐</span>
                Mon–Sat 10AM–5PM &nbsp;·&nbsp; Sun &amp; Holidays Closed
              </p>
            </div>

            <div className="footer-social">
              <a
                href="https://www.instagram.com/theswisslaundry_drycleaners/"
                target="_blank"
                rel="noopener"
                aria-label="Instagram"
                className="footer-social-ico"
              >
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
                  <rect x="2" y="2" width="20" height="20" rx="5" />
                  <circle cx="12" cy="12" r="4" />
                  <circle cx="17.5" cy="6.5" r="0.5" fill="currentColor" stroke="none" />
                </svg>
              </a>
              <a
                href="https://www.facebook.com/TheSwissLaundry"
                target="_blank"
                rel="noopener"
                aria-label="Facebook"
                className="footer-social-ico"
              >
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
                  <path d="M18 2h-3a5 5 0 00-5 5v3H7v4h3v8h4v-8h3l1-4h-4V7a1 1 0 011-1h3z" />
                </svg>
              </a>
              <a
                href="https://www.youtube.com/@TheSwissLaundry"
                target="_blank"
                rel="noopener"
                aria-label="YouTube"
                className="footer-social-ico"
              >
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
                  <path d="M22.54 6.42a2.78 2.78 0 00-1.94-1.96C18.88 4 12 4 12 4s-6.88 0-8.6.46A2.78 2.78 0 001.46 6.42 29 29 0 001 12a29 29 0 00.46 5.58A2.78 2.78 0 003.4 19.54C5.12 20 12 20 12 20s6.88 0 8.6-.46a2.78 2.78 0 001.94-1.96A29 29 0 0023 12a29 29 0 00-.46-5.58z" />
                  <polygon points="9.75 15.02 15.5 12 9.75 8.98 9.75 15.02" fill="currentColor" stroke="none" />
                </svg>
              </a>
              <a
                href="https://wa.me/918335888167"
                target="_blank"
                rel="noopener"
                aria-label="WhatsApp"
                className="footer-social-ico footer-social-wa"
              >
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
                  <path d="M21 11.5a8.38 8.38 0 01-.9 3.8 8.5 8.5 0 01-7.6 4.7 8.38 8.38 0 01-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 01-.9-3.8 8.5 8.5 0 014.7-7.6 8.38 8.38 0 013.8-.9h.5a8.48 8.48 0 018 8v.5z" />
                </svg>
              </a>
            </div>

            <div className="footer-apps">
              <p className="footer-apps-label">Download Our App</p>
              <div className="footer-apps-row">
                <a
                  href="https://apps.apple.com/in/app/swiss-laundry/id1630547588"
                  target="_blank"
                  rel="noopener"
                  className="footer-app-badge"
                  aria-label="Download on App Store"
                >
                  <div className="footer-app-inner">
                    <div className="footer-app-icon" />
                    <div className="footer-app-text">
                      <span className="footer-app-sub">Download on the</span>
                      <span className="footer-app-name">App Store</span>
                    </div>
                  </div>
                </a>
                <a
                  href="https://play.google.com/store/apps/details?id=com.theswisslaundry.app"
                  target="_blank"
                  rel="noopener"
                  className="footer-app-badge"
                  aria-label="Get it on Google Play"
                >
                  <div className="footer-app-inner">
                    <div className="footer-app-icon" style={{ fontSize: 18 }}>▶</div>
                    <div className="footer-app-text">
                      <span className="footer-app-sub">Get it on</span>
                      <span className="footer-app-name">Google Play</span>
                    </div>
                  </div>
                </a>
              </div>
              <div className="footer-chotu">
                <img
                  src="/images/section1-img-12.jpg"
                  alt="Chotusingh — The Swiss Laundry"
                  className="footer-chotu-img"
                  loading="lazy"
                />
                <p className="footer-chotu-line">Some members of the family never clock out.</p>
              </div>
            </div>
          </div>
        </div>

        <div className="footer-legal">
          <div className="footer-legal-inner">
            <div className="footer-legal-links">
              <Link href="/privacy-policy">Privacy Policy</Link>
              <span className="footer-sep">·</span>
              <Link href="/terms-and-conditions">Terms &amp; Conditions</Link>
              <span className="footer-sep">·</span>
              <Link href="/cancellation-policy" title="Cancellation Policy — The Swiss Laundry">
                Cancellation Policy
              </Link>
              <span className="footer-sep">·</span>
              <Link href="/site-map" title="Site Map — The Swiss Laundry">Site Map</Link>
              <span className="footer-sep">·</span>
              <span className="footer-legal-txt">
                Grievance Officer: Anand Bhatt —{" "}
                <a href="mailto:info@theswisslaundry.com">info@theswisslaundry.com</a>
              </span>
            </div>
            <p className="footer-copyright">
              © 2013–<span suppressHydrationWarning>{new Date().getFullYear()}</span> The Swiss
              Laundry. All rights reserved. Compliant with the Information Technology Act, 2000
              &amp; Consumer Protection (E-Commerce) Rules, 2020.
            </p>
          </div>
        </div>
      </footer>

      <a
        href="#top"
        className={`back-to-top${backToTopVisible ? " visible" : ""}`}
        aria-label="Back to top"
        onClick={(e) => {
          e.preventDefault();
          window.scrollTo({ top: 0, behavior: "smooth" });
        }}
      >
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" aria-hidden="true">
          <path d="M12 19V5M5 12l7-7 7 7" />
        </svg>
      </a>
    </>
  );
}
