// PasswordGate.jsx — splash screen that gates access to the site

const ACCESS_COOKIE = "sl-wedding-access";
const COOKIE_MAX_AGE = 60 * 60 * 24 * 365 * 10; // 10 years

function readAccessCookie() {
  const match = document.cookie.match(
    new RegExp("(?:^|; )" + ACCESS_COOKIE + "=([^;]*)"),
  );
  return match ? decodeURIComponent(match[1]) : null;
}

function setAccessCookie() {
  document.cookie =
    ACCESS_COOKIE + "=1; path=/; max-age=" + COOKIE_MAX_AGE + "; SameSite=Lax";
}

function HeroTitle() {
  return (
    <div className="hero-names" id="hero-names">
      <h1 className="hero-h" style={{ fontWeight: 500 }}>
        <span className="hero-name-part">Sara</span>
        <span className="hero-amp" aria-hidden="true">
          {" "}
          &amp;{" "}
        </span>
        <span className="hero-name-part">Lorenzo</span>
      </h1>
    </div>
  );
}

function isBrowserItalian() {
  return (navigator.language || "").toLowerCase().startsWith("it");
}

function PasswordGate({ children }) {
  const [authed, setAuthed] = React.useState(() => readAccessCookie() === "1");
  const [passwords, setPasswords] = React.useState(null);
  const [password, setPassword] = React.useState("");
  const [error, setError] = React.useState("");
  const [checking, setChecking] = React.useState(false);

  React.useEffect(() => {
    if (authed) return;
    let cancelled = false;
    fetch("wedding/passwords.json")
      .then((res) => {
        if (!res.ok) throw new Error("load failed");
        return res.json();
      })
      .then((list) => {
        if (cancelled) return;
        setPasswords(new Set(list.map((p) => p.toLowerCase())));
      })
      .catch(() => {
        if (!cancelled) {
          setError("Unable to verify access. Please refresh the page.");
        }
      });
    return () => {
      cancelled = true;
    };
  }, [authed]);

  const submit = (e) => {
    e.preventDefault();
    if (checking || !passwords) return;
    setChecking(true);
    setError("");
    const normalized = password.trim().toLowerCase();
    if (passwords.has(normalized)) {
      setAccessCookie();
      setAuthed(true);
      return;
    }
    setError(isBrowserItalian() ? "Password errata" : "Incorrect Password");
    setChecking(false);
  };

  if (authed) return children;

  return (
    <div className="password-splash" role="main">
      <section
        className="hero password-splash-hero"
        aria-labelledby="hero-names"
      >
        <HeroTitle />
        <Diamond />
      </section>

      <form className="password-splash-form form" onSubmit={submit} noValidate>
        <div className="row">
          <label
            htmlFor="site-password"
            style={{ fontSize: "larger", textAlign: "center", margin: "auto" }}
          >
            Password:
          </label>
          <input
            id="site-password"
            type="password"
            value={password}
            onChange={(e) => {
              setPassword(e.target.value);
              if (error) setError("");
            }}
            autoComplete="off"
            autoFocus
            disabled={!passwords}
            required
          />
        </div>

        {error ? (
          <p className="password-splash-error" role="alert">
            {error}
          </p>
        ) : null}

        <div className="form-actions">
          <button
            type="submit"
            className="btn"
            disabled={!password.trim() || !passwords || checking}
          >
            Enter →
          </button>
        </div>
      </form>
    </div>
  );
}

window.PasswordGate = PasswordGate;
