// Pricing — subscriptions + one-off packages, trial state, pricing modal.
// The heart of the commerce flow. Clean, trustworthy, premium.

const SUBSCRIPTION_PLANS = [
  {
    id: 'basic',
    name: 'Basic',
    leadsPerMonth: 100,
    priceMonthly: 190,
    trialLeads: 25,
    taglineKey: 'price.plan.basic.tag',
    featureKeys: [
      'price.plan.basic.f1',
      'price.plan.basic.f2',
      'price.plan.basic.f3',
      'price.plan.basic.f4',
      'price.plan.basic.f5',
    ],
  },
  {
    id: 'starter',
    name: 'Starter',
    leadsPerMonth: 250,
    priceMonthly: 290,
    trialLeads: 50,
    taglineKey: 'price.plan.starter.tag',
    recommended: true,
    featureKeys: [
      'price.plan.starter.f1',
      'price.plan.starter.f2',
      'price.plan.starter.f3',
      'price.plan.starter.f4',
      'price.plan.starter.f5',
      'price.plan.starter.f6',
    ],
  },
  {
    id: 'growth',
    name: 'Growth',
    leadsPerMonth: 500,
    priceMonthly: 490,
    trialLeads: 100,
    taglineKey: 'price.plan.growth.tag',
    featureKeys: [
      'price.plan.growth.f1',
      'price.plan.growth.f2',
      'price.plan.growth.f3',
      'price.plan.growth.f4',
      'price.plan.growth.f5',
      'price.plan.growth.f6',
    ],
  },
];

const ONEOFF_PACKAGES = [
  { id: 'oneoff-1000',  leads: 1000,  price: 790,    taglineKey: 'price.pack.1000.tag' },
  { id: 'oneoff-5000',  leads: 5000,  price: 3490,   taglineKey: 'price.pack.5000.tag' },
  { id: 'oneoff-10000', leads: 10000, price: 5490,   taglineKey: 'price.pack.10000.tag', popular: true },
  { id: 'oneoff-50000', leads: 50000, price: 18990,  taglineKey: 'price.pack.50000.tag' },
];

function formatEUR(n) {
  const locale = (window.LangStore && window.LangStore.get() === 'en') ? 'en-US' : 'de-DE';
  return new Intl.NumberFormat(locale).format(n) + ' €';
}

function formatLeads(n) {
  const locale = (window.LangStore && window.LangStore.get() === 'en') ? 'en-US' : 'de-DE';
  return new Intl.NumberFormat(locale).format(n);
}

// --- Pricing modal ------------------------------------------------------
function PricingModal({ open, onClose, accountStatus, onSubscribe, onBuyPackage, initialMode }) {
  useLang();
  const isTrial = accountStatus === 'trial';
  // If trial → default to subscriptions; if subscribed → default to one-off
  const [mode, setMode] = useState(initialMode || (isTrial ? 'sub' : 'oneoff'));
  const [selectedSub, setSelectedSub] = useState('starter');
  const [selectedPack, setSelectedPack] = useState('oneoff-10000');

  useEffect(() => {
    if (open) setMode(initialMode || (isTrial ? 'sub' : 'oneoff'));
  }, [open, initialMode, isTrial]);

  if (!open) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-6 fade-in"
         style={{ background: 'rgba(11,15,25,0.55)' }}
         onClick={onClose}>
      <div onClick={e => e.stopPropagation()}
           className="bg-white rounded-2xl shadow-2xl w-full max-w-[1060px] max-h-[92vh] overflow-hidden flex flex-col">
        {/* Header */}
        <div className="px-8 pt-7 pb-5 border-b border-line relative">
          <button onClick={onClose}
                  className="absolute top-5 right-5 w-9 h-9 rounded-lg text-ink-soft hover:bg-gray-100 hover:text-ink inline-flex items-center justify-center transition-colors">
            <Icon.X size={18}/>
          </button>
          <div className="max-w-[640px]">
            <h2 className="text-[26px] font-semibold text-ink tracking-tight leading-tight">
              {isTrial ? t('price.heroTrial') : t('price.heroSub')}
            </h2>
            <p className="text-[14px] text-ink-muted mt-2 leading-snug">
              {isTrial ? t('price.subTrialDesc') : t('price.subOneoffDesc')}
            </p>
          </div>

          {/* Mode toggle */}
          <div className="mt-5 inline-flex items-center rounded-full bg-[#F4F7FD] p-1 border border-line">
            <button onClick={() => setMode('sub')}
                    className={`inline-flex items-center gap-1.5 px-4 h-[34px] rounded-full text-[13px] font-medium transition-all ${
                      mode === 'sub' ? 'bg-white text-ink shadow-sm' : 'text-ink-soft hover:text-ink-muted'
                    }`}>
              <RefreshIcon size={13}/> {t('price.tab.sub')}
            </button>
            <button onClick={() => setMode('oneoff')}
                    disabled={isTrial}
                    title={isTrial ? t('price.tab.lockNote') : ''}
                    className={`inline-flex items-center gap-1.5 px-4 h-[34px] rounded-full text-[13px] font-medium transition-all ${
                      mode === 'oneoff' ? 'bg-white text-ink shadow-sm' : 'text-ink-soft hover:text-ink-muted'
                    } ${isTrial ? 'opacity-50 cursor-not-allowed' : ''}`}>
              <BoltIcon size={13}/> {t('price.tab.oneoff')}
              {isTrial && <span className="text-[10.5px] text-ink-soft ml-1">{t('price.tab.afterSub')}</span>}
            </button>
          </div>
        </div>

        {/* Body */}
        <div className="flex-1 overflow-y-auto px-8 py-7">
          {mode === 'sub' ? (
            <SubscriptionCards
              plans={SUBSCRIPTION_PLANS}
              selected={selectedSub}
              onSelect={setSelectedSub}
              isTrial={isTrial}
              currentStatus={accountStatus}
            />
          ) : (
            <OneOffCards
              packs={ONEOFF_PACKAGES}
              selected={selectedPack}
              onSelect={setSelectedPack}
            />
          )}

          {/* Trust row */}
          <div className="mt-7 pt-5 border-t border-line grid grid-cols-3 gap-5">
            <TrustItem
              icon={<ShieldCheckIcon/>}
              title={t('price.trust.refund.t')}
              sub={t('price.trust.refund.s')}
            />
            <TrustItem
              icon={<LockClosedIcon/>}
              title={t('price.trust.gdpr.t')}
              sub={t('price.trust.gdpr.s')}
            />
            <TrustItem
              icon={<CrossIcon/>}
              title={t('price.trust.cancel.t')}
              sub={t('price.trust.cancel.s')}
            />
          </div>
        </div>

        {/* Footer CTA */}
        <div className="px-8 py-5 border-t border-line bg-[#FAFBFD] flex items-center justify-between">
          <div className="text-[12.5px] text-ink-muted">
            {mode === 'sub' ? (
              <>{t('price.selected')} <span className="font-semibold text-ink">{SUBSCRIPTION_PLANS.find(p => p.id === selectedSub).name}</span>
                {isTrial ? (
                  <>
                    <span className="mx-1.5 text-ink-soft">·</span>
                    <span className="text-emerald-700 font-medium">
                      {t('price.trial3days')} · {SUBSCRIPTION_PLANS.find(p => p.id === selectedSub).trialLeads} {t('price.testLeads')}
                    </span>
                    <span className="mx-1.5 text-ink-soft">·</span>
                    <span className="text-ink-soft">{t('price.then')} {formatEUR(SUBSCRIPTION_PLANS.find(p => p.id === selectedSub).priceMonthly)}{t('price.perMonth')}</span>
                  </>
                ) : (
                  <>
                    <span className="mx-1.5 text-ink-soft">·</span>
                    <span className="text-ink">{formatEUR(SUBSCRIPTION_PLANS.find(p => p.id === selectedSub).priceMonthly)}{t('price.perMonth')}</span>
                  </>
                )}
              </>
            ) : (
              <>{t('price.selected')} <span className="font-semibold text-ink">{formatLeads(ONEOFF_PACKAGES.find(p => p.id === selectedPack).leads)} {t('price.leads')}</span>
                <span className="mx-1.5 text-ink-soft">·</span>
                <span className="text-ink">{formatEUR(ONEOFF_PACKAGES.find(p => p.id === selectedPack).price)} {t('price.oneTime')}</span>
              </>
            )}
          </div>
          <button
            onClick={() => {
              if (mode === 'sub') onSubscribe(selectedSub);
              else onBuyPackage(selectedPack);
            }}
            className="inline-flex items-center gap-2 px-6 h-[42px] rounded-md text-[13.5px] font-semibold text-white transition-all hover:scale-[1.02]"
            style={{ background: 'linear-gradient(107.45deg, #1479FC 18.94%, #B880FC 123.42%)' }}>
            {mode === 'sub'
              ? (isTrial ? t('price.ctaStartTrial') : t('price.ctaSwitchPlan'))
              : t('price.ctaTopUp')}
            <Icon.ArrowRight size={14}/>
          </button>
        </div>
      </div>
    </div>
  );
}

// --- Subscription cards ------------------------------------------------
function SubscriptionCards({ plans, selected, onSelect, isTrial, currentStatus }) {
  useLang();
  return (
    <div className="grid grid-cols-3 gap-4">
      {plans.map(plan => {
        const sel = plan.id === selected;
        const isCurrent = !isTrial && plan.id === currentStatus;
        return (
          <div key={plan.id}
               onClick={() => onSelect(plan.id)}
               className={`relative rounded-xl border-2 p-5 cursor-pointer transition-all flex flex-col ${
                 sel ? 'border-[#3465E3] bg-[#F4F7FD]/60' : 'border-line bg-white hover:border-[#C5D2EC]'
               } ${isCurrent ? 'ring-1 ring-emerald-300' : ''}`}>
            {/* Badges */}
            <div className="absolute -top-2.5 left-5 flex items-center gap-1.5">
              {plan.recommended && !isCurrent && (
                <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10.5px] font-semibold text-white"
                      style={{ background: 'linear-gradient(107.45deg, #1479FC 18.94%, #B880FC 123.42%)' }}>
                  <span className="w-1 h-1 rounded-full bg-white/80"/> Empfohlen
                </span>
              )}
              {isCurrent && (
                <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10.5px] font-semibold bg-emerald-600 text-white">
                  <Icon.Check size={9}/> Dein Plan
                </span>
              )}
            </div>

            {/* Radio */}
            <div className="absolute top-5 right-5">
              <div className={`w-5 h-5 rounded-full border-2 flex items-center justify-center ${
                sel ? 'border-[#3465E3] bg-[#3465E3]' : 'border-[#D5DDEA] bg-white'
              }`}>
                {sel && <div className="w-1.5 h-1.5 rounded-full bg-white"/>}
              </div>
            </div>

            {/* Plan name + tagline */}
            <div className="pr-8">
              <div className="text-[18px] font-semibold text-ink tracking-tight">{plan.name}</div>
              <div className="text-[12px] text-ink-muted mt-0.5 leading-snug">{t(plan.taglineKey)}</div>
            </div>

            {/* Price */}
            <div className="mt-4 flex items-baseline gap-1">
              <span className="text-[30px] font-bold text-ink tracking-tight tabular-nums">{plan.priceMonthly}€</span>
              <span className="text-[13px] text-ink-muted">{t('price.perMonthLong')}</span>
            </div>
            <div className="text-[12px] text-ink-muted mt-0.5">{t('price.monthlyCancelable')}</div>

            {/* Trial highlight */}
            {isTrial && (
              <div className="mt-3.5 rounded-md bg-emerald-50 border border-emerald-200 overflow-hidden">
                <div className="flex items-center gap-2 px-3 py-2">
                  <GiftIcon className="text-emerald-700 flex-shrink-0"/>
                  <div className="text-[12.5px] text-emerald-800 leading-snug">
                    <span className="font-semibold">{t('price.trial3days')}</span>
                    <span className="text-emerald-700/80"> · {t('price.trialIncl')} </span>
                    <span className="font-semibold">{plan.trialLeads} {t('price.testLeads')}</span>
                  </div>
                </div>
                <div className="px-3 pb-2 text-[11px] text-emerald-800/70 leading-snug">
                  {t('price.afterThen', { price: formatEUR(plan.priceMonthly) })}
                </div>
              </div>
            )}

            {/* Features */}
            <ul className="mt-4 space-y-2 flex-1">
              {plan.featureKeys.map((fk, i) => (
                <li key={i} className="flex items-start gap-2 text-[12.5px] text-ink-muted leading-snug">
                  <Icon.Check size={12} className="text-emerald-600 mt-0.5 flex-shrink-0"/>
                  <span>{t(fk)}</span>
                </li>
              ))}
            </ul>
          </div>
        );
      })}
    </div>
  );
}

// --- One-off package cards ---------------------------------------------
function OneOffCards({ packs, selected, onSelect }) {
  useLang();
  return (
    <div className="grid grid-cols-4 gap-4">
      {packs.map(pack => {
        const sel = pack.id === selected;
        const pricePerLead = (pack.price / pack.leads).toFixed(2).replace('.', ',');
        return (
          <div key={pack.id}
               onClick={() => onSelect(pack.id)}
               className={`relative rounded-xl border-2 p-5 cursor-pointer transition-all ${
                 sel ? 'border-[#3465E3] bg-[#F4F7FD]/60' : 'border-line bg-white hover:border-[#C5D2EC]'
               }`}>
            {pack.popular && (
              <span className="absolute -top-2.5 left-5 inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10.5px] font-semibold text-white"
                    style={{ background: 'linear-gradient(107.45deg, #1479FC 18.94%, #B880FC 123.42%)' }}>
                <BoltIcon size={9}/> {t('price.badge.popular')}
              </span>
            )}
            <div className="absolute top-5 right-5">
              <div className={`w-5 h-5 rounded-full border-2 flex items-center justify-center ${
                sel ? 'border-[#3465E3] bg-[#3465E3]' : 'border-[#D5DDEA] bg-white'
              }`}>
                {sel && <div className="w-1.5 h-1.5 rounded-full bg-white"/>}
              </div>
            </div>

            <div className="flex items-baseline gap-2 pr-8">
              <span className="text-[22px] font-semibold text-ink tracking-tight tabular-nums">
                {formatLeads(pack.leads)}
              </span>
              <span className="text-[13px] text-ink-muted">{t('price.leads')}</span>
            </div>
            <div className="text-[12.5px] text-ink-muted mt-0.5">{t(pack.taglineKey)}</div>

            <div className="mt-4 flex items-baseline justify-between">
              <div>
                <span className="text-[22px] font-bold text-ink tracking-tight tabular-nums">
                  {formatEUR(pack.price)}
                </span>
                <span className="text-[12px] text-ink-muted ml-1">{t('price.oneTime')}</span>
              </div>
              <div className="text-[11px] text-ink-soft tabular-nums">
                {pricePerLead} {t('price.perLead')}
              </div>
            </div>
          </div>
        );
      })}
    </div>
  );
}

// --- Trust row items ----------------------------------------------------
function TrustItem({ icon, title, sub }) {
  return (
    <div className="flex items-start gap-2.5">
      <div className="w-8 h-8 rounded-md bg-[#F4F7FD] flex items-center justify-center flex-shrink-0 text-[#3465E3]">
        {icon}
      </div>
      <div>
        <div className="text-[13px] font-semibold text-ink leading-tight">{title}</div>
        <div className="text-[11.5px] text-ink-muted mt-0.5 leading-snug">{sub}</div>
      </div>
    </div>
  );
}

// --- Trial banner (shown above the whole app when in trial) ------------
function TrialBanner({ daysLeft, creditsLeft, creditsTotal, planName, onUpgrade }) {
  useLang();
  const pct = Math.max(0, Math.min(100, (creditsLeft / creditsTotal) * 100));
  const dayText = daysLeft === 1 ? t('trial.day1') : t('trial.daysN', { n: daysLeft });
  return (
    <div className="relative overflow-hidden"
         style={{ background: 'linear-gradient(107deg, #0B0F19 0%, #1B2240 50%, #2D1F56 100%)' }}>
      <div className="max-w-[1440px] mx-auto px-6 py-2.5 flex items-center gap-4">
        <span className="inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full bg-white/10 text-white text-[10.5px] font-semibold uppercase tracking-[0.08em]">
          <SparkleIcon size={10}/> {t('trial.phase')}
        </span>
        <div className="text-[12.5px] text-white/90 flex-1 min-w-0">
          <span className="font-medium text-white">{dayText} {t('trial.freeTest')}</span>
          <span className="text-white/70 ml-1.5 hidden md:inline">
            {t('trial.afterNote', { plan: planName })}
          </span>
        </div>
        <div className="hidden md:flex items-center gap-2 text-[11.5px] text-white/70">
          <span className="tabular-nums">{t('trial.leadsLeft', { left: creditsLeft, total: creditsTotal })}</span>
          <div className="w-20 h-1 rounded-full bg-white/15 overflow-hidden">
            <div className="h-full bg-gradient-to-r from-[#7FA3FF] to-[#C7A5FF]" style={{ width: `${pct}%` }}/>
          </div>
        </div>
        <button onClick={onUpgrade}
                className="inline-flex items-center gap-1.5 px-3.5 h-[28px] rounded-md text-[12px] font-semibold text-ink bg-white hover:bg-white/95 transition-colors">
          {t('trial.secureSub')} <Icon.ArrowRight size={11}/>
        </button>
      </div>
    </div>
  );
}

// --- Icons --------------------------------------------------------------
function RefreshIcon({ size = 14, className = '' }) {
  return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className={className}><polyline points="23 4 23 10 17 10"/><polyline points="1 20 1 14 7 14"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></svg>;
}
function BoltIcon({ size = 14, className = '' }) {
  return <svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor" className={className}><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>;
}
function SparkleIcon({ size = 12, className = '' }) {
  return <svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor" className={className}><path d="M12 2L14 10L22 12L14 14L12 22L10 14L2 12L10 10L12 2Z"/></svg>;
}
function ShieldCheckIcon({ size = 16 }) {
  return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/><path d="M9 12l2 2 4-4"/></svg>;
}
function LockClosedIcon({ size = 16 }) {
  return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>;
}
function CrossIcon({ size = 16 }) {
  return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><path d="M8 12l3 3 5-6"/></svg>;
}
function GiftIcon({ size = 14, className = '' }) {
  return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className={className}><polyline points="20 12 20 22 4 22 4 12"/><rect x="2" y="7" width="20" height="5"/><line x1="12" y1="22" x2="12" y2="7"/><path d="M12 7H7.5a2.5 2.5 0 0 1 0-5C11 2 12 7 12 7z"/><path d="M12 7h4.5a2.5 2.5 0 0 0 0-5C13 2 12 7 12 7z"/></svg>;
}

Object.assign(window, {
  SUBSCRIPTION_PLANS, ONEOFF_PACKAGES, PricingModal, TrialBanner, formatEUR,
});
