'use client';

import { useState, useTransition } from 'react';
import { subscribeToNewsletter } from '@/app/actions';
import Turnstile from './Turnstile';

export default function NewsletterForm() {
  const [email, setEmail] = useState('');
  const [result, setResult] = useState<{ ok: boolean; message: string } | null>(null);
  const [isPending, startTransition] = useTransition();

  return (
    <div className="mt-3 max-w-xs">
      <form
        onSubmit={(e) => {
          e.preventDefault();
          const token = String(new FormData(e.currentTarget).get('cf-turnstile-response') ?? '');
          startTransition(async () => {
            const res = await subscribeToNewsletter(email, token);
            setResult(res);
            if (res.ok) setEmail('');
          });
        }}
        className="flex flex-col gap-2"
      >
        <div className="flex gap-2">
          <input
            type="email"
            required
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            placeholder="you@example.com"
            aria-label="Email address"
            className="w-full min-w-0 border border-line bg-paper px-3 py-2 text-sm"
          />
          <button
            type="submit"
            disabled={isPending}
            className="shrink-0 bg-clay px-4 py-2 text-sm font-medium text-paper hover:bg-clay-dark disabled:opacity-60"
          >
            {isPending ? '…' : 'Sign up'}
          </button>
        </div>
        <Turnstile />
      </form>
      {result && (
        <p role="status" className={`mt-2 text-xs ${result.ok ? 'text-splash-blue' : 'text-splash-pink'}`}>
          {result.message}
        </p>
      )}
    </div>
  );
}
