"use client";

/**
 * Opt-out confirmation (task 3.6).
 *
 * Every string here names the event. Suppression is per event by design (D11), so copy
 * saying "you will no longer receive our emails" would be false for anyone invited to a
 * second ceremony — and a guest who later kept receiving mail would reasonably read it as
 * the opt-out being ignored.
 */
import { useState } from "react";

import type { Dictionary } from "@/lib/i18n";

export type UnsubscribeView = {
  token: string;
  guestName: string;
  eventTitle: string;
  alreadyUnsubscribed: boolean;
};

/** The dictionary keeps `{event}` as a literal so the substitution happens once, here. */
function withEvent(template: string, event: string): string {
  return template.replaceAll("{event}", event);
}

export function UnsubscribeConfirm({
  view,
  dict,
}: {
  view: UnsubscribeView;
  dict: Dictionary;
}) {
  const [done, setDone] = useState(view.alreadyUnsubscribed);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);

  if (done) {
    return (
      <section className="rounded-2xl border p-6 text-center" role="status" aria-live="polite">
        <h1 className="text-xl font-semibold">
          {withEvent(dict.unsubscribeDoneTitle, view.eventTitle)}
        </h1>
        <p className="mt-3 text-sm opacity-70">
          {withEvent(dict.unsubscribeScope, view.eventTitle)}
        </p>
        <p className="mt-2 text-sm opacity-70">{dict.unsubscribeKeepsLink}</p>
        <a
          href={`/i/${view.token}`}
          className="mt-5 inline-block min-h-12 rounded-full border px-6 py-3 text-base"
        >
          {dict.backToInvitation}
        </a>
      </section>
    );
  }

  return (
    <section className="rounded-2xl border p-6 text-center">
      <h1 className="text-xl font-semibold">
        {withEvent(dict.unsubscribeTitle, view.eventTitle)}
      </h1>
      <p className="mt-3 text-sm opacity-70">
        {withEvent(dict.unsubscribeScope, view.eventTitle)}
      </p>
      <p className="mt-2 text-sm opacity-70">{dict.unsubscribeKeepsLink}</p>

      {error && (
        <p role="alert" className="mt-3 text-sm text-red-600">
          {error}
        </p>
      )}

      <div className="mt-5 flex flex-col gap-2">
        <button
          disabled={busy}
          onClick={async () => {
            setBusy(true);
            setError(null);
            try {
              // POST with an explicit confirm, so a link scanner fetching the URL cannot
              // opt somebody out — the same rule cancellation follows.
              const response = await fetch(
                `/api/unsubscribe/${encodeURIComponent(view.token)}`,
                {
                  method: "POST",
                  headers: { "content-type": "application/json" },
                  body: JSON.stringify({ confirm: true }),
                },
              );
              if (!response.ok) {
                setError(dict.formError);
                return;
              }
              setDone(true);
            } catch {
              setError(dict.formError);
            } finally {
              setBusy(false);
            }
          }}
          className="min-h-12 rounded-full bg-red-600 px-6 text-base font-medium text-white disabled:opacity-60"
        >
          {busy ? dict.submitting : dict.unsubscribeConfirm}
        </button>
        <a
          href={`/i/${view.token}`}
          className="min-h-12 rounded-full border px-6 py-3 text-base"
        >
          {dict.backToInvitation}
        </a>
      </div>
    </section>
  );
}
