'use client';

import { useEffect, useState } from 'react';
import { saveSessionChoice } from '../session';
import { useToast } from '../../hooks/useToast';
import { triggerTtqEvent } from '../../../lib/tiktok';

type PlanKey = 'yearly' | 'monthly';

const BENEFITS = [
  'Find answers in the Holy Quran',
  "Resolve life's challenges with Allah's teachings",
  'Relax and sleep with soothing Quran content',
];

const PLANS: Array<{
  key: PlanKey;
  name: string;
  oldPrice: string;
  rightPrimary: string;
  rightSelected: string;
  tag?: string;
}> = [
  {
    key: 'yearly',
    name: '1 year',
    oldPrice: '$39.99',
    rightPrimary: '$3.33/month',
    rightSelected: '$3.33/month',
    tag: '52% off',
  },
  {
    key: 'monthly',
    name: '1 month',
    oldPrice: '$6.99',
    rightPrimary: '$6.99/month',
    rightSelected: 'no long-term commitment',
  },
];

const getUtmAd = () => {
  if (typeof window === 'undefined') return undefined;
  return new URLSearchParams(window.location.search).get('utm_ad') ?? undefined;
};

const sendTelegram = async (label: string, utmAd?: string) => {
  try {
    await fetch('/api/telegram/notify', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ label: label.trim().toLowerCase(), utmAd }),
    });
  } catch {}
};

const triggerFb = (...args: unknown[]) => {
  if (typeof window === 'undefined') return;
  const fbq = (window as any).fbq;
  if (typeof fbq === 'function') {
    try { fbq(...args); } catch {}
  }
};

const formatCard = (v: string) =>
  v.replace(/\D/g, '').slice(0, 16).replace(/(.{4})/g, '$1 ').trim();

const formatExpiry = (v: string) => {
  const digits = v.replace(/\D/g, '').slice(0, 4);
  if (digits.length <= 2) return digits;
  return `${digits.slice(0, 2)}/${digits.slice(2)}`;
};

export default function PlansSection() {
  const { showToast } = useToast();
  const [selected, setSelected] = useState<PlanKey>('yearly');
  const [card, setCard] = useState('');
  const [expiry, setExpiry] = useState('');
  const [cvc, setCvc] = useState('');
  const [holder, setHolder] = useState('');
  const [email, setEmail] = useState('');

  useEffect(() => {
    void saveSessionChoice('plans', 'visited');
    triggerFb('trackCustom', 'OnboardingCompleted');
  }, []);

  const handleContinue = () => {
    const utmAd = getUtmAd();
    void sendTelegram(`paywall-${selected}`, utmAd);
    void saveSessionChoice('plans', `continue-${selected}`);
    triggerFb('track', 'InitiateCheckout');

    const addToCartEventId = triggerTtqEvent('AddToCart', {
      content_id: selected,
      content_name: selected,
    });
    fetch('/api/track', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        ttEvents: [
          {
            eventName: 'AddToCart',
            eventId: addToCartEventId,
            contentId: selected,
            contentName: selected,
          },
        ],
      }),
    }).catch(() => {});

    showToast(
      "We're experiencing more demand than expected!\nNew sign-ups are temporarily paused. Please check back soon.",
      5000
    );
  };

  return (
    <main className="paywall-page">
      <div className="paywall-stack">
        <h1 className="paywall-title">
          Discover peace in Allah&apos;s divine guidance
        </h1>

        <div className="paywall-benefits">
          {BENEFITS.map((b) => (
            <div key={b} className="paywall-benefit">{b}</div>
          ))}
        </div>

        <div className="paywall-plans">
          {PLANS.map((p) => {
            const isSelected = selected === p.key;
            return (
              <button
                key={p.key}
                type="button"
                className={`paywall-plan${isSelected ? ' selected' : ''}`}
                onClick={() => setSelected(p.key)}
              >
                <div className="paywall-plan-left">
                  <div className="paywall-plan-name-row">
                    <span className="paywall-plan-name">{p.name}</span>
                    {!isSelected && p.tag && (
                      <span className="paywall-plan-tag">{p.tag}</span>
                    )}
                  </div>
                  {isSelected && (
                    <div className="paywall-plan-subline">
                      <span className="paywall-plan-old">{p.oldPrice}</span>
                      {p.tag && <span className="paywall-plan-tag">{p.tag}</span>}
                    </div>
                  )}
                </div>
                <div className="paywall-plan-right">
                  {isSelected && <span className="paywall-plan-check" aria-hidden />}
                  <span className="paywall-plan-price">
                    {isSelected ? p.rightSelected : p.rightPrimary}
                  </span>
                </div>
              </button>
            );
          })}
        </div>

        <div className="paywall-card-section">
          <div className="paywall-card-label">
            <svg viewBox="0 0 24 24" fill="none" width="22" height="22" aria-hidden>
              <rect x="2.5" y="5" width="19" height="14" rx="2.5" stroke="currentColor" strokeWidth="1.8" />
              <rect x="2.5" y="8.5" width="19" height="2.5" fill="currentColor" />
            </svg>
            <span>Card</span>
          </div>

          <div className="paywall-card-row">
            <input
              className="paywall-input paywall-input-card"
              placeholder="Card number"
              inputMode="numeric"
              autoComplete="cc-number"
              value={card}
              onChange={(e) => setCard(formatCard(e.target.value))}
            />
            <input
              className="paywall-input paywall-input-exp"
              placeholder="MM / YY"
              inputMode="numeric"
              autoComplete="cc-exp"
              value={expiry}
              onChange={(e) => setExpiry(formatExpiry(e.target.value))}
            />
            <input
              className="paywall-input paywall-input-cvc"
              placeholder="CVC"
              inputMode="numeric"
              autoComplete="cc-csc"
              maxLength={4}
              value={cvc}
              onChange={(e) => setCvc(e.target.value.replace(/\D/g, ''))}
            />
          </div>

          <input
            className="paywall-input paywall-input-full"
            placeholder="Cardholder name"
            autoComplete="cc-name"
            value={holder}
            onChange={(e) => setHolder(e.target.value)}
          />

          <input
            className="paywall-input paywall-input-full"
            type="email"
            placeholder="Email"
            autoComplete="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
          />
        </div>

        <button type="button" className="paywall-cta" onClick={handleContinue}>
          Continue
        </button>

        <p className="paywall-guarantee">14-day money-back guarantee</p>

        <p className="paywall-legal">
          By clicking above, you agree to try Ayatique for a special one month
          price of six dollars and ninety-nine cents. After this period, you
          will automatically be charged twenty-four dollars and ninety-nine
          cents every one month unless you cancel it through your account
          settings.{' '}
          <a href="/terms" className="paywall-legal-link">Terms of Use</a> and{' '}
          <a href="/privacy" className="paywall-legal-link">Privacy Policy</a>{' '}
          apply. For more details, contact us at{' '}
          <a href="mailto:support@ayatique.si" className="paywall-legal-link">
            support@ayatique.si
          </a>
        </p>
      </div>
    </main>
  );
}
