'use client';

import { useState } from 'react';
import type { Locale } from '@ai-radar/shared';
import type { Dictionary } from '@/lib/dictionary';

type State = 'idle' | 'sending' | 'sent' | 'error';

/**
 * Email signup is hidden for now; Telegram is the offer.
 *
 * The reason is delivery, not preference. Email needs a verified sending
 * domain and a warmed reputation before a daily digest lands in an inbox
 * rather than spam. Telegram needs a bot token. Until the first is true,
 * offering email would collect addresses we cannot reliably reach.
 *
 * The email path below is intact, not deleted — flipping this constant
 * brings it back, along with the double opt-in flow and preferences page
 * that already exist and still work for anyone subscribed.
 */
const EMAIL_SIGNUP_ENABLED = false;

export function SubscribeForm({
  locale,
  dict,
  compact = false,
  telegramBot = null,
}: {
  locale: Locale;
  dict: Dictionary;
  compact?: boolean;
  /** Bot username. When null the Telegram option is hidden entirely. */
  telegramBot?: string | null;
}) {
  const [email, setEmail] = useState('');
  const [wantsInstant, setWantsInstant] = useState(false);
  const [state, setState] = useState<State>('idle');
  const [error, setError] = useState<string | null>(null);

  // Nothing to offer: no bot configured and email turned off. Render
  // nothing rather than a heading above a dead end.
  if (!EMAIL_SIGNUP_ENABLED && !telegramBot) return null;

  if (!EMAIL_SIGNUP_ENABLED) {
    return <TelegramSignup dict={dict} bot={telegramBot!} compact={compact} />;
  }

  async function submit(event: React.FormEvent) {
    event.preventDefault();
    setState('sending');
    setError(null);

    try {
      const response = await fetch(`${apiBase()}/subscribe`, {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ email, locale, wantsInstant }),
      });

      const body = (await response.json()) as { ok?: boolean; error?: string };

      if (!response.ok || !body.ok) {
        setError(body.error ?? dict.subscribe.failed);
        setState('error');
        return;
      }

      setState('sent');
    } catch {
      setError(dict.subscribe.failed);
      setState('error');
    }
  }

  // Success state replaces the form entirely: leaving an empty field
  // beside "check your inbox" invites a second submission.
  if (state === 'sent') {
    return (
      <div className="subscribe-done">
        <p className="subscribe-done-title">{dict.subscribe.checkInbox}</p>
        <p className="t-body-sm">{dict.subscribe.checkInboxBody}</p>
      </div>
    );
  }

  return (
    <form className={`subscribe ${compact ? 'compact' : ''}`} onSubmit={submit} noValidate>
      {!compact && (
        <>
          <h2 className="subscribe-heading">{dict.subscribe.heading}</h2>
          <p className="subscribe-blurb">{dict.subscribe.blurb}</p>
        </>
      )}

      <div className="subscribe-row">
        <input
          id="subscribe-email"
          type="email"
          className="subscribe-input"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          placeholder={dict.subscribe.placeholder}
          autoComplete="email"
          required
          aria-label={dict.subscribe.heading}
          aria-invalid={state === 'error'}
        />
        <button
          type="submit"
          className="subscribe-btn"
          disabled={state === 'sending' || email.length === 0}
        >
          {state === 'sending' ? dict.subscribe.submitting : dict.subscribe.submit}
        </button>
      </div>

      {!compact && (
        <label className="subscribe-check">
          <input
            id="subscribe-instant"
            type="checkbox"
            checked={wantsInstant}
            onChange={(e) => setWantsInstant(e.target.checked)}
          />
          <span>{dict.subscribe.instantOption}</span>
        </label>
      )}

      {error && <p className="subscribe-error">{error}</p>}

      {telegramBot && (
        <a
          className="subscribe-telegram"
          href={`https://t.me/${telegramBot}`}
          target="_blank"
          rel="noopener noreferrer"
        >
          <TelegramIcon />
          <span>
            {dict.subscribe.telegramOption}
            <span className="subscribe-telegram-note"> {dict.subscribe.telegramNote}</span>
          </span>
        </a>
      )}

      <p className="subscribe-privacy">{dict.subscribe.privacy}</p>
    </form>
  );
}

/**
 * Telegram signup.
 *
 * No form, because there is nothing to collect: opening the bot is the
 * subscription. So the space that a form would have taken goes to the
 * thing that actually makes this worth signing up for — that the reader
 * can narrow it to one topic, one company, or one model.
 *
 * Stated before the click, not after. Someone who only cares about
 * Claude will not subscribe to "everything in AI" to find out they could
 * have filtered it.
 */
function TelegramSignup({
  dict,
  bot,
  compact,
}: {
  dict: Dictionary;
  bot: string;
  compact: boolean;
}) {
  const t = dict.subscribe;

  return (
    <section className={`subscribe subscribe-tg ${compact ? 'compact' : ''}`}>
      {!compact && (
        <>
          <h2 className="subscribe-heading">{t.telegramHeading}</h2>
          <p className="subscribe-blurb">{t.telegramBlurb}</p>
        </>
      )}

      <a
        className="subscribe-tg-btn"
        href={`https://t.me/${bot}`}
        target="_blank"
        rel="noopener noreferrer"
      >
        <TelegramIcon />
        <span>{t.telegramCta}</span>
      </a>

      {!compact && (
        <div className="subscribe-tg-filters">
          <p className="subscribe-tg-filters-intro">{t.telegramFilterIntro}</p>
          <ul className="subscribe-tg-filters-list">
            <li>{t.telegramFilterTopic}</li>
            <li>{t.telegramFilterCompany}</li>
            <li>{t.telegramFilterModel}</li>
          </ul>
          <p className="subscribe-tg-filters-how">{t.telegramFilterHow}</p>
        </div>
      )}
    </section>
  );
}

function TelegramIcon() {
  return (
    <svg width="15" height="15" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
      <path d="M21.9 4.3 18.6 20c-.2 1.1-.9 1.4-1.8.9l-5-3.7-2.4 2.3c-.3.3-.5.5-1 .5l.4-5 9.1-8.2c.4-.4-.1-.6-.6-.2L6 12.1l-4.9-1.5c-1.1-.3-1.1-1 .2-1.5l19.2-7.4c.9-.3 1.7.2 1.4 2.6Z" />
    </svg>
  );
}

/** Browser-reachable API origin. */
function apiBase(): string {
  return (process.env.NEXT_PUBLIC_API_BASE_URL ?? 'http://localhost:4000/api').replace(/\/+$/, '');
}
