"use client";

import Link from "next/link";
import { useEffect, useState } from "react";
import type { StateItem } from "@/lib/types";
import { conShortLabel } from "@/components/widgets/ConProfileSection";
import WaitlistForm, { type WaitlistText } from "./WaitlistForm";

export interface StatesGridText {
  openEyebrow: string;
  openHeading: string;
  soonEyebrow: string;
  soonHeading: string;
  soonSubtitle: string;
  joinLabel: string;
  soonPill: string;
  openPill: string;
  noResults: string;
  modalTitle: string;
  modalText: string;
  modalSubmit: string;
  modalSuccess: string;
}

/** States page: open states link to their page; "coming soon" states open a
 *  waitlist modal. Filtered by the hero search box ("msc:state-search"). */
export default function StatesGrid({
  states,
  text,
  formKey,
  waitlist
}: {
  states: StateItem[];
  text: StatesGridText;
  formKey: string;
  waitlist: WaitlistText;
}) {
  const [filter, setFilter] = useState("");
  const [modalState, setModalState] = useState<string | null>(null);
  const [modalKey, setModalKey] = useState(0);

  useEffect(() => {
    const on = (e: Event) => setFilter(String((e as CustomEvent).detail || ""));
    window.addEventListener("msc:state-search", on);
    return () => window.removeEventListener("msc:state-search", on);
  }, []);

  const match = (s: StateItem) => s.name.toLowerCase().includes(filter.toLowerCase());
  const open = states.filter((s) => s.status === "open");
  const soon = states.filter((s) => s.status !== "open");
  const soonShown = soon.filter(match);

  const openModal = (name: string) => {
    setModalState(name);
    setModalKey((k) => k + 1);
    window.dispatchEvent(new CustomEvent("msc:waitlist-state", { detail: name }));
  };

  const fill = (t: string, name: string) => t.split("{name}").join(name);

  return (
    <>
      <div className="section-label">{text.openEyebrow}</div>
      <div className="section-header">
        <h2>{text.openHeading}</h2>
      </div>
      <div className="states-grid">
        {open.map((s) => (
          <Link key={s.slug} className="state-card open" href={s.href} style={match(s) ? undefined : { display: "none" }}>
            <div>
              <div className="state-name">
                {s.code.toUpperCase()} {s.name}
              </div>
              {s.subtitle && <div className="state-sub">{s.subtitle}</div>}
              {s.linkLabel && <span className="notice-link">{s.linkLabel}</span>}
            </div>
            <span className={`state-pill open con-${s.con.status || "unknown"}`}>
              {conShortLabel(s.con.status) || (
                <>
                  <span className="nl-dot" aria-hidden="true" /> {text.openPill}
                </>
              )}
            </span>
          </Link>
        ))}
      </div>

      {soon.length > 0 && (
        <>
      <div className="section-label" style={{ marginTop: 40 }}>
        {text.soonEyebrow}
      </div>
      <div className="section-header">
        <h2>{text.soonHeading}</h2>
      </div>
      <div className="states-grid">
        {soonShown.map((s) => (
          <div key={s.slug} className="state-card" onClick={() => openModal(s.name)} style={{ cursor: "pointer" }}>
            <div>
              <div className="state-name">{s.name}</div>
              <div className="state-sub">{s.subtitle || text.soonSubtitle}</div>
              <span style={{ fontSize: ".78rem", color: "var(--gold)", fontWeight: 600, marginTop: 4, display: "block" }}>{text.joinLabel}</span>
            </div>
            <span className={`state-pill soon con-${s.con.status || "unknown"}`}>{conShortLabel(s.con.status) || text.soonPill}</span>
          </div>
        ))}
      </div>
      {soonShown.length === 0 && <div className="no-results">{text.noResults}</div>}
        </>
      )}

      {soon.length > 0 && (
        <>
      <div
        className={`modal-overlay${modalState ? " open" : ""}`}
        onClick={(e) => {
          if (e.target === e.currentTarget) setModalState(null);
        }}
      >
        <div className="modal">
          <button type="button" className="modal-close" onClick={() => setModalState(null)}>
            x
          </button>
          <h3>{fill(text.modalTitle, modalState || "")}</h3>
          <p>{fill(text.modalText, modalState || "")}</p>
          {modalState && (
            <WaitlistForm
              key={modalKey}
              formKey={formKey}
              fixedState={modalState}
              className="modal-form"
              successClassName="msc-modal-success"
              successStyle={{ textAlign: "center", padding: 16, color: "#065f46", fontWeight: 600 }}
              text={{ ...waitlist, submitLabel: text.modalSubmit, successText: text.modalSuccess, source: `${waitlist.source} (state modal)` }}
            />
          )}
        </div>
      </div>
        </>
      )}
    </>
  );
}
