'use client';

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

const STAR_PATH = 'M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z';

const pad = (v: number) => v.toString().padStart(2, '0');
const formatTime = (s: number) => `${pad(Math.floor(s / 60))}:${pad(s % 60)}`;

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 {}
  }
};

export default function PlansTemplateSection() {
  const { showToast } = useToast();
  const data = PLANS_DATA;

  const defaultKey = data.plans.find((p) => p.isDefault)?.key ?? data.plans[0]?.key ?? '';
  const [selectedPlan, setSelectedPlan] = useState(defaultKey);
  const [seconds, setSeconds] = useState(Math.max(data.topBanner.initialSeconds, 0));
  const [bannerVisible, setBannerVisible] = useState(data.topBanner.initialSeconds > 0);
  const [openFaq, setOpenFaq] = useState<string | null>(null);

  useEffect(() => {
    if (data.topBanner.initialSeconds <= 0) return;
    const iv = setInterval(() => {
      setSeconds((p) => {
        const n = Math.max(p - 1, 0);
        if (n === 0) { setBannerVisible(false); clearInterval(iv); }
        return n;
      });
    }, 1000);
    return () => clearInterval(iv);
  }, [data.topBanner.initialSeconds]);

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

  const timer = useMemo(() => formatTime(seconds), [seconds]);
  const offerText = data.topBanner.offerTemplate.replace('{time}', timer);

  const handleCta = (label: string) => {
    const utmAd = getUtmAd();
    void sendTelegram(label, utmAd);
    void saveSessionChoice('plans-template', label.trim());
    triggerFb('track', 'InitiateCheckout');

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

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

  return (
    <main className="plans-page">
      {bannerVisible && (
        <div className="plans-banner">
          <div className="plans-banner-text">
            <span className="plans-banner-label">{data.topBanner.label}</span>
            <span className="plans-banner-timer">{timer}</span>
          </div>
          <button type="button" className="plans-banner-cta" onClick={() => handleCta(data.topBanner.cta)}>
            {data.topBanner.cta}
          </button>
        </div>
      )}

      <div className="plans-stack">
        <h1 className="plans-heading">
          {data.heading.pre} <span className="gold">{data.heading.highlight}</span> {data.heading.post}
        </h1>

        <div className="plans-cards">
          {data.plans.map((plan) => (
            <button
              key={plan.key}
              type="button"
              className={`plan-card${selectedPlan === plan.key ? ' featured' : ''}`}
              onClick={() => setSelectedPlan(plan.key)}
            >
              {plan.tag && <div className="plan-tag">{plan.tag}</div>}
              <div className="plan-body">
                <div className="plan-left">
                  <span className="plan-radio" />
                  <div>
                    <p className="plan-name">{plan.name}</p>
                    <div className="plan-prices">
                      {plan.oldPrice && <span className="plan-old-price">{plan.oldPrice}</span>}
                      <span className="plan-current-price">{plan.currentPrice}</span>
                    </div>
                  </div>
                </div>
                <div className="plan-right">
                  <p className="plan-daily">{plan.dailyPrice}</p>
                  <p className="plan-per-day">{plan.perDay}</p>
                </div>
              </div>
              {plan.showOfferBar && bannerVisible && seconds > 0 && (
                <div className="plan-offer-bar">{offerText}</div>
              )}
            </button>
          ))}
        </div>

        <button type="button" className="cta-gold plans-continue-cta" onClick={() => handleCta(data.cta)}>
          {data.cta}
        </button>

        <p className="plans-footer-note">
          {data.footerNote1}<br /><strong>{data.footerNote2}</strong>
        </p>

        <div className="plans-reviews">
          <h2>{data.reviews.heading}</h2>
          <div className="plans-review-grid">
            {data.reviews.cards.map((card) => (
              <div key={card.author} className="plans-review-card">
                <div className="plans-review-stars">
                  {[...Array(card.stars)].map((_, i) => (
                    <svg key={i} viewBox="0 0 24 24"><path d={STAR_PATH} fill="#FACC15" /></svg>
                  ))}
                </div>
                <p className="plans-review-quote">{card.quote}</p>
                <p className="plans-review-author">{card.author}</p>
              </div>
            ))}
          </div>
          <div className="plans-platform-grid">
            {data.reviews.platforms.map((p) => (
              <div key={p.name} className="plans-platform-card">
                <p className="plans-platform-rating">{p.rating}</p>
                <div className="plans-platform-stars">
                  {[...Array(4)].map((_, i) => (
                    <svg key={i} viewBox="0 0 24 24"><path d={STAR_PATH} fill="#FACC15" /></svg>
                  ))}
                  <svg viewBox="0 0 24 24">
                    <defs><linearGradient id={`half-${p.name}`}><stop offset="50%" stopColor="#FACC15" /><stop offset="50%" stopColor="#555" /></linearGradient></defs>
                    <path d={STAR_PATH} fill={`url(#half-${p.name})`} />
                  </svg>
                </div>
                <p className="plans-platform-reviews">{p.reviews}</p>
              </div>
            ))}
          </div>
        </div>

        <div className="plans-advantages">
          {data.advantages.map((a) => (
            <div key={a.title} className="plans-advantage-item">
              <span className="plans-advantage-check" />
              <div>
                <p className="plans-advantage-title">{a.title}</p>
                <p className="plans-advantage-desc">{a.description}</p>
              </div>
            </div>
          ))}
        </div>

        <div className="plans-guarantee">
          <h2>{data.guarantee.heading}</h2>
          <p>{data.guarantee.description}</p>
        </div>

        <div className="plans-faq">
          <h2 className="plans-faq-heading">{data.faq.heading}</h2>
          {data.faq.cards.map((card) => {
            const isOpen = openFaq === card.id;
            return (
              <div key={card.id} className={`plans-faq-card${isOpen ? ' open' : ''}`}>
                <div className="plans-faq-q" onClick={() => setOpenFaq(isOpen ? null : card.id)}>
                  <span>{card.question}</span>
                  <button type="button" className={`plans-faq-chevron${isOpen ? ' open' : ''}`} />
                </div>
                <div className="plans-faq-answer">{card.answer}</div>
              </div>
            );
          })}
        </div>

        <div className="plans-cards">
          {data.plans.map((plan) => (
            <button
              key={`bottom-${plan.key}`}
              type="button"
              className={`plan-card${selectedPlan === plan.key ? ' featured' : ''}`}
              onClick={() => setSelectedPlan(plan.key)}
            >
              {plan.tag && <div className="plan-tag">{plan.tag}</div>}
              <div className="plan-body">
                <div className="plan-left">
                  <span className="plan-radio" />
                  <div>
                    <p className="plan-name">{plan.name}</p>
                    <div className="plan-prices">
                      {plan.oldPrice && <span className="plan-old-price">{plan.oldPrice}</span>}
                      <span className="plan-current-price">{plan.currentPrice}</span>
                    </div>
                  </div>
                </div>
                <div className="plan-right">
                  <p className="plan-daily">{plan.dailyPrice}</p>
                  <p className="plan-per-day">{plan.perDay}</p>
                </div>
              </div>
            </button>
          ))}
        </div>

        <button type="button" className="cta-gold plans-continue-cta" onClick={() => handleCta(data.cta)}>
          CONTINUE
        </button>

        <p className="plans-footer-note">
          {data.footerNote1}<br /><strong>{data.footerNote2}</strong>
        </p>
      </div>
    </main>
  );
}
