/*
 * F-C1 수신거부(해지) 랜딩 — 메일 링크 GET 호환. token 을 읽어 마운트 시 해지 처리(멱등).
 * 백엔드: POST/GET /api/public/subscriptions/unsubscribe?token= (프론트는 멱등 POST 사용).
 * Nifty 문자 그대로: kxp-subcard/kxp-subresult + kx 토큰(publicExtras.css). 하드코딩 0.
 */
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Link, useSearchParams } from 'react-router-dom';
import { PublicShell } from './PublicShell';
import { publicApi, type UnsubscribeResult } from './publicApi';
import { errorMessage } from './publicFormat';
import { IconCheckCircle } from './publicIcons';
import './publicExtras.css';

export function PublicUnsubscribePage() {
  const { t } = useTranslation();
  const [params] = useSearchParams();
  const token = params.get('token') ?? '';
  const [loading, setLoading] = useState(true);
  const [result, setResult] = useState<UnsubscribeResult | null>(null);
  const [error, setError] = useState('');

  useEffect(() => {
    let alive = true;
    if (!token) {
      setLoading(false);
      // i18n 신규: subscribe.unsub.noToken
      setError('유효하지 않은 수신거부 링크입니다.');
      return;
    }
    setLoading(true);
    publicApi
      .unsubscribe(token)
      .then((r) => alive && (setResult(r), setError('')))
      .catch((e) => alive && setError(errorMessage(e)))
      .finally(() => alive && setLoading(false));
    return () => {
      alive = false;
    };
  }, [token]);

  const ok = result?.ok === true;

  return (
    <PublicShell active="events" search={false}>
      <section className="kxp-section" aria-label={t('subscribe.unsub.title', { defaultValue: '수신거부' })}>
        <div className="kxp-wrap" style={{ maxWidth: '40rem' }}>
          <div className="kxp-section__head">
            <div>
              {/* i18n 신규: subscribe.unsub.title */}
              <h1 className="kxp-section__title">오픈 알림 수신거부</h1>
            </div>
          </div>

          <div className="kxp-subcard">
            {loading ? (
              <p className="kxp-empty" role="status">
                {t('home.loading', { defaultValue: '처리 중…' })}
              </p>
            ) : (
              <div
                className={`kxp-subresult ${ok ? 'kxp-subresult--ok' : 'kxp-subresult--warn'}`}
                role="status"
              >
                <span className="kxp-subresult__ic" aria-hidden>
                  <IconCheckCircle width={22} height={22} />
                </span>
                <div>
                  <span className="kxp-subresult__strong">
                    {result?.message ?? (error || '요청을 처리하지 못했습니다.')}
                  </span>
                </div>
              </div>
            )}

            <div style={{ marginTop: 'var(--space-4)' }}>
              <Link className="kxp-btn kxp-btn--outline" to="/public/events">
                {/* i18n 신규: subscribe.unsub.browse */}
                행사 둘러보기
              </Link>
            </div>
          </div>
        </div>
      </section>
    </PublicShell>
  );
}
