// "Request account deletion" form page. Bilingual (EN/ES). Posts the requester
// email to the Supabase `deletion-request` Edge Function, which emails support.

const DELETION_ENDPOINT =
  "https://gqftrzrfiternycvotba.supabase.co/functions/v1/deletion-request";

const RD_COPY = {
  en: {
    eyebrow: "Legal",
    home: "Home",
    title: "Request account deletion",
    intro:
      "Use this form to request deletion of your Lumgoals account and its associated data if you no longer have access to the app. We may verify your identity before completing the request, and we aim to process it within 30 days.",
    emailLabel: "Email of the account you want to delete",
    emailPlaceholder: "you@example.com",
    messageLabel: "Message",
    fixedMessage: "I want to delete my account.",
    submit: "Send request",
    sending: "Sending…",
    successTitle: "Request sent",
    successBody:
      "Thanks. We received your account deletion request and will follow up at the email you provided. We may ask you to confirm from your account address before deleting.",
    errInvalid: "Please enter a valid email address.",
    errGeneric: "Something went wrong. Please try again, or email support@lumgoals.com.",
    note:
      "Prefer email? You can also write to support@lumgoals.com from the address associated with your account.",
  },
  es: {
    eyebrow: "Legal",
    home: "Inicio",
    title: "Solicitar eliminación de cuenta",
    intro:
      "Usa este formulario para solicitar la eliminación de tu cuenta de Lumgoals y los datos asociados si ya no tienes acceso a la app. Es posible que verifiquemos tu identidad antes de completar la solicitud, y buscamos procesarla en un plazo de 30 días.",
    emailLabel: "Correo de la cuenta que quieres eliminar",
    emailPlaceholder: "tu@ejemplo.com",
    messageLabel: "Mensaje",
    fixedMessage: "Quiero eliminar mi cuenta.",
    submit: "Enviar solicitud",
    sending: "Enviando…",
    successTitle: "Solicitud enviada",
    successBody:
      "Gracias. Recibimos tu solicitud de eliminación de cuenta y te contactaremos al correo que indicaste. Es posible que te pidamos confirmar desde el correo de tu cuenta antes de eliminarla.",
    errInvalid: "Introduce un correo electrónico válido.",
    errGeneric: "Algo salió mal. Inténtalo de nuevo o escribe a support@lumgoals.com.",
    note:
      "¿Prefieres correo? También puedes escribir a support@lumgoals.com desde el correo asociado a tu cuenta.",
  },
};

const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

function RequestDeletionPage() {
  const { lang } = useLang();
  const copy = RD_COPY[lang] || RD_COPY.en;

  const [email, setEmail] = React.useState("");
  const [website, setWebsite] = React.useState(""); // honeypot
  const [status, setStatus] = React.useState("idle"); // idle | sending | sent | error
  const [error, setError] = React.useState("");

  const submit = async e => {
    e.preventDefault();
    setError("");
    const value = email.trim().toLowerCase();
    if (!EMAIL_RE.test(value)) {
      setError(copy.errInvalid);
      return;
    }
    setStatus("sending");
    try {
      const res = await fetch(DELETION_ENDPOINT, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email: value, lang, website }),
      });
      if (!res.ok) throw new Error("bad status");
      setStatus("sent");
    } catch (err) {
      setStatus("error");
      setError(copy.errGeneric);
    }
  };

  return (
    <>
      <div className="page-bg"/>
      <Nav/>

      <main className="legal-page">
        <div className="container">
          <nav className="legal-breadcrumb" aria-label="Breadcrumb">
            <a href="/">{copy.home}</a>
            <span className="legal-breadcrumb-sep">/</span>
            <a href="/legal">{copy.eyebrow}</a>
            <span className="legal-breadcrumb-sep">/</span>
            <span className="legal-breadcrumb-current">{copy.title}</span>
          </nav>

          <header className="legal-header">
            <div className="legal-eyebrow">{copy.eyebrow}</div>
            <h1>{copy.title}</h1>
            <p>{copy.intro}</p>
          </header>

          <article className="legal-content" style={{ maxWidth: 640 }}>
            {status === "sent" ? (
              <div className="rd-success">
                <h2>{copy.successTitle}</h2>
                <p className="legal-intro">{copy.successBody}</p>
              </div>
            ) : (
              <form className="rd-form" onSubmit={submit} noValidate>
                <label className="rd-label" htmlFor="rd-email">{copy.emailLabel}</label>
                <input
                  id="rd-email"
                  className="rd-input"
                  type="email"
                  autoComplete="email"
                  placeholder={copy.emailPlaceholder}
                  value={email}
                  onChange={e => setEmail(e.target.value)}
                  required
                />

                <label className="rd-label" htmlFor="rd-message">{copy.messageLabel}</label>
                <textarea
                  id="rd-message"
                  className="rd-input rd-textarea"
                  value={copy.fixedMessage}
                  readOnly
                  aria-readonly="true"
                  rows={2}
                />

                {/* Honeypot: hidden from humans, bots tend to fill it. */}
                <input
                  type="text"
                  name="website"
                  tabIndex={-1}
                  autoComplete="off"
                  value={website}
                  onChange={e => setWebsite(e.target.value)}
                  style={{ position: "absolute", left: "-9999px", width: 1, height: 1, opacity: 0 }}
                  aria-hidden="true"
                />

                {error ? <div className="rd-error">{error}</div> : null}

                <button className="rd-submit" type="submit" disabled={status === "sending"}>
                  {status === "sending" ? copy.sending : copy.submit}
                </button>

                <p className="rd-note">{copy.note}</p>
              </form>
            )}
          </article>
        </div>
      </main>

      <PageFooter/>
    </>
  );
}

function RequestDeletionApp() {
  return (
    <I18nProvider>
      <ThemeProvider>
        <RequestDeletionPage/>
      </ThemeProvider>
    </I18nProvider>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<RequestDeletionApp/>);
