// Account screen — Profil + Abrechnung tabs
// Clean, cohesive design using the existing Leadscraper visual language

function ScreenAccount({ onBack, toast, accountStatus, currentPlan, trialDaysLeft, trialCreditsLeft, trialCreditsTotal, onOpenPricing }) {
  useLang();
  const [subtab, setSubtab] = useState('profile'); // profile · billing · integrations

  return (
    <div className="max-w-[1080px] mx-auto px-6 py-8">
      {/* Header */}
      <div className="mb-6">
        <h1 className="text-[28px] font-semibold text-ink tracking-tight leading-tight">{t('acct.title')}</h1>
        <p className="text-[13.5px] text-ink-muted mt-1 max-w-[620px] leading-snug">{t('acct.sub')}</p>
      </div>

      {/* Sub-tabs */}
      <div className="border-b border-line flex items-center gap-1">
        <AcctTab id="profile" active={subtab==='profile'} onClick={() => setSubtab('profile')}
                 icon={<Icon.User size={13}/>} label={t('acct.tab.profile')}/>
        <AcctTab id="billing" active={subtab==='billing'} onClick={() => setSubtab('billing')}
                 icon={<CardIcon size={13}/>} label={t('acct.tab.billing')}/>
        <AcctTab id="integrations" active={subtab==='integrations'} onClick={() => setSubtab('integrations')}
                 icon={<PlugIcon size={13}/>} label={t('acct.tab.integrations')}/>
      </div>

      {/* Body */}
      <div className="mt-6 space-y-6">
        {subtab === 'profile' && <ProfilePanel/>}
        {subtab === 'billing' && <BillingPanel
          accountStatus={accountStatus}
          currentPlan={currentPlan}
          trialDaysLeft={trialDaysLeft}
          trialCreditsLeft={trialCreditsLeft}
          trialCreditsTotal={trialCreditsTotal}
          onOpenPricing={onOpenPricing}
        />}
        {subtab === 'integrations' && <IntegrationsPanel toast={toast}/>}
      </div>
    </div>
  );
}

function PlugIcon({ 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}><path d="M9 2v6"/><path d="M15 2v6"/><path d="M6 8h12v4a6 6 0 0 1-12 0V8z"/><path d="M12 18v4"/></svg>;
}

function AcctTab({ active, onClick, icon, label }) {
  return (
    <button onClick={onClick}
      className={`relative inline-flex items-center gap-1.5 px-3 py-2.5 text-[13px] font-medium transition-colors ${
        active ? 'text-[#3465E3]' : 'text-ink-muted hover:text-ink'
      }`}>
      <span className={active ? 'text-[#3465E3]' : 'text-ink-soft'}>{icon}</span>
      {label}
      {active && <span className="absolute left-0 right-0 -bottom-px h-[2px] bg-[#3465E3] rounded-full"/>}
    </button>
  );
}

// --- Profile Panel --------------------------------------------------------

function ProfilePanel() {
  useLang();
  const [firstName, setFirstName] = useState('Janik');
  const [lastName, setLastName] = useState('Deimann');
  const [email, setEmail] = useState('janik.dmann@gmail.com');
  const [language, setLanguage] = useState('Deutsch');
  const [dirty, setDirty] = useState(false);
  const [twoFa, setTwoFa] = useState(false);

  const onChange = (setter) => (v) => { setter(v); setDirty(true); };

  return (
    <>
      {/* Profil Information */}
      <Card>
        <CardHeader
          title={t('acct.prof.title')}
          action={
            <button
              disabled={!dirty}
              onClick={() => setDirty(false)}
              className={`px-4 h-[34px] rounded-md text-[12.5px] font-medium text-white transition-all ${
                dirty ? 'hover:scale-[1.02]' : 'opacity-60 cursor-not-allowed'
              }`}
              style={{background: dirty
                ? 'linear-gradient(107.45deg, #1479FC 18.94%, #B880FC 123.42%)'
                : '#9CA3AF'}}>
              {t('acct.prof.save')}
            </button>
          }/>

        <div className="px-6 py-5">
          {/* Avatar row */}
          <div className="flex items-center gap-4 mb-6">
            <div className="relative">
              <div className="w-[68px] h-[68px] rounded-full flex items-center justify-center text-[22px] font-semibold text-white"
                   style={{background:'linear-gradient(135deg, #3465E3 0%, #6D4FE6 55%, #8B5CF6 100%)'}}>
                JD
              </div>
              <div className="absolute -bottom-0.5 -right-0.5 w-5 h-5 rounded-full bg-white flex items-center justify-center border border-line">
                <div className="w-2 h-2 rounded-full bg-emerald-500"/>
              </div>
            </div>
            <div className="flex-1">
              <button className="inline-flex items-center gap-2 px-3.5 py-2 rounded-md text-[12.5px] font-medium text-white transition-transform hover:scale-[1.02]"
                      style={{background:'linear-gradient(107.45deg, #1479FC 18.94%, #B880FC 123.42%)'}}>
                <CameraIcon size={13}/> {t('acct.prof.upload')}
              </button>
              <div className="text-[11.5px] text-ink-soft mt-1.5">{t('acct.prof.uploadHint')}</div>
            </div>
          </div>

          {/* Form grid */}
          <div className="grid grid-cols-2 gap-4">
            <Field label={t('acct.prof.first')} value={firstName} onChange={onChange(setFirstName)}/>
            <Field label={t('acct.prof.last')} value={lastName} onChange={onChange(setLastName)}/>
            <Field label={t('acct.prof.email')} value={email} onChange={onChange(setEmail)} type="email"/>
            <Field label={t('acct.prof.lang')} value={language} onChange={onChange(setLanguage)} select
                   options={['Deutsch', 'English']}/>
          </div>
        </div>
      </Card>

      {/* Security */}
      <Card>
        <CardHeader title={t('acct.sec.title')}/>

        <div className="divide-y divide-[#F0F4FA]">
          {/* Password row */}
          <div className="px-6 py-4 flex items-center justify-between">
            <div className="flex items-start gap-3">
              <div className="w-8 h-8 rounded-md bg-[#F4F7FD] flex items-center justify-center flex-shrink-0">
                <LockIcon size={14} className="text-[#3465E3]"/>
              </div>
              <div>
                <div className="text-[13.5px] font-medium text-ink">{t('acct.sec.pw')}</div>
                <div className="text-[12px] text-ink-muted mt-0.5">{t('acct.sec.pwSub')}</div>
              </div>
            </div>
            <button className="px-4 h-[32px] rounded-md text-[12.5px] font-medium text-[#3465E3] border border-[#3465E3] hover:bg-[#EEF2FE] transition-colors">
              {t('acct.sec.change')}
            </button>
          </div>

          {/* 2FA row */}
          <div className="px-6 py-4 flex items-center justify-between">
            <div className="flex items-start gap-3">
              <div className="w-8 h-8 rounded-md bg-[#F4F7FD] flex items-center justify-center flex-shrink-0">
                <ShieldIcon size={14} className="text-[#3465E3]"/>
              </div>
              <div>
                <div className="flex items-center gap-2">
                  <div className="text-[13.5px] font-medium text-ink">{t('acct.sec.twofa')}</div>
                  {!twoFa && (
                    <span className="inline-flex items-center gap-1 px-1.5 py-[2px] rounded text-[10.5px] font-medium bg-[#FDECEC] text-[#D03B3B]">
                      <span className="w-1 h-1 rounded-full bg-[#D03B3B]"/> {t('acct.sec.inactive')}
                    </span>
                  )}
                  {twoFa && (
                    <span className="inline-flex items-center gap-1 px-1.5 py-[2px] rounded text-[10.5px] font-medium bg-emerald-50 text-emerald-700">
                      <span className="w-1 h-1 rounded-full bg-emerald-600"/> {t('acct.sec.active')}
                    </span>
                  )}
                </div>
                <div className="text-[12px] text-ink-muted mt-0.5 max-w-[520px]">{t('acct.sec.twofaSub')}</div>
              </div>
            </div>
            <button onClick={() => setTwoFa(v => !v)}
                    className="px-4 h-[32px] rounded-md text-[12.5px] font-medium text-white transition-transform hover:scale-[1.02]"
                    style={{background: twoFa
                      ? '#6B7280'
                      : 'linear-gradient(107.45deg, #1479FC 18.94%, #B880FC 123.42%)'}}>
              {twoFa ? t('acct.sec.twofaDeactivate') : t('acct.sec.twofaActivate')}
            </button>
          </div>
        </div>
      </Card>
    </>
  );
}

// --- Billing Panel --------------------------------------------------------

function BillingPanel({ accountStatus, currentPlan, trialDaysLeft, trialCreditsLeft, trialCreditsTotal, onOpenPricing }) {
  const lang = useLang();
  const [filter, setFilter] = useState('all');
  const isTrial = accountStatus === 'trial';
  const hasMethod = !isTrial; // subscribed users have a method on file

  // Monthly usage mock
  const monthLeadsUsed = isTrial ? 0 : Math.round(currentPlan.leadsPerMonth * 0.42);
  const monthLeadsLeft = Math.max(0, currentPlan.leadsPerMonth - monthLeadsUsed);
  const monthPct = isTrial ? 0 : Math.min(100, (monthLeadsUsed / currentPlan.leadsPerMonth) * 100);
  const nextRenewal = isTrial ? t('acct.plan.afterTrial') : '22.11.2025';

  const monthNames = lang === 'en'
    ? ['January','February','March','April','May','June','July','August','September','October','November','December']
    : ['Januar','Februar','März','April','Mai','Juni','Juli','August','September','Oktober','November','Dezember'];

  const txs = hasMethod ? [
    { date: '22.10.2025', desc: t('acct.bill.descSub', {plan: currentPlan.name, month: monthNames[9]}), amount: `${currentPlan.priceMonthly},00 €`, credits: `+${currentPlan.leadsPerMonth}`, status: 'paid' },
    { date: '22.09.2025', desc: t('acct.bill.descSub', {plan: currentPlan.name, month: monthNames[8]}), amount: `${currentPlan.priceMonthly},00 €`, credits: `+${currentPlan.leadsPerMonth}`, status: 'paid' },
  ] : [];

  return (
    <>
      {/* Subscription overview */}
      <div className="bg-white border border-line rounded-xl overflow-hidden">
        <div className="px-6 py-5 border-b border-[#F0F4FA] flex items-start justify-between gap-4">
          <div className="flex-1 min-w-0">
            <div className="flex items-center gap-2">
              <span className="text-[11px] uppercase tracking-[0.1em] text-ink-soft font-medium">{t('acct.plan.your')}</span>
              {isTrial ? (
                <span className="inline-flex items-center gap-1 px-1.5 py-[2px] rounded text-[10.5px] font-medium bg-ink text-white">
                  <span className="w-1 h-1 rounded-full bg-white"/> {t('acct.plan.trial')}
                </span>
              ) : (
                <span className="inline-flex items-center gap-1 px-1.5 py-[2px] rounded text-[10.5px] font-medium bg-emerald-50 text-emerald-700">
                  <span className="w-1 h-1 rounded-full bg-emerald-600"/> {t('acct.plan.active')}
                </span>
              )}
            </div>
            <div className="mt-1.5 flex items-baseline gap-2">
              <span className="text-[22px] font-semibold text-ink tracking-tight">{currentPlan.name}</span>
              <span className="text-[13px] text-ink-muted">· {currentPlan.priceMonthly},00 € {t('acct.plan.perMonth')}</span>
            </div>
            <div className="text-[12.5px] text-ink-muted mt-1">
              {isTrial
                ? (trialDaysLeft > 0
                    ? (trialDaysLeft === 1 ? t('acct.plan.dayLeft') : t('acct.plan.daysLeft', {n: trialDaysLeft}))
                    : t('acct.plan.endsToday'))
                : t('acct.plan.nextBill', {date: nextRenewal, leads: currentPlan.leadsPerMonth})}
            </div>
          </div>
          <div className="flex items-center gap-2 flex-shrink-0">
            {!isTrial && (
              <button onClick={() => onOpenPricing && onOpenPricing('sub')}
                      className="px-4 h-[34px] rounded-md border border-line text-[12.5px] font-medium text-ink-muted hover:bg-gray-50 transition-colors">
                {t('acct.plan.switch')}
              </button>
            )}
            {isTrial && (
              <button onClick={() => onOpenPricing && onOpenPricing('sub')}
                      className="inline-flex items-center gap-1.5 px-4 h-[34px] rounded-md text-[12.5px] font-medium text-white transition-transform hover:scale-[1.02]"
                      style={{background:'linear-gradient(107.45deg, #1479FC 18.94%, #B880FC 123.42%)'}}>
                {t('acct.plan.secureSub')} <Icon.ArrowRight size={12}/>
              </button>
            )}
          </div>
        </div>

        {/* Usage bar */}
        <div className="px-6 py-5">
          <div className="flex items-end justify-between mb-2">
            <div>
              <div className="text-[11px] uppercase tracking-[0.1em] text-ink-soft font-medium">
                {isTrial ? t('acct.plan.trialUsage') : t('acct.plan.monthUsage')}
              </div>
              <div className="mt-1 flex items-baseline gap-2">
                <span className="text-[20px] font-semibold text-ink tabular-nums">
                  {isTrial ? trialCreditsLeft : monthLeadsLeft}
                </span>
                <span className="text-[12.5px] text-ink-muted">
                  {t('acct.plan.leftOf', {total: isTrial ? trialCreditsTotal : currentPlan.leadsPerMonth})}
                </span>
              </div>
            </div>
            {!isTrial && (
              <button onClick={() => onOpenPricing && onOpenPricing('oneoff')}
                      className="inline-flex items-center gap-1.5 text-[12px] text-[#3465E3] font-medium hover:underline">
                {t('acct.plan.addOneOff')} <Icon.ArrowRight size={10}/>
              </button>
            )}
          </div>
          <div className="h-2 rounded-full bg-[#F0F4FA] overflow-hidden">
            <div className="h-full transition-all"
                 style={{
                   width: isTrial
                     ? `${Math.round(((trialCreditsTotal - trialCreditsLeft) / trialCreditsTotal) * 100)}%`
                     : `${monthPct}%`,
                   background: 'linear-gradient(90deg, #3465E3 0%, #8B5CF6 100%)',
                 }}/>
          </div>
          {!isTrial && (
            <div className="text-[11.5px] text-ink-soft mt-2 tabular-nums">
              {t('acct.plan.usedThisMonth', {used: monthLeadsUsed, total: currentPlan.leadsPerMonth, date: nextRenewal})}
            </div>
          )}
        </div>
      </div>

      {/* Payment methods */}
      <Card>
        <CardHeader
          title={t('acct.bill.methods')}
          action={hasMethod ? (
            <button className="inline-flex items-center gap-1.5 px-4 h-[34px] rounded-md text-[12.5px] font-medium text-white transition-transform hover:scale-[1.02]"
                    style={{background:'linear-gradient(107.45deg, #1479FC 18.94%, #B880FC 123.42%)'}}>
              <ExternalIcon size={12}/> {t('acct.bill.manageCards')}
            </button>
          ) : null}/>

        {hasMethod ? (
          <div className="px-6 py-4 flex items-center gap-4">
            <div className="w-11 h-8 rounded bg-gradient-to-br from-[#1A1F36] to-[#3A4464] flex items-center justify-center text-white text-[10px] font-bold tracking-wider">
              VISA
            </div>
            <div className="flex-1">
              <div className="text-[13px] text-ink font-medium">{t('acct.bill.cardEnds')}</div>
              <div className="text-[11.5px] text-ink-muted">{t('acct.bill.cardExpHolder')}</div>
            </div>
            <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[11px] font-medium bg-[#EEF2FE] text-[#3465E3]">
              {t('acct.bill.primary')}
            </span>
          </div>
        ) : (
          <div className="px-6 py-10 flex flex-col items-center justify-center text-center">
            <div className="w-14 h-14 rounded-full bg-[#F4F7FD] flex items-center justify-center mb-3">
              <CardIcon size={22} className="text-ink-soft"/>
            </div>
            <div className="text-[13.5px] text-ink-muted">{t('acct.bill.noMethods')}</div>
            <div className="text-[12px] text-ink-soft mt-1">{t('acct.bill.methodAutoAdded')}</div>
          </div>
        )}
      </Card>

      {/* Transactions */}
      <Card>
        <CardHeader
          title={t('acct.bill.history')}
          action={
            <select value={filter} onChange={e => setFilter(e.target.value)}
                    className="h-[32px] px-3 pr-7 rounded-md border border-line bg-white text-[12.5px] text-ink-muted hover:text-ink transition-colors cursor-pointer"
                    style={{backgroundImage:"url(\"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='10' height='6' viewBox='0 0 10 6' fill='none'><path d='M1 1L5 5L9 1' stroke='%236B7280' stroke-width='1.5' stroke-linecap='round'/></svg>\")",
                             backgroundRepeat:'no-repeat', backgroundPosition:'right 10px center',
                             appearance:'none', WebkitAppearance:'none'}}>
              <option value="all">{t('acct.bill.filter.all')}</option>
              <option value="30">{t('acct.bill.filter.30')}</option>
              <option value="90">{t('acct.bill.filter.90')}</option>
            </select>
          }/>

        <div className="overflow-hidden">
          <table className="w-full text-[13px]">
            <thead>
              <tr className="text-left text-[11px] uppercase tracking-[0.06em] text-ink-muted" style={{background:'#EEF2FE'}}>
                <th className="px-6 py-2.5 font-medium">{t('acct.bill.col.date')}</th>
                <th className="px-4 py-2.5 font-medium">{t('acct.bill.col.desc')}</th>
                <th className="px-4 py-2.5 font-medium text-right">{t('acct.bill.col.amount')}</th>
                <th className="px-4 py-2.5 font-medium text-right">{t('acct.bill.col.credits')}</th>
                <th className="px-4 py-2.5 font-medium">{t('acct.bill.col.status')}</th>
                <th className="px-6 py-2.5 font-medium text-right">{t('acct.bill.col.invoice')}</th>
              </tr>
            </thead>
            <tbody>
              {txs.length === 0 ? (
                <tr>
                  <td colSpan={6} className="px-6 py-12 text-center">
                    <div className="text-[13.5px] text-ink font-medium">{t('acct.bill.empty')}</div>
                    <div className="text-[12px] text-ink-muted mt-1">{t('acct.bill.emptySub')}</div>
                  </td>
                </tr>
              ) : txs.map((tx, i) => (
                <tr key={i} className="border-t border-line hover:bg-[#FAFCFF] transition-colors">
                  <td className="px-6 py-3.5 whitespace-nowrap text-ink">{tx.date}</td>
                  <td className="px-4 py-3.5 text-ink">{tx.desc}</td>
                  <td className="px-4 py-3.5 text-right tabular-nums font-medium text-ink">{tx.amount}</td>
                  <td className="px-4 py-3.5 text-right tabular-nums text-emerald-600 font-medium">{tx.credits}</td>
                  <td className="px-4 py-3.5">
                    <span className="inline-flex items-center gap-1 px-2 py-[2px] rounded-full text-[11px] font-medium bg-emerald-50 text-emerald-700">
                      <span className="w-1 h-1 rounded-full bg-emerald-600"/> {t('acct.bill.paid')}
                    </span>
                  </td>
                  <td className="px-6 py-3.5 text-right">
                    <button className="text-[12px] text-[#3465E3] font-medium hover:underline inline-flex items-center gap-1">
                      <DownloadIcon size={11}/> PDF
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </Card>
    </>
  );
}

// --- Shared building blocks ----------------------------------------------

function Card({ children }) {
  return (
    <div className="bg-white border border-line rounded-xl overflow-hidden">
      {children}
    </div>
  );
}

function CardHeader({ title, action }) {
  return (
    <div className="px-6 py-4 border-b border-[#F0F4FA] flex items-center justify-between">
      <div className="text-[14.5px] font-semibold text-ink">{title}</div>
      {action}
    </div>
  );
}

function Field({ label, value, onChange, type = 'text', select, options }) {
  return (
    <div>
      <label className="block text-[11.5px] text-ink-muted mb-1.5">{label}</label>
      {select ? (
        <select value={value} onChange={e => onChange(e.target.value)}
                className="w-full h-[38px] px-3 pr-8 rounded-md border border-line bg-white text-[13px] text-ink hover:border-[#C5D2EC] focus:outline-none focus:border-[#3465E3] focus:ring-2 focus:ring-[#3465E3]/15 transition-all cursor-pointer"
                style={{backgroundImage:"url(\"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='10' height='6' viewBox='0 0 10 6' fill='none'><path d='M1 1L5 5L9 1' stroke='%236B7280' stroke-width='1.5' stroke-linecap='round'/></svg>\")",
                         backgroundRepeat:'no-repeat', backgroundPosition:'right 12px center',
                         appearance:'none', WebkitAppearance:'none'}}>
          {(options || []).map(o => <option key={o} value={o}>{o}</option>)}
        </select>
      ) : (
        <input type={type} value={value} onChange={e => onChange(e.target.value)}
               className="w-full h-[38px] px-3 rounded-md border border-line bg-white text-[13px] text-ink hover:border-[#C5D2EC] focus:outline-none focus:border-[#3465E3] focus:ring-2 focus:ring-[#3465E3]/15 transition-all"/>
      )}
    </div>
  );
}

// --- Icons ---------------------------------------------------------------

function CardIcon({ 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}><rect x="2" y="5" width="20" height="14" rx="2"/><line x1="2" y1="10" x2="22" y2="10"/></svg>;
}
function LockIcon({ 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}><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>;
}
function ShieldIcon({ 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}><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>;
}
function CameraIcon({ 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}><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/><circle cx="12" cy="13" r="4"/></svg>;
}
function ExternalIcon({ size = 12, className = '' }) {
  return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className={className}><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>;
}
function DownloadIcon({ size = 12, className = '' }) {
  return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className={className}><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>;
}

Object.assign(window, { ScreenAccount });
