/* Klipzy.lv — Clipper dashboard + submit flow */
const round2 = (n) => Math.round((n + Number.EPSILON) * 100) / 100;
const CLIPPER_NAV = [
  { key: 'panel', label: 'Panelis', icon: 'grid' },
  { key: 'campaigns', label: 'Manas kampaņas', icon: 'megaphone' },
  { key: 'clips', label: 'Mani klipi', icon: 'film' },
  { key: 'earnings', label: 'Ieņēmumi', icon: 'wallet' },
  { key: 'payments', label: 'Maksājumi', icon: 'card' },
  { key: 'academy', label: 'Mācības', icon: 'book' },
  { key: 'settings', label: 'Iestatījumi', icon: 'gear' },
];

function ClipperApp({ go, params, user }) {
  const [tab, setTab] = useState(params.tab || 'panel');
  const lang = useLang();
  const uid = (user && user.user && user.user.uid) || null;
  const { campaigns, clips, loading, reload } = useClipperData(uid);
  useEffect(() => { if (params.tab) setTab(params.tab); }, [params.tab]);

  const onNav = (k) => { if (k === 'academy') { go('academy'); return; } setTab(k); };

  return (
    <div className="dash-shell" style={{ display: 'flex', height: '100%' }}>
      <Sidebar items={CLIPPER_NAV.map((n) => ({ ...n, label: tr(n.label, lang) }))} active={tab} onNav={onNav} role="clipper" go={go} user={user} />
      <div className="app-scroll" style={{ flex: 1 }}>
        {tab === 'panel' && <ClipperPanel go={go} setTab={setTab} clips={clips} campaigns={campaigns} loading={loading} joined={params.joined} user={user} reload={reload} />}
        {tab === 'campaigns' && <ClipperCampaigns go={go} campaigns={campaigns} loading={loading} joined={params.joined} uid={uid} reload={reload} />}
        {tab === 'clips' && <ClipperClips go={go} clips={clips} setTab={setTab} reload={reload} />}
        {tab === 'submit' && <SubmitClip go={go} setTab={setTab} params={params} user={user} myCampaigns={campaigns} onDone={reload} />}
        {tab === 'earnings' && <ClipperEarnings clips={clips} reload={reload} user={user} />}
        {tab === 'payments' && <ClipperPayments uid={uid} />}
        {tab === 'settings' && <SettingsStub title={tr('Iestatījumi', lang)} user={user} role="clipper" />}
      </div>
    </div>
  );
}

function ClipperPanel({ go, setTab, clips, campaigns, loading, joined, user, reload }) {
  const profile = (user && user.profile) || {};
  const fbUser = (user && user.user) || {};
  const cpuid = (user && user.user && user.user.uid) || null;
  const cverify = useVerify(cpuid, profile);
  const cplang = useLang();
  const T = (s) => tr(s, cplang);
  const fullName = profile.displayName || fbUser.displayName || '';
  const firstName = (fullName.trim().split(/\s+/)[0]) || (cplang === 'en' ? 'clipper' : 'klipotāj');
  const totalViews = clips.reduce((s, c) => s + c.views, 0);
  // Nopelnīts = validated & paid earnings only (verified from the brand side).
  const totalEarned = round2(clips.reduce((s, c) => s + (c.paidAmount || 0), 0));
  // Pending = earned-on-paper but not yet validated/verified (not counted as earned).
  const pending = round2(clips.reduce((s, c) => s + Math.max(0, (c.status !== 'rejected' ? c.earned : 0) - (c.paidAmount || 0)), 0));
  // Wallet: validated funds not yet cashed out.
  const walletBalance = round2(clips.reduce((s, c) => s + Math.max(0, (c.paidAmount || 0) - (c.withdrawnAmount || 0)), 0));
  // Deleted campaigns don't count as active participation.
  const activeCampaigns = campaigns.filter((m) => m.status !== 'deleted');
  const [cashOpen, setCashOpen] = useState(false);
  const uid = (user && user.user && user.user.uid) || null;
  const { notes, reload: reloadNotes } = useUserNotifications(uid);
  const resolveNote = async (n) => { try { if (window.KlipzyFirebase) await window.KlipzyFirebase.resolveNotification(n.id); } catch (_) {} reloadNotes(); };

  return (
    <div className="fade-in">
      <TopBar title={`${T('Sveiks')}, ${firstName} 👋`} subtitle={T('Lūk, kā veicas taviem klipiem.')} notif={{ notes, onResolve: resolveNote }}>
        <button className="btn btn-secondary" onClick={() => go('marketplace')}>{T('Kampaņas')}</button>
        <button className="btn btn-primary" onClick={() => setTab('submit')}><Icon d={I.plus} size={17} /> {T('Iesniegt jaunu klipu')}</button>
      </TopBar>
      <div style={{ padding: 32, display: 'flex', flexDirection: 'column', gap: 24 }}>
        <NotifBanner notes={notes.filter((n) => n.severity === 'critical')} onResolve={resolveNote} />
        {!cverify.both && (
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, background: 'var(--amber-tint)', border: '1px solid #FDE68A', borderRadius: 12, padding: '14px 18px' }}>
            <span style={{ color: 'var(--amber)' }}><Icon d={I.alert} size={18} /></span>
            <div style={{ flex: 1, fontSize: 13.5, color: '#92400E' }}>{tr('Lai iesniegtu klipus, vispirms verificē savu e-pastu.', cplang)}</div>
            <button className="btn btn-secondary btn-sm" style={{ flex: 'none' }} onClick={() => setTab('settings')}>{tr('Iestatījumi', cplang)}</button>
          </div>
        )}
        {joined && <JoinedBanner brand={joined} />}

        <div className="r-grid4" style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 18 }}>
          <StatCard label={T('Kopējie skatījumi')} value={views(totalViews)} icon="chart" />
          <StatCard label={T('Nopelnīts (kopā)')} value={eur(totalEarned)} icon="wallet" />
          <StatCard label={T('Gaida apstiprinājumu')} value={eur(pending)} icon="clock" />
          <StatCard label={T('Aktīvās kampaņas')} value={activeCampaigns.length} icon="megaphone" />
        </div>

        <div className="r-grid2" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 24 }}>
          {/* active campaigns */}
          <div className="card" style={{ padding: 22 }}>
            <div className="spread" style={{ marginBottom: 16 }}>
              <h3 style={{ fontSize: 16 }}>{T('Aktīvās kampaņas')}</h3>
              <button className="btn btn-ghost btn-sm" style={{ color: 'var(--accent-700)' }} onClick={() => setTab('campaigns')}>{T('Visas')}</button>
            </div>
            {activeCampaigns.length === 0 ? (
              <div className="muted" style={{ fontSize: 13.5, padding: '10px 0' }}>{loading ? T('Ielādē…') : T('Veēl neesi pievienojies kampaņām.')}</div>
            ) : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
              {activeCampaigns.map((m, i) => (
                <div key={m.cid} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '11px 0', borderTop: i ? '1px solid var(--border)' : 'none', cursor: 'pointer' }} onClick={() => go('campaign', { id: m.cid })}>
                  <BrandLogo initials={m.initials} grad={m.grad} size={40} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 14.5, fontWeight: 540 }}>{m.brand}</div>
                    <div className="muted" style={{ fontSize: 12.5 }}>{eur(m.rate)} / 1 000 · {m.clips} {T('klipi')}</div>
                  </div>
                  <div style={{ textAlign: 'right' }}>
                    <div className="tnum" style={{ fontSize: 14, fontWeight: 560 }}>{views(m.views)}</div>
                    <div className="tnum" style={{ fontSize: 12.5, color: 'var(--green)', fontWeight: 540 }}>{eur(m.earned)}</div>
                  </div>
                </div>
              ))}
            </div>
            )}
          </div>

          {/* earnings goal / payout */}
          <div className="card" style={{ padding: 22, display: 'flex', flexDirection: 'column' }}>
            <div className="spread" style={{ marginBottom: 16 }}>
              <h3 style={{ fontSize: 16 }}>{T('Nākamā izmaksa')}</h3>
            </div>
            <div style={{ background: 'linear-gradient(120deg,#1E3A8A,#2563EB)', borderRadius: 14, padding: '22px 24px', color: '#fff' }}>
              <div style={{ fontSize: 13, opacity: .82 }}>{T('Pieejamais atlikums')}</div>
              <div className="tnum" style={{ fontSize: 36, fontWeight: 600, letterSpacing: '-0.03em', marginTop: 4 }}>{eur(walletBalance)}</div>
              <button className="btn btn-block" style={{ marginTop: 16, background: '#fff', color: 'var(--accent-700)' }} disabled={walletBalance < 10} onClick={() => setCashOpen(true)}>{T('Pieprasīt izmaksu')}</button>
            </div>
            <div style={{ marginTop: 16, fontSize: 13, color: 'var(--text-2)', lineHeight: 1.5 }}>
              {T('Izmaksas tiek veiktas automātiski, kad sasniegts €10 slieksnis. Nauda kontā nonāk vidēji 1–2 darba dienu laikā.')}
            </div>
          </div>
        </div>

        {/* recent clips */}
        <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
          <div className="spread" style={{ padding: '18px 22px', borderBottom: '1px solid var(--border)' }}>
            <h3 style={{ fontSize: 16 }}>{T('Pēdējie iesniegtie klipi')}</h3>
            <button className="btn btn-ghost btn-sm" style={{ color: 'var(--accent-700)' }} onClick={() => setTab('clips')}>{T('Visi klipi')}</button>
          </div>
          {clips.length === 0
            ? <div className="muted" style={{ padding: 28, textAlign: 'center', fontSize: 14 }}>{loading ? T('Ielādē…') : T('Vēl nav iesniegtu klipu.')}</div>
            : <ClipsTable clips={clips} />}
        </div>
      </div>
      {cashOpen && <ClipperCashModal amount={walletBalance} clips={clips} user={user} onClose={() => setCashOpen(false)} onDone={() => { setCashOpen(false); if (reload) reload(); }} />}
    </div>
  );
}

function ClipperCashModal({ amount, clips, user, onClose, onDone }) {
  const lang = useLang();
  const T = (s) => tr(s, lang);
  const uid = (user && user.user && user.user.uid) || null;
  const profile = (user && user.profile) || {};
  const [wallets, setWallets] = useState(Array.isArray(profile.payoutWallets) ? profile.payoutWallets : []);
  const [busy, setBusy] = useState(false);
  const NETWORKS = { USDT: ['ERC20'], BTC: ['Bitcoin'], ETH: ['ERC20'] };
  const [coin, setCoin] = useState('USDT');
  const [network, setNetwork] = useState('ERC20');
  const [addr, setAddr] = useState('');
  const [selWallet, setSelWallet] = useState('');
  const [saveNew, setSaveNew] = useState(false);
  const [walletName, setWalletName] = useState('');
  const [err, setErr] = useState('');
  const [instant] = useState(false);
  const pickCoin = (k) => { setCoin(k); setNetwork(NETWORKS[k][0]); setSelWallet(''); setAddr(''); };
  const coinWallets = wallets.filter((w) => w.coin === coin);
  const pickSaved = (id) => {
    setSelWallet(id); setErr('');
    if (id === '') { setAddr(''); return; }
    const w = coinWallets.find((x) => x.id === id);
    if (w) { setAddr(w.addr); setNetwork(w.network || NETWORKS[coin][0]); }
  };
  const baseFee = Math.round((amount || 0) * 0.02 * 100) / 100;
  const instFee = instant ? Math.round((amount || 0) * 0.01 * 100) / 100 : 0;
  const totalFee = round2(baseFee + instFee);
  const net = round2(Math.max(0, (amount || 0) - totalFee));
  const submit = async () => {
    if (!addr.trim()) { setErr(T('Ievadi kripto maka adresi.')); return; }
    setBusy(true); setErr('');
    try {
      if (selWallet === '' && saveNew && uid) {
        const entry = { id: 'w' + Date.now(), name: (walletName.trim() || (coin + ' ' + T('maks'))), coin, network, addr: addr.trim() };
        try { await window.KlipzyFirebase.updateProfileFields(uid, { payoutWallets: [...wallets, entry] }); } catch (_) {}
      }
      if (window.KlipzyFirebase) await window.KlipzyFirebase.clipperCashout(clips.filter((c) => (c.paidAmount || 0) - (c.withdrawnAmount || 0) > 0), { instant, fee: totalFee, method: 'crypto', coin, network, addr: addr.trim() });
      onDone();
    } catch (e) { setErr(T('Neizdevās izpildīt izmaksu. Pārbaudi adresi un mēģini vēlreiz.')); setBusy(false); }
  };
  const removeWallet = async (id) => {
    const next = wallets.filter((w) => w.id !== id);
    setWallets(next);
    if (selWallet === id) { setSelWallet(''); setAddr(''); }
    try { if (window.KlipzyFirebase && uid) await window.KlipzyFirebase.updateProfileFields(uid, { payoutWallets: next }); } catch (_) {}
  };
  return (
    <ModalShell onClose={onClose} width={400}>
        <div className="spread" style={{ marginBottom: 6 }}>
          <h3 style={{ fontSize: 19 }}>{T('Pieprasīt izmaksu')}</h3>
          <button className="btn btn-ghost btn-sm" style={{ padding: 6 }} onClick={onClose}><Icon d={I.x} size={18} /></button>
        </div>
        <p className="muted" style={{ fontSize: 13.5, marginBottom: 16 }}>{T('Pieejams izmaksai')}: <strong className="tnum" style={{ color: 'var(--text)' }}>{eur(amount)}</strong></p>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <div className="field">
            <label>{T('Izmaksas metode')}</label>
            <div style={{ display: 'flex', gap: 8 }}>
              {['USDT', 'BTC', 'ETH'].map((k) => (
                <button key={k} onClick={() => pickCoin(k)} className="btn" style={{ flex: 1, height: 44, border: '1px solid ' + (coin === k ? 'var(--accent)' : 'var(--border-strong)'), background: coin === k ? 'var(--accent-tint)' : '#fff', color: coin === k ? 'var(--accent-700)' : 'var(--text-2)', fontWeight: 540 }}>{k}</button>
              ))}
            </div>
          </div>
          {coinWallets.length > 0 && (
            <div className="field">
              <label>{T('Saglabātā adrese')}</label>
              <select className="input" value={selWallet} onChange={(e) => pickSaved(e.target.value)}>
                <option value="">{T('Ievadīt jaunu adresi')}</option>
                {coinWallets.map((w) => <option key={w.id} value={w.id}>{w.name} — {w.addr.slice(0, 6)}…{w.addr.slice(-4)}</option>)}
              </select>
              {selWallet && <button className="btn-link" style={{ background: 'none', border: 'none', color: 'var(--red)', cursor: 'pointer', padding: '4px 0 0', font: 'inherit', fontSize: 12.5, alignSelf: 'flex-start' }} onClick={() => removeWallet(selWallet)}>{T('Dzēst saglabāto adresi')}</button>}
            </div>
          )}
          <div className="field">
            <label>{T('Tīkls')}</label>
            <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
              {NETWORKS[coin].map((n) => (
                <button key={n} onClick={() => setNetwork(n)} className="btn" style={{ flex: 1, minWidth: 90, height: 40, border: '1px solid ' + (network === n ? 'var(--accent)' : 'var(--border-strong)'), background: network === n ? 'var(--accent-tint)' : '#fff', color: network === n ? 'var(--accent-700)' : 'var(--text-2)', fontWeight: 540, fontSize: 13 }}>{n}</button>
              ))}
            </div>
            <span style={{ fontSize: 12, color: 'var(--muted)' }}>{T('Pārliecinies, ka tīkls atbilst tavam makam — nepareizs tīkls nozīmē zaudētus līdzekļus.')}</span>
          </div>
          {selWallet === '' && (
          <div className="field">
            <label>{coin} {T('maka adrese')}</label>
            <input className="input" value={addr} onChange={(e) => { setAddr(e.target.value); setErr(''); }} placeholder={coin + ' ' + T('adrese')} />
            <label style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, marginTop: 8, cursor: 'pointer', color: 'var(--text-2)' }}>
              <input type="checkbox" checked={saveNew} onChange={(e) => setSaveNew(e.target.checked)} style={{ accentColor: 'var(--accent)' }} />
              {T('Saglabāt šo adresi turpmākai lietošanai')}
            </label>
            {saveNew && <input className="input" style={{ marginTop: 8 }} value={walletName} onChange={(e) => setWalletName(e.target.value)} placeholder={T('Maka nosaukums (piem. Galvenais)')} />}
          </div>
          )}
          {amount > 0 && (
            <div style={{ background: '#F8FAFC', borderRadius: 10, padding: '12px 14px', fontSize: 13, display: 'flex', flexDirection: 'column', gap: 5 }}>
              <div className="spread"><span className="muted">{T('Summa')}</span><span className="tnum">{eur(amount)}</span></div>
              <div className="spread"><span className="muted">{T('Komisija')} (2%)</span><span className="tnum" style={{ color: 'var(--red)' }}>−{eur(totalFee)}</span></div>
              <div className="spread" style={{ borderTop: '1px solid var(--border)', paddingTop: 5, fontWeight: 600 }}><span>{T('Saņemsi')}</span><span className="tnum">{eur(net)}</span></div>
            </div>
          )}
          {err && <div style={{ background: '#FEF2F2', border: '1px solid #FECACA', color: '#B91C1C', borderRadius: 'var(--r)', padding: '10px 13px', fontSize: 13.5 }}>{err}</div>}
          <button className="btn btn-primary btn-lg btn-block" disabled={busy || amount < 10} onClick={submit}>{busy ? T('Apstrādā…') : T('Izmaksāt') + ' ' + eur(amount)}</button>
          <p className="muted" style={{ fontSize: 12, textAlign: 'center', lineHeight: 1.4 }}>{T('Parastā izmaksa nonāk kontā 7 darba dienu laikā.') + ' ' + T('Minimālā izmaksa €10.')}</p>
        </div>
    </ModalShell>
  );
}

function JoinedBanner({ brand }) {
  const lang = useLang();
  const [show, setShow] = useState(true);
  if (!show) return null;
  return (
    <div className="fade-in" style={{ display: 'flex', alignItems: 'center', gap: 12, background: 'var(--green-tint)', border: '1px solid #BBF7D0', borderRadius: 12, padding: '14px 18px' }}>
      <span style={{ width: 34, height: 34, borderRadius: 9, background: '#fff', color: 'var(--green)', display: 'grid', placeItems: 'center', flex: 'none' }}><Icon d={I.check} size={18} sw={2.4} /></span>
      <div style={{ flex: 1 }}>
        <div style={{ fontWeight: 560, fontSize: 14.5, color: '#166534' }}>{`${tr('Tu pievienojies kampaņai', lang)} “${brand}”!`}</div>
        <div style={{ fontSize: 13, color: '#15803D' }}>{tr('Izveido klipu pēc vadlīnijām un iesniedz to pārbaudei.', lang)}</div>
      </div>
      <button className="btn btn-ghost btn-sm" style={{ color: '#166534' }} onClick={() => setShow(false)}><Icon d={I.x} size={16} /></button>
    </div>
  );
}

const DISPUTE_STATUS_LV = { open: 'Strīds atvērts', fraud_review: 'Krāpšanas pārbaudē', under_review: 'Strīds tiek izskatīts', awaiting_info: 'Gaida tavu informāciju', resolved_clipper: 'Atrisināts par labu tev', resolved_brand: 'Atrisināts par labu zīmolam', closed: 'Strīds slēgts' };
function ClipsTable({ clips, onDelete, onDispute, onResubmit }) {
  const lang = useLang();
  const T = (s) => tr(s, lang);
  return (
    <table className="r-table">
      <thead>
        <tr style={{ background: '#FAFBFC' }}>
          {['Klips', 'Kampaņa', 'Platforma', 'Skatījumi', 'Statuss', 'Apstrādē', 'Izmaksāts'].map((h, i) => (
            <th key={h} style={{ textAlign: i >= 3 ? 'right' : 'left', padding: '11px 22px', fontSize: 11.5, fontWeight: 600, letterSpacing: '.05em', textTransform: 'uppercase', color: 'var(--muted)' }}>{T(h)}</th>
          ))}
          {(onDelete || onDispute) && <th style={{ padding: '11px 22px' }}></th>}
        </tr>
      </thead>
      <tbody>
        {clips.map((c) => {
          // Apstrādē (Pending): earned on views, awaiting automated validation.
          // Izmaksāts (Paid): amount the brand has paid into the wallet (paidAmount).
          const earned = c.status === 'rejected' ? 0 : (c.earned || 0);
          const paidToWallet = c.paidAmount || 0;
          const pend = Math.max(0, round2(earned - paidToWallet));
          const paid = round2(paidToWallet);
          return (
          <tr key={c.id} style={{ borderTop: '1px solid var(--border)' }}>
            <td style={{ padding: '12px 22px' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 11 }}>
                {c.url
                  ? <a href={c.url} target="_blank" rel="noopener noreferrer" title={c.url} style={{ flex: 'none' }}><GradTile grad={c.grad} radius={7} style={{ width: 34, height: 44, display: 'grid', placeItems: 'center', cursor: 'pointer' }}><Icon d={I.play} size={14} fill="#fff" stroke="none" /></GradTile></a>
                  : <GradTile grad={c.grad} radius={7} style={{ width: 34, height: 44, flex: 'none', display: 'grid', placeItems: 'center' }}><Icon d={I.play} size={14} fill="#fff" stroke="none" /></GradTile>}
                <span className="muted" style={{ fontSize: 12.5 }}>{c.date}</span>
              </div>
            </td>
            <td style={{ padding: '12px 22px', fontSize: 14, fontWeight: 540 }}>{c.campaign}</td>
            <td style={{ padding: '12px 22px' }}><Platform name={c.platform} /></td>
            <td style={{ padding: '12px 22px', textAlign: 'right' }} className="tnum">{numLv(c.views)}</td>
            <td style={{ padding: '12px 22px', textAlign: 'right' }}><StatusBadge status={c.clipState || c.status} /></td>
            <td style={{ padding: '12px 22px', textAlign: 'right', fontWeight: 540, color: pend > 0 ? 'var(--amber)' : 'var(--muted-2)' }} className="tnum">{pend > 0 ? eur(pend) : '—'}</td>
            <td style={{ padding: '12px 22px', textAlign: 'right', fontWeight: 560, color: paid > 0 ? 'var(--green)' : 'var(--muted-2)' }} className="tnum">{paid > 0 ? eur(paid) : '—'}</td>
            {(onDelete || onDispute) && (
              <td style={{ padding: '12px 22px', textAlign: 'right', whiteSpace: 'nowrap' }}>
                {onResubmit && c.status === 'rejected' && !c.disputed && <button className="btn btn-secondary btn-sm" style={{ marginRight: 8 }} onClick={() => onResubmit(c)}>{T('Jauna saite')}</button>}
                {onDispute && c.status === 'rejected' && (c.disputed
                  ? <span className="muted" style={{ fontSize: 12.5, marginRight: 8 }}>{tr(DISPUTE_STATUS_LV[c.disputeStatus] || 'Strīds izskatīšanā', lang)}</span>
                  : <button className="btn btn-secondary btn-sm" style={{ marginRight: 8 }} onClick={() => onDispute(c)}>{T('Iesniegt strīdu')}</button>)}
                {onDelete && <button className="btn btn-ghost btn-sm" style={{ color: 'var(--red)', padding: 6 }} title={T('Dzēst klipu')} onClick={() => onDelete(c)}><Icon d={I.trash} size={16} /></button>}
              </td>
            )}
          </tr>
          );
        })}
      </tbody>
    </table>
  );
}

function CampaignStatusBadge({ status }) {
  const lang = useLang();
  // Prefer the explicit derived state when a full campaign object isn't passed.
  if (status === 'paused') return <span className="badge badge-amber">{tr('Apturēta uz laiku', lang)}</span>;
  if (status === 'deleted') return <span className="badge badge-red">{tr('Pārtraukta', lang)}</span>;
  return <span className="badge badge-green">{tr('Aktīva', lang)}</span>;
}

function ConfirmDialog({ icon, danger, title, body, confirmLabel, busy, onConfirm, onClose }) {
  const lang = useLang();
  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(15,23,42,.45)', display: 'grid', placeItems: 'center', zIndex: 80, padding: 20 }}>
      <div onClick={(e) => e.stopPropagation()} className="card fade-in" style={{ width: 420, maxWidth: '100%', padding: 26 }}>
        <div style={{ width: 46, height: 46, borderRadius: 12, background: danger ? '#FEF2F2' : 'var(--accent-tint)', color: danger ? 'var(--red)' : 'var(--accent-700)', display: 'grid', placeItems: 'center', marginBottom: 14 }}><Icon d={icon || I.trash} size={22} /></div>
        <h3 style={{ fontSize: 18 }}>{title}</h3>
        <p className="muted" style={{ fontSize: 14, marginTop: 6, lineHeight: 1.5 }}>{body}</p>
        <div style={{ display: 'flex', gap: 10, marginTop: 22, justifyContent: 'flex-end' }}>
          <button className="btn btn-secondary" onClick={onClose}>{tr('Atcelt', lang)}</button>
          <button className="btn btn-primary" style={danger ? { background: 'var(--red)' } : undefined} disabled={busy} onClick={onConfirm}>{busy ? tr('Apstrādā…', lang) : confirmLabel}</button>
        </div>
      </div>
    </div>
  );
}

function ClipperCampaigns({ go, campaigns, loading, joined, uid, reload }) {
  const lang = useLang();
  const T = (s) => tr(s, lang);
  const [leaving, setLeaving] = useState(null); // campaign pending cancel
  const [busy, setBusy] = useState(false);
  const doLeave = async () => {
    if (!leaving) return;
    setBusy(true);
    try { if (window.KlipzyFirebase) await window.KlipzyFirebase.leaveCampaign(uid, leaving.cid, leaving.subIds); } catch (_) {}
    setBusy(false); setLeaving(null);
    if (reload) reload();
  };
  return (
    <div className="fade-in">
      <TopBar title={T('Manas kampaņas')} subtitle={T('Kampaņas, kurām esi pievienojies.')}>
        <button className="btn btn-primary" onClick={() => go('marketplace')}><Icon d={I.plus} size={17} /> {T('Pievienoties kampaņai')}</button>
      </TopBar>
      <div style={{ padding: 32 }}>
        {joined && <div style={{ marginBottom: 20 }}><JoinedBanner brand={joined} /></div>}
        {campaigns.length === 0 ? (
          <div className="card" style={{ padding: 48, textAlign: 'center' }}>
            <div className="muted" style={{ fontSize: 14.5 }}>{loading ? T('Ielādē…') : T('Veēl neesi pievienojies nevienai kampaņai.')}</div>
            {!loading && <button className="btn btn-primary" style={{ marginTop: 16 }} onClick={() => go('marketplace')}>{T('Pārlūkot kampaņas')}</button>}
          </div>
        ) : (
        <div className="r-grid2" style={{ display: 'grid', gridTemplateColumns: 'repeat(2,1fr)', gap: 18 }}>
          {campaigns.map((m) => {
            const stopped = m.status === 'deleted' || m.status === 'paused';
            return (
              <div key={m.cid} className="card" style={{ padding: 20, opacity: m.status === 'deleted' ? .75 : 1 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 13, marginBottom: 16 }}>
                  <BrandLogo initials={m.initials} grad={m.grad} size={46} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 15.5, fontWeight: 600 }}>{m.brand}</div>
                    <div className="muted" style={{ fontSize: 13 }}>{m.rate ? eur(m.rate) + ' / 1 000 ' + T('skatījumi') : T('Kampaņa vairs nav pieejama')}</div>
                  </div>
                  <CampaignStatusBadge status={m.status} />
                </div>

                {stopped && (
                  <div style={{ display: 'flex', alignItems: 'center', gap: 10, background: m.status === 'deleted' ? '#FEF2F2' : 'var(--amber-tint)', borderRadius: 10, padding: '10px 13px', marginBottom: 14, fontSize: 12.5, color: m.status === 'deleted' ? '#B91C1C' : '#92400E', lineHeight: 1.45 }}>
                    <Icon d={m.status === 'deleted' ? I.x : I.pause} size={15} />
                    {m.status === 'deleted' ? T('Zīmols ir pārtraucis šo kampaņu.') : T('Zīmols šo kampaņu uz laiku ir apturējis.')}
                  </div>
                )}

                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 10, marginBottom: 16 }}>
                  <MiniMetric label={T('Skatījumi')} value={views(m.views)} />
                  <MiniMetric label={T('Nopelnīts')} value={eur(m.earned)} accent />
                  <MiniMetric label={T('Klipi')} value={m.clips} />
                </div>
                <div style={{ display: 'flex', gap: 10 }}>
                  {m.status === 'deleted' ? (
                    <button className="btn btn-secondary btn-block btn-sm" onClick={() => setLeaving(m)}>{T('Noņemt no saraksta')}</button>
                  ) : (
                    <>
                      <button className="btn btn-secondary btn-block btn-sm" onClick={() => go('campaign', { id: m.cid })} disabled={m.status === 'paused'}>{T('Detaļas')}</button>
                      {m.status === 'active' && <button className="btn btn-primary btn-block btn-sm" onClick={() => go('clipper', { tab: 'submit', campaignId: m.cid })}>{T('Iesniegt klipu')}</button>}
                      <button className="btn btn-ghost btn-sm" style={{ color: 'var(--red)', flex: 'none' }} title={T('Atcelt dalību')} onClick={() => setLeaving(m)}><Icon d={I.x} size={16} /></button>
                    </>
                  )}
                </div>
              </div>
            );
          })}
        </div>
        )}
      </div>
      {leaving && (
        <ConfirmDialog danger icon={I.x}
          title={leaving.status === 'deleted' ? T('Noņemt kampaņu?') : T('Atcelt dalību?')}
          body={leaving.status === 'deleted'
            ? T('Kampaņa tiks noņemta no tava saraksta. Tavi iesniegtie klipi šai kampaņai arī tiks dzēsti.')
            : `${T('Tava dalība kampaņā')} “${leaving.brand}” ${T('tiks atcelta un visi tavi iesniegtie klipi šai kampaņai tiks noņemti no zīmola pārbaudes.')}`}
          confirmLabel={leaving.status === 'deleted' ? T('Noņemt') : T('Atcelt dalību')} busy={busy}
          onConfirm={doLeave} onClose={() => setLeaving(null)} />
      )}
    </div>
  );
}
function MiniMetric({ label, value, accent }) {
  return (
    <div style={{ background: '#F8FAFC', borderRadius: 10, padding: '10px 12px' }}>
      <div className="eyebrow" style={{ fontSize: 10 }}>{label}</div>
      <div className="tnum" style={{ fontSize: 17, fontWeight: 600, marginTop: 3, color: accent ? 'var(--green)' : 'var(--text)' }}>{value}</div>
    </div>
  );
}

function ClipperClips({ clips, setTab, reload }) {
  const lang = useLang();
  const T = (s) => tr(s, lang);
  const [del, setDel] = useState(null);
  const [busy, setBusy] = useState(false);
  const [dispute, setDispute] = useState(null);
  const [reason, setReason] = useState('');
  const [evidence, setEvidence] = useState('');
  const [resub, setResub] = useState(null);   // rejected clip pending link change
  const [resubUrl, setResubUrl] = useState('');
  const doDelete = async () => {
    if (!del) return;
    setBusy(true);
    try { if (window.KlipzyFirebase) await window.KlipzyFirebase.deleteSubmission(del.id); } catch (_) {}
    setBusy(false); setDel(null);
    if (reload) reload();
  };
  const doResubmit = async () => {
    if (!resub || !resubUrl.trim()) return;
    setBusy(true);
    // Replace the link on the same submission and send it back for review.
    try { if (window.KlipzyFirebase) await window.KlipzyFirebase.updateSubmission(resub.id, { url: resubUrl.trim(), reviewStatus: 'pending', frozen: false, rejectReason: null, disputed: false, disputeStatus: null }); } catch (_) {}
    setBusy(false); setResub(null); setResubUrl('');
    if (reload) reload();
  };
  const doDispute = async () => {
    if (!dispute || !reason.trim()) return;
    setBusy(true);
    try { if (window.KlipzyFirebase) await window.KlipzyFirebase.disputeSubmission(dispute, { reason: reason.trim(), evidence: evidence.trim() }); } catch (_) {}
    setBusy(false); setDispute(null); setReason(''); setEvidence('');
    if (reload) reload();
  };
  return (
    <div className="fade-in">
      <TopBar title={T('Mani klipi')} subtitle={`${clips.length} ${T('iesniegti klipi')}`}>
        <button className="btn btn-primary" onClick={() => setTab('submit')}><Icon d={I.plus} size={17} /> {T('Iesniegt jaunu klipu')}</button>
      </TopBar>
      <div style={{ padding: 32 }}>
        {clips.length === 0
          ? <div className="card" style={{ padding: 48, textAlign: 'center' }}><div className="muted" style={{ fontSize: 14.5 }}>{T('Vēl nav iesniegtu klipu.')}</div></div>
          : <div className="card" style={{ padding: 0, overflow: 'hidden' }}><ClipsTable clips={clips} onDelete={setDel} onDispute={setDispute} onResubmit={(c) => { setResub(c); setResubUrl(''); }} /></div>}
      </div>
      {resub && (
        <ModalShell onClose={() => setResub(null)} width={440}>
          <div className="spread" style={{ marginBottom: 6 }}>
            <h3 style={{ fontSize: 18 }}>{T('Iesniegt jaunu saiti')}</h3>
            <button className="btn btn-ghost btn-sm" style={{ padding: 6 }} onClick={() => setResub(null)}><Icon d={I.x} size={18} /></button>
          </div>
          {resub.rejectReason && <div style={{ background: '#FEF2F2', border: '1px solid #FECACA', color: '#B91C1C', borderRadius: 'var(--r)', padding: '10px 13px', fontSize: 13, marginBottom: 12 }}>{T('Noraidīšanas iemesls')}: {resub.rejectReason}</div>}
          <p className="muted" style={{ fontSize: 13.5, marginBottom: 14, lineHeight: 1.5 }}>{T('Nomaini saiti uz jaunu klipu — tas tiks nosūtīts atkārtotai pārbaudei. Pārējie kampaņas dati paliek nemainīgi.')}</p>
          <div className="field"><label>{T('Jaunā klipa saite')}</label><input className="input" placeholder="https://…" value={resubUrl} onChange={(e) => setResubUrl(e.target.value)} /></div>
          <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end', marginTop: 16 }}>
            <button className="btn btn-secondary" onClick={() => setResub(null)}>{T('Atcelt')}</button>
            <button className="btn btn-primary" disabled={busy || !resubUrl.trim()} onClick={doResubmit}>{busy ? T('Sūta…') : T('Iesniegt atkārtoti')}</button>
          </div>
        </ModalShell>
      )}
      {dispute && (
        <div onClick={() => setDispute(null)} style={{ position: 'fixed', inset: 0, background: 'rgba(15,23,42,.45)', display: 'grid', placeItems: 'center', zIndex: 80, padding: 20 }}>
          <div onClick={(e) => e.stopPropagation()} className="card fade-in" style={{ width: 440, maxWidth: '100%', padding: 26 }}>
            <div style={{ width: 46, height: 46, borderRadius: 12, background: 'var(--amber-tint)', color: 'var(--amber)', display: 'grid', placeItems: 'center', marginBottom: 14 }}><Icon d={I.alert} size={22} /></div>
            <h3 style={{ fontSize: 18 }}>{T('Iesniegt strīdu')}</h3>
            <p className="muted" style={{ fontSize: 13.5, marginTop: 6, lineHeight: 1.5 }}>{`${T('Strīds par klipu')} “${dispute.campaign}” ${T('tiks nosūtīts Klipzy atbalstam. Skatījumi paliek iesaldēti līdz administrācijas lēmumam.')}`}</p>
            <div style={{ marginTop: 16, display: 'flex', flexDirection: 'column', gap: 12 }}>
              <div className="field"><label>{T('Strīda iemesls')}</label><textarea className="textarea" rows="3" placeholder={T('Paskaidro, kāpēc nepiekrīti lēmumam…')} value={reason} onChange={(e) => setReason(e.target.value)} /></div>
              <div className="field"><label>{T('Pierādījumi / saite (nav obligāti)')}</label><input className="input" placeholder="https://…" value={evidence} onChange={(e) => setEvidence(e.target.value)} /></div>
              <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end' }}>
                <button className="btn btn-secondary" onClick={() => setDispute(null)}>{T('Atcelt')}</button>
                <button className="btn btn-primary" disabled={busy || !reason.trim()} onClick={doDispute}>{busy ? T('Sūta…') : T('Nosūtīt strīdu')}</button>
              </div>
            </div>
          </div>
        </div>
      )}
      {del && (
        <ConfirmDialog danger icon={I.trash}
          title={T('Dzēst klipu?')}
          body={del.status === 'approved'
            ? `${T('Šis klips')} (“${del.campaign}”) ${T('ir apstiprināts. Dzēšot to, tas tiks noņemts un vairs nepelnīs.')}`
            : `${T('Klips')} (“${del.campaign}”) ${T('tiks dzēsts un vairs nerādīsies zīmola pārbaudē.')}`}
          confirmLabel={T('Dzēst klipu')} busy={busy}
          onConfirm={doDelete} onClose={() => setDel(null)} />
      )}
    </div>
  );
}

function ClipperEarnings({ clips, reload, user }) {
  const lang = useLang();
  const T = (s) => tr(s, lang);
  // Nopelnīts = validated & paid (verified); pending = not yet validated.
  const paidClips = clips.filter((c) => (c.paidAmount || 0) > 0);
  const total = round2(clips.reduce((s, c) => s + (c.paidAmount || 0), 0));
  const pending = round2(clips.reduce((s, c) => s + Math.max(0, (c.status !== 'rejected' ? c.earned : 0) - (c.paidAmount || 0)), 0));
  const walletBalance = round2(clips.reduce((s, c) => s + Math.max(0, (c.paidAmount || 0) - (c.withdrawnAmount || 0)), 0));
  const [cashOpen, setCashOpen] = useState(false);
  return (
    <div className="fade-in">
      <TopBar title={T('Ieņēmumi')} subtitle={T('Tavi nopelnītie līdzekļi.')}>
        <button className="btn btn-primary" disabled={walletBalance < 10} onClick={() => setCashOpen(true)}><Icon d={I.wallet} size={16} /> {T('Nākamā izmaksa')} · {eur(walletBalance)}</button>
      </TopBar>
      <div style={{ padding: 32, display: 'flex', flexDirection: 'column', gap: 24 }}>
        <div className="r-grid3" style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 18 }}>
          <StatCard label={T('Nopelnīts (kopā)')} value={eur(total)} icon="wallet" />
          <StatCard label={T('Gaida apstiprinājumu')} value={eur(pending)} icon="clock" />
          <StatCard label={T('Pieejams izmaksai')} value={eur(walletBalance)} icon="check" />
        </div>
        <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
          <div style={{ padding: '18px 22px', borderBottom: '1px solid var(--border)' }}><h3 style={{ fontSize: 16 }}>{T('Validētie ieņēmumi')}</h3></div>
          {paidClips.length === 0 ? (
            <div className="muted" style={{ padding: 28, textAlign: 'center', fontSize: 14 }}>{T('Veēl nav validētu ieņēmumu. Skatījumi tiek izmaksāti pēc tam, kad zīmols tos apstiprina.')}</div>
          ) : (
          <table className="r-table">
            <thead><tr style={{ background: '#FAFBFC' }}>{['Datums', 'Kampaņa', 'Skatījumi', 'Nopelnīts'].map((h, i) => <th key={h} style={{ textAlign: i >= 2 ? 'right' : 'left', padding: '11px 22px', fontSize: 11.5, fontWeight: 600, letterSpacing: '.05em', textTransform: 'uppercase', color: 'var(--muted)' }}>{T(h)}</th>)}</tr></thead>
            <tbody>
              {paidClips.map((c) => (
                <tr key={c.id} style={{ borderTop: '1px solid var(--border)' }}>
                  <td style={{ padding: '13px 22px', fontSize: 14 }} className="muted">{c.date}</td>
                  <td style={{ padding: '13px 22px', fontSize: 14, fontWeight: 540 }}>{c.campaign}</td>
                  <td style={{ padding: '13px 22px', fontSize: 14, textAlign: 'right' }} className="tnum">{numLv(c.views)}</td>
                  <td style={{ padding: '13px 22px', fontSize: 14, fontWeight: 600, textAlign: 'right', color: 'var(--green)' }} className="tnum">+{eur(c.paidAmount)}</td>
                </tr>
              ))}
            </tbody>
          </table>
          )}
        </div>
        {cashOpen && <ClipperCashModal amount={walletBalance} clips={clips} user={user} onClose={() => setCashOpen(false)} onDone={() => { setCashOpen(false); if (reload) reload(); }} />}
      </div>
    </div>
  );
}

/* ===== PAYMENTS (cash-out history) ===== */
function ClipperPayments({ uid }) {
  const lang = useLang();
  const T = (s) => tr(s, lang);
  const [rows, setRows] = useState(null);
  useEffect(() => {
    let ok = true;
    (async () => {
      let list = [];
      try {
        if (window.KlipzyFirebase && window.KlipzyFirebase.listClipperCashouts) list = await window.KlipzyFirebase.listClipperCashouts(uid);
      } catch (_) {}
      if (ok) setRows(list);
    })();
    return () => { ok = false; };
  }, [uid]);
  const statusOf = (r) => {
    if (r.status === 'paid') return { label: T('Izmaksāts'), cls: 'badge-green' };
    if (r.status === 'processing') return { label: T('Procesā'), cls: 'badge-blue' };
    if (r.status === 'declined') return { label: T('Atteikts'), cls: 'badge-red' };
    if (r.status === 'failed') return { label: T('Neizdevās'), cls: 'badge-red' };
    return { label: T('Saņemts'), cls: 'badge-amber' };
  };
  return (
    <div className="fade-in">
      <TopBar title={T('Maksājumi')} subtitle={T('Tavu izmaksu vēsture un statuss.')} />
      <div style={{ padding: 32 }}>
        <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
          {rows === null ? (
            <div className="muted" style={{ padding: 28, textAlign: 'center', fontSize: 14 }}>{T('Ielādē…')}</div>
          ) : rows.length === 0 ? (
            <div className="muted" style={{ padding: 28, textAlign: 'center', fontSize: 14 }}>{T('Vēl nav izmaksu.')}</div>
          ) : (
            <table className="r-table">
              <thead>
                <tr style={{ background: '#FAFBFC' }}>
                  {['Datums', 'Summa', 'Metode', 'Statuss'].map((h, i) => (
                    <th key={h} style={{ textAlign: i >= 1 && i <= 1 ? 'right' : 'left', padding: '11px 22px', fontSize: 11.5, fontWeight: 600, letterSpacing: '.05em', textTransform: 'uppercase', color: 'var(--muted)' }}>{T(h)}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {rows.map((r) => {
                  const st = statusOf(r);
                  const d = r.createdAt && r.createdAt.seconds ? new Date(r.createdAt.seconds * 1000).toLocaleDateString(lang === 'en' ? 'en-GB' : 'lv-LV') : '—';
                  return (
                    <tr key={r.id} style={{ borderTop: '1px solid var(--border)' }}>
                      <td style={{ padding: '13px 22px', fontSize: 13.5 }} className="muted">{d}</td>
                      <td style={{ padding: '13px 22px', textAlign: 'right', fontWeight: 600 }} className="tnum">{eur(r.net != null ? r.net : r.amount)}</td>
                      <td style={{ padding: '13px 22px', fontSize: 13 }}>{r.coin || r.method || '—'}{r.network ? ' · ' + r.network : ''}</td>
                      <td style={{ padding: '13px 22px' }}><span className={'badge ' + st.cls}>{st.label}</span>{r.status === 'failed' && r.failReason ? <div className="muted" style={{ fontSize: 12, marginTop: 3 }}>{r.failReason}</div> : null}</td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          )}
        </div>
      </div>
    </div>
  );
}

/* ===== SUBMIT CLIP ===== */
function SubmitClip({ go, setTab, params, user, myCampaigns, onDone }) {
  const lang = useLang();
  const scuid = (user && user.user && user.user.uid) || null;
  const scverify = accountVerified(scuid, (user && user.profile) || {});
  const { campaigns: allCampaigns } = useCampaigns();
  // Only campaigns the clipper is actively participating in — ended, paused,
  // and deleted campaigns are excluded from the dropdown. Campaigns closed to
  // new submissions (budget exhausted / 10% low-budget rule) are also excluded.
  const options = (myCampaigns || []).filter((m) => !m.ended && m.isOpenForSubmissions !== false);
  const [campaign, setCampaign] = useState('');
  const [platform, setPlatform] = useState('');
  const [url, setUrl] = useState('');
  const [notes, setNotes] = useState('');
  const [done, setDone] = useState(false);
  const [touched, setTouched] = useState(false);
  const [busy, setBusy] = useState(false);
  const [dupErr, setDupErr] = useState('');

  const [locked, setLocked] = useState(!!(params && params.campaignId));
  // Preselect campaign if arriving from a campaign page (locked); the main-page
  // "Iesniegt jaunu klipu" button arrives with no campaignId, so it stays changeable.
  useEffect(() => { if (params && params.campaignId) { setCampaign(params.campaignId); setLocked(true); } }, [params && params.campaignId]);

  // Resolve the full campaign (platforms, rate, brandUid) from the global list.
  const camp = allCampaigns.find((c) => c.id === campaign);
  // A campaign whose budget is already fully committed to earlier clips can
  // take no new submissions (FIFO: the money is spoken for).
  const [budgetFull, setBudgetFull] = useState(false);
  useEffect(() => {
    let alive = true;
    setBudgetFull(false);
    if (!camp || !camp.id) return;
    (async () => {
      try {
        const all = window.KlipzyFirebase ? await window.KlipzyFirebase.listAllSubmissions() : [];
        if (!alive) return;
        const mine = (all || []).filter((s) => s.campaignId === camp.id).map(mapSubmission);
        setBudgetFull(campaignBudgetExhausted(mine, camp));
      } catch (_) {}
    })();
    return () => { alive = false; };
  }, [camp && camp.id]);
  const closed = camp && (camp.isOpenForSubmissions === false || budgetFull);
  const platOptions = camp ? camp.platforms : [];
  // TikTok clips require a verified TikTok account (mirrors YouTube-only rules).
  const ttVerified = !!(user && user.profile && user.profile.tiktok_verified);
  const needsTikTok = canonPlatform(platform) === 'tiktok' && !ttVerified;
  const igVerified = !!(user && user.profile && user.profile.instagram_verified);
  const needsInstagram = canonPlatform(platform) === 'instagram' && !igVerified;
  const valid = campaign && platform && !closed && /^https?:\/\/|\.(com|lv)/.test(url.toLowerCase()) && url.length > 6;
  const clipperName = (user && user.profile && user.profile.displayName) || (user && user.user && user.user.displayName) || 'Klipotājs';
  const clipperUid = (user && user.user && user.user.uid) || null;

  const submit = async () => {
    setTouched(true);
    if (!scverify.both) { setDupErr(tr('Vispirms verificē savu e-pastu Iestatījumos, lai iesniegtu klipus.', lang)); return; }
    if (needsTikTok) { setDupErr(tr('Lūdzu, verificē savu TikTok kontu Iestatījumos pirms TikTok klipu iesniegšanas.', lang)); return; }
    if (needsInstagram) { setDupErr(tr('Lūdzu, verificē savu Instagram kontu Iestatījumos pirms Instagram klipu iesniegšanas.', lang)); return; }
    if (!valid || !camp || closed) return;
    setBusy(true);
    setDupErr('');
    try {
      if (window.KlipzyFirebase) {
        const canonical = canonPlatform(platform);
        // The URL must actually belong to the selected platform.
        const urlPlat = /(?:^|\.)tiktok\.com/i.test(url) ? 'tiktok'
          : /(?:youtube\.com|youtu\.be)/i.test(url) ? 'youtube'
          : /(?:^|\.)instagram\.com/i.test(url) ? 'instagram' : '';
        if (!urlPlat || urlPlat !== canonical) {
          setDupErr(tr('Saite neatbilst izvēlētajai platformai. Iesniedz {p} video saiti.', lang).replace('{p}', PLATFORM_LABEL[canonical] || platform));
          setBusy(false); return;
        }
        // Instagram: only Reels are supported (feed /p/ posts don't carry a
        // reliable publish time for the 60-minute window).
        if (canonical === 'instagram' && !/instagram\.com\/reels?\//i.test(url)) {
          setDupErr(tr('Instagram klipiem izmanto Reel saiti (instagram.com/reel/...).', lang));
          setBusy(false); return;
        }
        // Fetch the clip's current views at submission so it shows immediately
        // (baseline), and verify the 60-minute publication window per platform.
        let startCount = 0;
        if (canonical === 'tiktok') {
          // TikTok live streams aren't allowed — only regular videos.
          if (/tiktok\.com\/@[^/]+\/live|\/live\b/i.test(url)) { setDupErr(tr('TikTok tiešraides nevar iesniegt — tikai video.', lang)); setBusy(false); return; }
          if (window.KlipzyFirebase.getTikTokViews) {
            let d = null;
            try {
              d = await window.KlipzyFirebase.getTikTokViews(url);
            } catch (e) {
              // A failed lookup must NOT let an old clip through.
              setDupErr(tr('Neizdevās pārbaudīt klipa publicēšanas laiku. Mēģini vēlreiz.', lang)); setBusy(false); return;
            }
            if (d && d.isLive) { setDupErr(tr('TikTok tiešraides nevar iesniegt — tikai video.', lang)); setBusy(false); return; }
            if (d && Number.isFinite(+d.views)) startCount = +d.views;
            // Enforce the 60-minute publication window for TikTok clips.
            if (d && d.createdMs) {
              const ageMin = (Date.now() - Number(d.createdMs)) / 60000;
              if (ageMin > 60) { setDupErr(tr('Klipu var iesniegt tikai 60 minūšu laikā pēc publicēšanas. Šis klips ir par vecu.', lang)); setBusy(false); return; }
            } else {
              setDupErr(tr('Neizdevās noteikt klipa publicēšanas laiku. Mēģini vēlreiz.', lang)); setBusy(false); return;
            }
          } else {
            setDupErr(tr('Neizdevās pārbaudīt klipa publicēšanas laiku. Mēģini vēlreiz.', lang)); setBusy(false); return;
          }
        } else if (canonical === 'instagram') {
          if (window.KlipzyFirebase.getInstagramViews) {
            let d = null;
            try {
              d = await window.KlipzyFirebase.getInstagramViews(url);
            } catch (e) {
              // A failed lookup must NOT let an old clip through.
              setDupErr(tr('Neizdevās pārbaudīt klipa publicēšanas laiku. Mēģini vēlreiz.', lang)); setBusy(false); return;
            }
            if (d && Number.isFinite(+d.views)) startCount = +d.views;
            // Enforce the 60-minute publication window for Instagram clips.
            // If Apify returns no timestamp we reject rather than silently
            // allowing an old Reel through.
            if (d && d.createdMs) {
              const ageMin = (Date.now() - Number(d.createdMs)) / 60000;
              if (ageMin > 60) { setDupErr(tr('Klipu var iesniegt tikai 60 minūšu laikā pēc publicēšanas. Šis klips ir par vecu.', lang)); setBusy(false); return; }
            } else {
              setDupErr(tr('Neizdevās noteikt klipa publicēšanas laiku. Mēģini vēlreiz.', lang) + (d && d.tsKeys ? ' [' + d.tsKeys + ']' : ' [nav lauku]')); setBusy(false); return;
            }
          } else {
            setDupErr(tr('Neizdevās pārbaudīt klipa publicēšanas laiku. Mēģini vēlreiz.', lang)); setBusy(false); return;
          }
        } else if (canonical === 'youtube') {
          // YouTube uses the Data API: live view count + publish time, and
          // live streams / premieres are rejected.
          if (window.KlipzyFirebase.getYouTubeMeta) {
            let d = null;
            try {
              d = await window.KlipzyFirebase.getYouTubeMeta(url);
            } catch (e) {
              setDupErr(tr('Neizdevās pārbaudīt klipa publicēšanas laiku. Mēģini vēlreiz.', lang)); setBusy(false); return;
            }
            if (d && d.isLive) { setDupErr(tr('YouTube tiešraides nevar iesniegt — tikai video.', lang)); setBusy(false); return; }
            if (d && Number.isFinite(+d.views)) startCount = +d.views;
            if (d && d.createdMs) {
              const ageMin = (Date.now() - Number(d.createdMs)) / 60000;
              if (ageMin > 60) { setDupErr(tr('Klipu var iesniegt tikai 60 minūšu laikā pēc publicēšanas. Šis klips ir par vecu.', lang)); setBusy(false); return; }
            } else {
              setDupErr(tr('Neizdevās noteikt klipa publicēšanas laiku. Mēģini vēlreiz.', lang)); setBusy(false); return;
            }
          } else {
            setDupErr(tr('Neizdevās pārbaudīt klipa publicēšanas laiku. Mēģini vēlreiz.', lang)); setBusy(false); return;
          }
        }
        await window.KlipzyFirebase.createSubmission({
          campaignId: camp.id, campaignName: camp.name, brandUid: camp.brandUid,
          clipperUid, clipper: clipperName,
          platform: canonical, videoId: extractVideoId(url, canonical), url, viewCount: startCount,
          rate: camp.rate, minViews: camp.minViews,
        });
      }
      if (onDone) onDone();
      setDone(true);
    } catch (e) {
      if (e && e.code === 'duplicate-submission') setDupErr(tr('Šis klips jau ir iesniegts šai kampaņai. Vienu un to pašu saturu nevar iesniegt divreiz.', lang));
      else if (e && e.code === 'duplicate-content-global') setDupErr(tr('Šis klips jau ir iesniegts platformā. Vienu un to pašu saturu nevar iesniegt vairākas reizes vai no vairākiem kontiem.', lang));
      else setDupErr(tr('Neizdevās iesniegt klipu. Mēģini vēlreiz.', lang));
    }
    setBusy(false);
  };

  if (done) {
    return (
      <div className="fade-in" style={{ height: '100%', display: 'grid', placeItems: 'center', padding: 32 }}>
        <div className="card" style={{ padding: '48px 44px', maxWidth: 460, textAlign: 'center' }}>
          <div style={{ width: 64, height: 64, borderRadius: 999, background: 'var(--green-tint)', color: 'var(--green)', display: 'grid', placeItems: 'center', margin: '0 auto 22px' }}><Icon d={I.check} size={32} sw={2.4} /></div>
          <h2 style={{ fontSize: 23 }}>{tr('Klips iesniegts pārbaudei', lang)}</h2>
          <p className="muted" style={{ fontSize: 15, marginTop: 12, lineHeight: 1.5 }}>{tr('Skatījumi tiks izsekoti automātiski. Tiklīdz zīmols apstiprinās klipu, tas parādīsies tavā panelī.', lang)}</p>
          <div style={{ background: '#F8FAFC', borderRadius: 12, padding: 16, margin: '22px 0', textAlign: 'left' }}>
            <Row k={tr('Kampaņa', lang)} v={camp ? camp.name : campaign} /><Row k={tr('Platforma', lang)} v={platform} /><Row k={tr('Saite', lang)} v={url} last />
          </div>
          <div style={{ display: 'flex', gap: 10 }}>
            <button className="btn btn-secondary btn-block" onClick={() => { setDone(false); setCampaign(''); setPlatform(''); setUrl(''); setNotes(''); setTouched(false); }}>{tr('Iesniegt vēl vienu', lang)}</button>
            <button className="btn btn-primary btn-block" onClick={() => setTab('clips')}>{tr('Skatīt manus klipus', lang)}</button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="fade-in">
      <TopBar title={tr('Iesniegt jaunu klipu', lang)} subtitle={tr('Pievieno sava klipa saiti — pārējo izdarīsim mēs.', lang)} />
      <div style={{ padding: 32, maxWidth: 640 }}>
        <div className="card" style={{ padding: 28, display: 'flex', flexDirection: 'column', gap: 20 }}>
          <div className="field">
            <label>{tr('Kampaņa', lang)}</label>
            {camp && locked ? (
              <div className="input" style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', background: '#F8FAFC', cursor: 'default' }}>
                <span style={{ fontWeight: 540 }}>{camp.brand || camp.name}</span>
                <span className="muted" style={{ fontSize: 13 }}>{eur(camp.rate)} / 1 000</span>
              </div>
            ) : (
              <>
                <select className="select" value={campaign} onChange={(e) => { setCampaign(e.target.value); setPlatform(''); }} disabled={options.length === 0}>
                  <option value="">{options.length === 0 ? tr('Nav pievienotu kampaņu', lang) : tr('Izvēlies kampaņu…', lang)}</option>
                  {options.map((m) => <option key={m.cid} value={m.cid}>{m.brand} — {eur(m.rate)} / 1 000</option>)}
                </select>
                {options.length === 0 && (
                  <span style={{ fontSize: 12.5, color: 'var(--muted)' }}>{tr('Vispirms pievienojies kampaņai', lang)} <button className="btn-link" onClick={() => go('marketplace')} style={{ background: 'none', border: 'none', color: 'var(--accent-700)', cursor: 'pointer', padding: 0, font: 'inherit' }}>{tr('tirgū', lang)}</button>.</span>
                )}
              </>
            )}
          </div>

          <div className="field">
            <label>{tr('Platforma', lang)}</label>
            <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
              {(platOptions.length ? platOptions : ALL_PLATFORMS).map((p) => {
                const canon = canonPlatform(p);
                const locked = (canon === 'tiktok' && !ttVerified) || (canon === 'instagram' && !igVerified);
                return (
                <button key={p} onClick={() => { if (!locked) setPlatform(p); }} disabled={!campaign || locked} className="btn"
                  title={locked ? tr('Platforma nav verificēta. Verificē to Iestatījumos.', lang) : undefined}
                  style={{ flex: '1 1 30%', minWidth: 92, height: 42, fontSize: 13.5, border: '1px solid ' + (platform === p ? 'var(--accent)' : 'var(--border-strong)'), background: platform === p ? 'var(--accent-tint)' : '#fff', color: platform === p ? 'var(--accent-700)' : 'var(--text-2)', fontWeight: 540, opacity: !campaign ? .5 : (locked ? .4 : 1), cursor: locked ? 'not-allowed' : 'pointer' }}>
                  {PLATFORM_LABEL[canon] || p}
                </button>
                );
              })}
            </div>
            {needsTikTok && (
              <div style={{ display: 'flex', alignItems: 'center', gap: 9, background: 'var(--amber-tint)', border: '1px solid #FDE68A', borderRadius: 10, padding: '10px 13px', fontSize: 13, color: '#92400E', marginTop: 8 }}>
                <Icon d={I.alert} size={16} /> {tr('Lūdzu, verificē savu TikTok kontu Iestatījumos pirms TikTok klipu iesniegšanas.', lang)}
              </div>
            )}
            {needsInstagram && (
              <div style={{ display: 'flex', alignItems: 'center', gap: 9, background: 'var(--amber-tint)', border: '1px solid #FDE68A', borderRadius: 10, padding: '10px 13px', fontSize: 13, color: '#92400E', marginTop: 8 }}>
                <Icon d={I.alert} size={16} /> {tr('Lūdzu, verificē savu Instagram kontu Iestatījumos pirms Instagram klipu iesniegšanas.', lang)}
              </div>
            )}
          </div>

          <div className="field">
            <label>{tr('Klipa saite (URL)', lang)}</label>
            <div style={{ position: 'relative' }}>
              <span style={{ position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)', color: 'var(--muted-2)' }}><Icon d={I.link} size={17} /></span>
              <input className="input" style={{ paddingLeft: 38, borderColor: touched && !valid && url ? 'var(--red)' : undefined }} placeholder="https://tiktok.com/@tu/video/…" value={url} onChange={(e) => setUrl(e.target.value)} />
            </div>
            {touched && !valid && <span style={{ fontSize: 12.5, color: 'var(--red)' }}>{tr('Lūdzu, ievadi derīgu klipa saiti.', lang)}</span>}
          </div>

          <div className="field">
            <label>{tr('Piezīmes', lang)} <span className="muted" style={{ fontWeight: 400 }}>({tr('neobligāti', lang)})</span></label>
            <textarea className="textarea" rows="3" placeholder={tr('Kaut kas, ko zīmolam vajadzētu zināt par šo klipu…', lang)} value={notes} onChange={(e) => setNotes(e.target.value)} />
          </div>

          <div style={{ display: 'flex', alignItems: 'center', gap: 9, background: 'var(--accent-tint)', borderRadius: 10, padding: '12px 14px', fontSize: 13.5, color: 'var(--accent-700)' }}>
            <Icon d={I.spark} size={17} /> {tr('Skatījumi tiks izsekoti automātiski no publiskās saites.', lang)}
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 9, background: 'var(--amber-tint)', border: '1px solid #FDE68A', borderRadius: 10, padding: '12px 14px', fontSize: 13, color: '#92400E' }}>
            <Icon d={I.clock} size={16} /> {tr('Klipu var iesniegt tikai 60 minūšu laikā pēc tā publicēšanas.', lang)}
          </div>

          {closed && (
            <div style={{ display: 'flex', alignItems: 'center', gap: 9, background: '#FEF2F2', border: '1px solid #FECACA', borderRadius: 10, padding: '12px 14px', fontSize: 13.5, color: '#B91C1C' }}>
              <Icon d={I.alert} size={17} /> {tr('Šī kampaņa vairs nepieņem jaunus klipus (budžets ir zems vai iztērēts).', lang)}
            </div>
          )}

          <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end' }}>
            <button className="btn btn-secondary" onClick={() => setTab('panel')}>{tr('Atcelt', lang)}</button>
            <button className="btn btn-primary" disabled={busy || closed} onClick={submit}>{busy ? tr('Iesniedz…', lang) : tr('Iesniegt klipu', lang)} <Icon d={I.arrowR} size={16} /></button>
          </div>
          {dupErr && <div style={{ background: '#FEF2F2', border: '1px solid #FECACA', color: '#B91C1C', borderRadius: 'var(--r)', padding: '10px 13px', fontSize: 13.5, marginTop: 10 }}>{dupErr}</div>}
        </div>
      </div>
    </div>
  );
}
function Row({ k, v, last }) {
  return (
    <div className="spread" style={{ padding: '7px 0', borderBottom: last ? 'none' : '1px solid var(--border)' }}>
      <span className="muted" style={{ fontSize: 13 }}>{k}</span>
      <span style={{ fontSize: 13, fontWeight: 540, maxWidth: 220, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{v}</span>
    </div>
  );
}

const PHONE_CODES = [
  ['LV', '🇱🇻', '+371'], ['LT', '🇱🇹', '+370'], ['EE', '🇪🇪', '+372'],
  ['GB', '🇬🇧', '+44'], ['DE', '🇩🇪', '+49'], ['FR', '🇫🇷', '+33'],
  ['ES', '🇪🇸', '+34'], ['IT', '🇮🇹', '+39'], ['PL', '🇵🇱', '+48'],
  ['SE', '🇸🇪', '+46'], ['FI', '🇫🇮', '+358'], ['NL', '🇳🇱', '+31'],
  ['US', '🇺🇸', '+1'], ['UA', '🇺🇦', '+380'], ['RU', '🇷🇺', '+7'],
];
function EmailVerify({ lang, email, uid, profile }) {
  // The registered address is fixed — users can't verify a different one.
  const addr = (profile && profile.email) || email || '';
  const [sent, setSent] = useState(false);
  const [sentAt, setSentAt] = useState(0);
  const [code, setCode] = useState('');
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState('');
  const [cooldown, setCooldown] = useState(0);
  // Tick the resend cooldown down to zero.
  useEffect(() => {
    if (cooldown <= 0) return;
    const t = setTimeout(() => setCooldown((n) => n - 1), 1000);
    return () => clearTimeout(t);
  }, [cooldown]);
  // Google sign-ups arrive pre-verified; Firestore is the source of truth.
  const google = !!(profile && (profile.authProvider === 'google' || profile.photoURL || '').toString().includes('googleusercontent'));
  const [verified, setVerified] = useState(() => !!(profile && (profile.emailVerified || profile.authProvider === 'google')));
  useEffect(() => { if (profile && (profile.emailVerified || profile.authProvider === 'google')) setVerified(true); }, [profile && profile.emailVerified, profile && profile.authProvider]);
  const CODE_TTL = 30 * 60 * 1000;
  // Auto-cancel once the code expires so the user must request a fresh one.
  useEffect(() => {
    if (!sent || verified || !sentAt) return;
    const left = sentAt + CODE_TTL - Date.now();
    if (left <= 0) { setSent(false); setCode(''); setErr(tr('Kods ir beidzies. Pieprasi jaunu kodu.', lang)); return; }
    const t = setTimeout(() => { setSent(false); setCode(''); setErr(tr('Kods ir beidzies. Pieprasi jaunu kodu.', lang)); }, left);
    return () => clearTimeout(t);
  }, [sent, sentAt, verified]);
  const send = async () => {
    setBusy(true); setErr('');
    try {
      if (window.KlipzyFirebase) await window.KlipzyFirebase.sendEmailVerifyCode(addr, lang);
      setSent(true); setSentAt(Date.now()); setCode(''); setCooldown(30);
    } catch (e) {
      setErr((e && e.message) || tr('Neizdevās nosūtīt kodu. Mēģini vēlreiz.', lang));
    }
    setBusy(false);
  };
  const cancel = () => { setSent(false); setSentAt(0); setCode(''); setErr(''); setCooldown(0); };
  // Resend re-delivers the SAME code (a lost email, not a new request).
  const resend = async () => {
    if (cooldown > 0) return;
    setBusy(true); setErr('');
    try {
      if (window.KlipzyFirebase) await window.KlipzyFirebase.sendEmailVerifyCode(addr, lang, true);
      setCooldown(30);
    } catch (e) {
      setErr((e && e.message) || tr('Neizdevās nosūtīt kodu. Mēģini vēlreiz.', lang));
    }
    setBusy(false);
  };
  const confirm = async () => {
    // Client-side expiry guard; the Cloud Function enforces it authoritatively.
    if (sentAt && Date.now() - sentAt > CODE_TTL) { cancel(); setErr(tr('Kods ir beidzies. Pieprasi jaunu kodu.', lang)); return; }
    setBusy(true); setErr('');
    try {
      const r = window.KlipzyFirebase ? await window.KlipzyFirebase.confirmEmailVerifyCode(uid, code) : { verified: true };
      if (r && r.verified) { setVerified(true); setVerifyFlag(uid, 'email', true); }
      else setErr(tr('Nepareizs kods.', lang));
    } catch (e) {
      const msg = (e && e.message) || '';
      // Expired on the server → drop back to the start of the flow.
      if (/expired|beidz/i.test(msg)) { cancel(); setErr(tr('Kods ir beidzies. Pieprasi jaunu kodu.', lang)); }
      else setErr(msg || tr('Nepareizs kods.', lang));
    }
    setBusy(false);
  };
  return (
    <div className="field">
      <label>{tr('E-pasts', lang)}</label>
      <div style={{ display: 'flex', gap: 8, alignItems: 'stretch' }}>
        <input className="input" style={{ flex: 1 }} value={addr} readOnly disabled placeholder="tu@epasts.lv" />
        {!verified && <button className="btn btn-secondary" style={{ flex: 'none' }} disabled={busy || sent} onClick={send}>
          {sent ? <><Icon d={I.check} size={15} sw={2.4} /> {tr('Nosūtīts', lang)}</> : busy ? tr('Sūta…', lang) : tr('Verificēt', lang)}
        </button>}
      </div>
      {sent && !verified && (
        <>
          <div style={{ display: 'flex', gap: 8, alignItems: 'stretch', marginTop: 8 }}>
            <input className="input tnum" style={{ flex: 1, letterSpacing: '0.3em', textAlign: 'center' }} type="text" inputMode="numeric" maxLength={6} placeholder="000000" value={code} onChange={(e) => setCode(e.target.value.replace(/\D/g, '').slice(0, 6))} />
            <button className="btn btn-primary" style={{ flex: 'none' }} disabled={busy || code.length !== 6} onClick={confirm}>{tr('Apstiprināt kodu', lang)}</button>
          </div>
          <div style={{ display: 'flex', gap: 8, marginTop: 8 }}>
            <button className="btn btn-secondary btn-sm" disabled={busy || cooldown > 0} onClick={resend}>
              {cooldown > 0 ? tr('Nosūtīt atkārtoti', lang) + ' (' + cooldown + 's)' : tr('Nosūtīt atkārtoti', lang)}
            </button>
            <button className="btn btn-secondary btn-sm" style={{ color: 'var(--muted)' }} disabled={busy} onClick={cancel}>{tr('Atcelt verifikāciju', lang)}</button>
          </div>
        </>
      )}
      {err && <span style={{ fontSize: 12.5, color: 'var(--red)', marginTop: 4 }}>{err}</span>}
      <span style={{ fontSize: 12.5, color: verified ? 'var(--green)' : 'var(--muted)', marginTop: 2 }}>
        {verified
          ? <><Icon d={I.check} size={13} sw={2.4} /> {google ? tr('E-pasts verificēts caur Google.', lang) : tr('E-pasts veiksmīgi verificēts.', lang)}</>
          : sent
          ? tr('Ievadi 6 ciparu kodu, kas nosūtīts uz tavu e-pastu.', lang)
          : tr('Nepieciešams, lai konts būtu pilnībā darbotiesspējīgs.', lang)}
      </span>
    </div>
  );
}

function PhoneVerify({ lang, uid, profile }) {
  const [cc, setCc] = useState((profile && profile.phoneCc) || 'LV');
  const [num, setNum] = useState((profile && profile.phoneNumber) || '');
  const [sent, setSent] = useState(false);
  const [code, setCode] = useState('');
  // Firestore is the source of truth; local flag is a fast fallback.
  const [verified, setVerified] = useState(() => !!((profile && profile.phoneVerified) || getVerify(uid).phone));
  useEffect(() => { if (profile && profile.phoneVerified) setVerified(true); }, [profile && profile.phoneVerified]);
  const opt = PHONE_CODES.find((c) => c[0] === cc) || PHONE_CODES[0];
  return (
    <div className="field">
      <label>{tr('Mobilais tālrunis', lang)}</label>
      <div style={{ display: 'flex', gap: 8, alignItems: 'stretch' }}>
        <div style={{ position: 'relative', flex: 'none' }}>
          <select value={cc} onChange={(e) => { setCc(e.target.value); setSent(false); setVerified(false); }} className="input" style={{ height: '100%', paddingRight: 30, appearance: 'none', cursor: 'pointer', fontVariantEmoji: 'emoji' }} disabled={verified}>
            {PHONE_CODES.map(([code2, flag, dial]) => <option key={code2} value={code2}>{flag} {dial}</option>)}
          </select>
          <span style={{ position: 'absolute', right: 10, top: '50%', transform: 'translateY(-50%)', pointerEvents: 'none', color: 'var(--muted-2)' }}><Icon d={I.chevronR} size={13} style={{ transform: 'rotate(90deg)' }} /></span>
        </div>
        <input className="input" style={{ flex: 1 }} type="tel" inputMode="tel" placeholder={tr('Tālruņa numurs', lang)} value={num} onChange={(e) => { setNum(e.target.value.replace(/[^0-9\s]/g, '')); setSent(false); setVerified(false); }} disabled={verified} />
        {!verified && <button className="btn btn-secondary" style={{ flex: 'none' }} disabled={num.trim().length < 5 || sent} onClick={() => setSent(true)}>
          {sent ? <><Icon d={I.check} size={15} sw={2.4} /> {tr('Nosūtīts', lang)}</> : tr('Verificēt', lang)}
        </button>}
      </div>
      {sent && !verified && (
        <div style={{ display: 'flex', gap: 8, alignItems: 'stretch', marginTop: 8 }}>
          <input className="input tnum" style={{ flex: 1, letterSpacing: '0.3em', textAlign: 'center' }} type="text" inputMode="numeric" maxLength={4} placeholder="0000" value={code} onChange={(e) => setCode(e.target.value.replace(/\D/g, '').slice(0, 4))} />
          <button className="btn btn-primary" style={{ flex: 'none' }} disabled={code.length !== 4} onClick={() => { setVerified(true); setVerifyFlag(uid, 'phone', true); }}>{tr('Apstiprināt kodu', lang)}</button>
        </div>
      )}
      <span style={{ fontSize: 12.5, color: verified ? 'var(--green)' : 'var(--muted)', marginTop: 2 }}>
        {verified
          ? <><Icon d={I.check} size={13} sw={2.4} /> {tr('Tālrunis veiksmīgi verificēts.', lang)}</>
          : sent
          ? tr('Ievadi 4 ciparu kodu, kas nosūtīts uz', lang) + ' ' + opt[2] + ' ' + num.trim() + '.'
          : tr('Nepieciešams, lai konts būtu pilnībā darbotiesspējīgs.', lang)}
      </span>
    </div>
  );
}

function TikTokVerify({ lang, uid, profile }) {
  const T = (s) => tr(s, lang);
  const [verified, setVerified] = useState(!!(profile && profile.tiktok_verified));
  const [ttUser, setTtUser] = useState((profile && profile.tiktok_username) || '');
  const [code, setCode] = useState((profile && profile.tiktok_verification_code) || '');
  const [username, setUsername] = useState('');
  const [busy, setBusy] = useState('');
  const [err, setErr] = useState('');
  const start = async () => {
    setBusy('gen'); setErr('');
    try { const c = window.KlipzyFirebase ? await window.KlipzyFirebase.startTikTokVerification(uid) : 'A7K29P'; setCode(c); } catch (_) { setErr(T('Neizdevās. Mēģini vēlreiz.')); }
    setBusy('');
  };
  const confirm = async () => {
    const handle = username.trim().replace(/^@/, '');
    if (!handle) { setErr(T('Ievadi savu TikTok lietotājvārdu.')); return; }
    setBusy('verify'); setErr('');
    try {
      const res = window.KlipzyFirebase ? await window.KlipzyFirebase.confirmTikTokVerification(uid, handle, code) : { verified: true, username: handle };
      if (res.verified) { setVerified(true); setTtUser(res.username || handle); }
      else setErr(T('Kods netika atrasts tavā TikTok aprakstā. Pārbaudi un mēģini vēlreiz.'));
    } catch (_) { setErr(T('Neizdevās pārbaudīt TikTok profilu. Mēģini vēlreiz.')); }
    setBusy('');
  };
  return (
    <div style={{ border: '1px solid var(--border)', borderRadius: 12, padding: '14px 16px' }}>
      <div className="spread" style={{ marginBottom: (verified || !code) ? 0 : 10 }}>
        <span style={{ fontSize: 14, fontWeight: 600 }}>TikTok</span>
        {verified
          ? <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
              <span className="badge" style={{ background: 'var(--green-tint)', color: 'var(--green)', fontWeight: 560, display: 'inline-flex', alignItems: 'center', gap: 5 }}><Icon d={I.check} size={13} sw={2.6} /> {ttUser ? '@' + ttUser : T('Verificēts')}</span>
              <button className="btn btn-ghost btn-sm" style={{ color: 'var(--red)', padding: 5 }} title={T('Noņemt verificēto kontu')} onClick={async () => { if (window.KlipzyFirebase) await window.KlipzyFirebase.removeSocialVerification(uid, 'tiktok'); setVerified(false); setTtUser(''); setCode(''); }}><Icon d={I.trash} size={15} /></button>
            </span>
          : !code ? <button className="btn btn-secondary btn-sm" style={{ height: 30 }} disabled={busy === 'gen'} onClick={start}>{busy === 'gen' ? T('Ģenerē…') : T('Verificēt')}</button> : null}
      </div>
      {!verified && code && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          <div style={{ background: 'var(--accent-tint)', borderRadius: 10, padding: '12px 14px', fontSize: 13, color: 'var(--accent-700)', lineHeight: 1.5 }}>
            {T('Pievieno šo kodu savam TikTok profila aprakstam (bio). Vari saglabāt esošo tekstu — kodam tikai jāparādās aprakstā.')}
            <div style={{ marginTop: 8, display: 'flex', alignItems: 'center', gap: 8 }}>
              <code className="tnum" style={{ fontSize: 18, fontWeight: 700, letterSpacing: '0.15em', background: '#fff', padding: '4px 12px', borderRadius: 8, color: 'var(--text)' }}>{code}</code>
              <span className="muted" style={{ fontSize: 12 }}>{T('piem.')} “My gaming clips | Verification: {code}”</span>
            </div>
          </div>
          <div style={{ display: 'flex', gap: 8, alignItems: 'stretch' }}>
            <input className="input" style={{ flex: 1 }} placeholder={T('@tavs_tiktok')} value={username} onChange={(e) => setUsername(e.target.value)} />
            <button className="btn btn-primary" style={{ flex: 'none' }} disabled={busy === 'verify' || !username.trim()} onClick={confirm}>{busy === 'verify' ? T('Pārbauda…') : T('Verificēt')}</button>
          </div>
          <button className="btn btn-ghost btn-sm" style={{ alignSelf: 'flex-start', color: 'var(--muted)' }} disabled={!!busy}
            onClick={async () => { setCode(''); setUsername(''); setErr(''); try { if (window.KlipzyFirebase) await window.KlipzyFirebase.cancelSocialVerification(uid, 'tiktok'); } catch (_) {} }}>
            {T('Atcelt verifikāciju')}
          </button>
        </div>
      )}
      {err && <span style={{ fontSize: 12.5, color: 'var(--red)', marginTop: 6, display: 'block' }}>{err}</span>}
    </div>
  );
}

/* Instagram account verification — mirrors TikTok (bio-code ownership check). */
function InstagramVerify({ lang, uid, profile }) {
  const T = (s) => tr(s, lang);
  const [verified, setVerified] = useState(!!(profile && profile.instagram_verified));
  const [igUser, setIgUser] = useState((profile && profile.instagram_username) || '');
  const [code, setCode] = useState((profile && profile.instagram_verification_code) || '');
  const [username, setUsername] = useState('');
  const [busy, setBusy] = useState('');
  const [err, setErr] = useState('');
  const start = async () => {
    setBusy('gen'); setErr('');
    try { const c = window.KlipzyFirebase ? await window.KlipzyFirebase.startInstagramVerification(uid) : 'A7K29P'; setCode(c); } catch (_) { setErr(T('Neizdevās. Mēģini vēlreiz.')); }
    setBusy('');
  };
  const confirm = async () => {
    const handle = username.trim().replace(/^@/, '');
    if (!handle) { setErr(T('Ievadi savu Instagram lietotājvārdu.')); return; }
    setBusy('verify'); setErr('');
    try {
      const res = window.KlipzyFirebase ? await window.KlipzyFirebase.confirmInstagramVerification(uid, handle, code) : { verified: true, username: handle };
      if (res.verified) { setVerified(true); setIgUser(res.username || handle); }
      else if (res.reason === 'no-bio') setErr(T('Neizdevās nolasīt tavu Instagram aprakstu. Pārliecinies, ka profils ir publisks.'));
      else setErr(T('Kods netika atrasts tavā Instagram aprakstā. Pārbaudi un mēģini vēlreiz.') + (res.bioSnippet ? ' (bio: "' + res.bioSnippet + '")' : ''));
    } catch (_) { setErr(T('Neizdevās pārbaudīt Instagram profilu. Mēģini vēlreiz.')); }
    setBusy('');
  };
  return (
    <div style={{ border: '1px solid var(--border)', borderRadius: 12, padding: '14px 16px' }}>
      <div className="spread" style={{ marginBottom: (verified || !code) ? 0 : 10 }}>
        <span style={{ fontSize: 14, fontWeight: 600 }}>Instagram</span>
        {verified
          ? <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
              <span className="badge" style={{ background: 'var(--green-tint)', color: 'var(--green)', fontWeight: 560, display: 'inline-flex', alignItems: 'center', gap: 5 }}><Icon d={I.check} size={13} sw={2.6} /> {igUser ? '@' + igUser : T('Verificēts')}</span>
              <button className="btn btn-ghost btn-sm" style={{ color: 'var(--red)', padding: 5 }} title={T('Noņemt verificēto kontu')} onClick={async () => { if (window.KlipzyFirebase) await window.KlipzyFirebase.removeSocialVerification(uid, 'instagram'); setVerified(false); setIgUser(''); setCode(''); }}><Icon d={I.trash} size={15} /></button>
            </span>
          : !code ? <button className="btn btn-secondary btn-sm" style={{ height: 30 }} disabled={busy === 'gen'} onClick={start}>{busy === 'gen' ? T('Ģenerē…') : T('Verificēt')}</button> : null}
      </div>
      {!verified && code && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          <div style={{ background: 'var(--accent-tint)', borderRadius: 10, padding: '12px 14px', fontSize: 13, color: 'var(--accent-700)', lineHeight: 1.5 }}>
            {T('Pievieno šo kodu savam Instagram profila aprakstam (bio). Vari saglabāt esošo tekstu — kodam tikai jāparādās aprakstā.')}
            <div style={{ marginTop: 8, display: 'flex', alignItems: 'center', gap: 8 }}>
              <code className="tnum" style={{ fontSize: 18, fontWeight: 700, letterSpacing: '0.15em', background: '#fff', padding: '4px 12px', borderRadius: 8, color: 'var(--text)' }}>{code}</code>
              <span className="muted" style={{ fontSize: 12 }}>{T('piem.')} “My gaming clips | Verification: {code}”</span>
            </div>
          </div>
          <div style={{ display: 'flex', gap: 8, alignItems: 'stretch' }}>
            <input className="input" style={{ flex: 1 }} placeholder={T('@tavs_instagram')} value={username} onChange={(e) => setUsername(e.target.value)} />
            <button className="btn btn-primary" style={{ flex: 'none' }} disabled={busy === 'verify' || !username.trim()} onClick={confirm}>{busy === 'verify' ? T('Pārbauda…') : T('Verificēt')}</button>
          </div>
          <button className="btn btn-ghost btn-sm" style={{ alignSelf: 'flex-start', color: 'var(--muted)' }} disabled={!!busy}
            onClick={async () => { setCode(''); setUsername(''); setErr(''); try { if (window.KlipzyFirebase) await window.KlipzyFirebase.cancelSocialVerification(uid, 'instagram'); } catch (_) {} }}>
            {T('Atcelt verifikāciju')}
          </button>
        </div>
      )}
      {err && <span style={{ fontSize: 12.5, color: 'var(--red)', marginTop: 6, display: 'block' }}>{err}</span>}
    </div>
  );
}

/* Not-yet-implemented social verification box (YouTube). */
function SocialVerifyStub({ name, lang }) {
  const [pending, setPending] = useState(false);
  return (
    <div style={{ border: '1px solid var(--border)', borderRadius: 12, padding: '14px 16px' }}>
      <div className="spread">
        <span style={{ fontSize: 14, fontWeight: 600 }}>{name}</span>
        <button className="btn btn-secondary btn-sm" disabled={pending} onClick={() => setPending(true)}>{tr('Verificēt', lang)}</button>
      </div>
      {pending && <span className="muted" style={{ fontSize: 12.5, marginTop: 8, display: 'block' }}>{tr('Šī platforma drīzumā būs pieejama verifikācijai.', lang)}</span>}
    </div>
  );
}

function ProfilePhoto({ lang, uid, profile, role }) {
  const T = (s) => tr(s, lang);
  const [url, setUrl] = useState((profile && profile.photoURL) || '');
  const [path, setPath] = useState((profile && profile.photoPath) || '');
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState('');
  const inputRef = React.useRef(null);
  useEffect(() => { if (profile && profile.photoURL) { setUrl(profile.photoURL); setPath(profile.photoPath || ''); } }, [profile && profile.photoURL]);
  const pick = async (e) => {
    const file = e.target.files && e.target.files[0];
    e.target.value = '';
    if (!file) return;
    setErr(''); setBusy(true);
    try {
      const res = await window.KlipzyFirebase.uploadProfilePhoto(uid, file);
      setUrl((res && res.url) || '');
      setPath((res && res.path) || '');
    } catch (ex) {
      const c = (ex && ex.code) || '';
      setErr(c === 'too-large' ? T('Attēls ir par lielu. Maksimālais izmērs 5 MB.')
        : c === 'not-an-image' ? T('Atļauti tikai attēli.')
        : T('Neizdevās augšupielādēt attēlu.'));
    }
    setBusy(false);
  };
  const clear = async () => {
    setBusy(true);
    try { await window.KlipzyFirebase.removeProfilePhoto(uid, path); setUrl(''); setPath(''); } catch (_) {}
    setBusy(false);
  };
  const label = role === 'brand' ? T('Zīmola logo') : T('Profila attēls');
  return (
    <div className="field">
      <label>{label} <span className="muted" style={{ fontWeight: 400 }}>({T('nav obligāti')})</span></label>
      <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
        {url
          ? <img src={url} alt="" style={{ width: 56, height: 56, borderRadius: 12, objectFit: 'cover', flex: 'none', border: '1px solid var(--border)' }} />
          : <div style={{ width: 56, height: 56, borderRadius: 12, background: '#F1F5F9', border: '1px dashed var(--border-strong)', display: 'grid', placeItems: 'center', flex: 'none', color: 'var(--muted-2)' }}><Icon d={I.users} size={22} /></div>}
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
          <button className="btn btn-secondary btn-sm" disabled={busy} onClick={() => inputRef.current && inputRef.current.click()}>
            {busy ? T('Augšupielādē…') : url ? T('Nomainīt') : T('Augšupielādēt')}
          </button>
          {url && <button className="btn btn-ghost btn-sm" style={{ color: 'var(--red)' }} disabled={busy} onClick={clear}>{T('Noņemt')}</button>}
        </div>
        <input ref={inputRef} type="file" accept="image/*" onChange={pick} style={{ display: 'none' }} />
      </div>
      {err
        ? <span style={{ fontSize: 12.5, color: 'var(--red)', marginTop: 4 }}>{err}</span>
        : <span style={{ fontSize: 12.5, color: 'var(--muted)', marginTop: 2 }}>{T('JPG, PNG vai WebP · maks. 5 MB')}</span>}
    </div>
  );
}

function SettingsStub({ title, user, role }) {
  const lang = useLang();
  const profile = (user && user.profile) || {};
  const fbUser = (user && user.user) || {};
  const name = profile.displayName || fbUser.displayName || '';
  const email = profile.email || fbUser.email || '';
  const isAdmin = role === 'admin';
  const uid = (user && user.user && user.user.uid) || null;
  const [delOpen, setDelOpen] = useState(false);
  const nameRef = React.useRef(null);
  const passRef = React.useRef(null);
  const [saving, setSaving] = useState(false);
  const [saved, setSaved] = useState(false);
  const [saveErr, setSaveErr] = useState('');
  const saveChanges = async () => {
    setSaveErr(''); setSaving(true);
    try {
      const displayName = nameRef.current ? nameRef.current.value : undefined;
      const pw = passRef.current ? passRef.current.value : '';
      if (window.KlipzyFirebase && window.KlipzyFirebase.updateProfileFields) {
        await window.KlipzyFirebase.updateProfileFields(uid, { displayName }, pw || undefined);
      }
      if (passRef.current) passRef.current.value = '';
      setSaved(true); setSaving(false);
      setTimeout(() => setSaved(false), 4000);
    } catch (e) {
      setSaving(false);
      setSaveErr(tr('Neizdevās saglabāt izmaiņas. MēĢini vēlreiz.', lang));
    }
  };
  // Deletion guards, computed from the user's own data.
  const { campaigns: brandCamps } = useBrandCampaigns(role === 'brand' ? uid : null);
  const { txns } = useTransactions(role === 'brand' ? uid : null);
  const { clips } = useClipperData(role === 'clipper' ? uid : null);
  const sumT = (t) => txns.filter((x) => x.type === t).reduce((s, x) => s + x.amount, 0);
  const brandAvailable = sumT('deposit') - sumT('cashout') - sumT('reserve') + sumT('refund');
  const activeCampaigns = brandCamps.filter((c) => c.status === 'active' || c.status === 'paused').length;
  const clipperUnwithdrawn = round2((clips || []).reduce((s, c) => s + Math.max(0, (c.paidAmount || 0) - (c.withdrawnAmount || 0)), 0));
  let blockReason = '';
  if (role === 'brand') {
    if (brandAvailable < 0) blockReason = tr('Kontā ir negatīvs atlikums. Vispirms to nokārto.', lang);
    else if (activeCampaigns > 0) blockReason = tr('Tev ir aktīvas vai pauzētas kampaņas. Vispirms tās dzēs.', lang);
    else if (brandAvailable > 0) blockReason = tr('Kontā vēl ir līdzekļi', lang) + ' (' + eur0(brandAvailable) + '). ' + tr('Izņem tos pirms konta dzēšanas.', lang);
  } else if (role === 'clipper') {
    if (clipperUnwithdrawn > 0) blockReason = 'Tev ir neizmaksāti līdzekļi (' + eur(clipperUnwithdrawn) + '). Sazinies ar atbalstu, lai tos izmaksātu pirms konta dzēšanas.';
  }
  const adminPerms = (profile && profile.perms) || {};
  const ADMIN_PERMS = [
    [tr('Lietotāju pārvaldība', lang), tr('Skatīt, apstiprināt un dzēst kontus', lang), true],
    [tr('Kampaņu pārraudzība', lang), tr('Pārraudzīt visas platformas kampaņas', lang), true],
    [tr('Maksājumi', lang), tr('Skatīt un apstrādāt izmaksas', lang), !!adminPerms.payments],
  ];
  return (
    <div className="fade-in">
      <TopBar title={title} subtitle={tr('Konta un profila iestatījumi.', lang)} />
      <div style={{ padding: 32, maxWidth: 980, display: 'flex', flexDirection: 'column', gap: 20 }}>
        <div className="r-settings-grid" style={{ display: 'grid', gridTemplateColumns: isAdmin ? '1fr' : '1.4fr 1fr', gap: 20, alignItems: 'start' }}>
          {/* LEFT — main account information */}
          <div className="card" style={{ padding: 28, display: 'flex', flexDirection: 'column', gap: 18 }}>
            <ProfilePhoto lang={lang} uid={uid} profile={profile} role={role} />
            <div className="field"><label>{tr(role === 'brand' ? 'Nosaukums' : 'Vārds', lang)}</label><input ref={nameRef} className="input" defaultValue={name} placeholder={role === 'brand' ? tr('Zīmola nosaukums', lang) : 'Vārds Uzvārds'} /></div>
            {isAdmin
              ? <div className="field"><label>{tr('E-pasts', lang)}</label><input className="input" defaultValue={email} placeholder="tu@epasts.lv" /></div>
              : <EmailVerify lang={lang} email={email} uid={uid} profile={profile} />}
            <div className="field"><label>{tr('Parole', lang)}</label><input ref={passRef} className="input" type="password" defaultValue="" placeholder={tr('Jauna parole', lang)} /></div>
            {false && <PhoneVerify lang={lang} uid={uid} profile={profile} />}
            {isAdmin && (
              <div className="field">
                <label>{tr('Atļaujas', lang)}</label>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                  {ADMIN_PERMS.map(([t, d, on]) => (
                    <div key={t} style={{ display: 'flex', alignItems: 'center', gap: 12, background: '#F8FAFC', border: '1px solid var(--border)', borderRadius: 10, padding: '11px 14px', opacity: on ? 1 : 0.6 }}>
                      <span style={{ width: 30, height: 30, borderRadius: 8, background: on ? 'var(--green-tint)' : '#F1F5F9', color: on ? 'var(--green)' : 'var(--muted)', display: 'grid', placeItems: 'center', flex: 'none' }}><Icon d={on ? I.check : I.x} size={16} sw={2.4} /></span>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ fontSize: 13.5, fontWeight: 540 }}>{t}</div>
                        <div className="muted" style={{ fontSize: 12.5 }}>{d}</div>
                      </div>
                      <span className="badge" style={{ background: on ? 'var(--green-tint)' : '#F1F5F9', color: on ? 'var(--green)' : 'var(--muted)', fontWeight: 540 }}>{on ? tr('Aktīva', lang) : tr('Izslēgta', lang)}</span>
                    </div>
                  ))}
                </div>
                <span style={{ fontSize: 12.5, color: 'var(--muted)', marginTop: 2 }}>{tr('Atļaujas nosaka sistēma — tās nevar mainīt.', lang)}</span>
              </div>
            )}
            {saveErr && <div style={{ background: '#FEF2F2', border: '1px solid #FECACA', color: '#B91C1C', borderRadius: 'var(--r)', padding: '10px 13px', fontSize: 13 }}>{saveErr}</div>}
            <div style={{ display: 'flex', justifyContent: 'flex-end' }}><button className="btn btn-primary" disabled={saving} onClick={saveChanges}>{saving ? tr('Saglabā…', lang) : tr('Saglabāt izmaiņas', lang)}</button></div>
          </div>

          {/* RIGHT — social media verifications */}
          {role === 'clipper' && (
            <div className="card" style={{ padding: 28, display: 'flex', flexDirection: 'column', gap: 18 }}>
              <div>
                <h3 style={{ fontSize: 15.5 }}>{tr('Sociālo tīklu verifikācija', lang)}</h3>
                <p className="muted" style={{ fontSize: 12.5, marginTop: 3, lineHeight: 1.45 }}>{tr('Verificē savus kontus, lai varētu iesniegt klipus.', lang)}</p>
              </div>
              <TikTokVerify lang={lang} uid={uid} profile={profile} />
              <InstagramVerify lang={lang} uid={uid} profile={profile} />
            </div>
          )}
        </div>

        {!isAdmin && (
          <div className="card" style={{ padding: 24, border: '1px solid #FECACA' }}>
            <h3 style={{ fontSize: 15.5, color: '#B91C1C' }}>{tr('Dzēst kontu', lang)}</h3>
            <p className="muted" style={{ fontSize: 13.5, marginTop: 6, lineHeight: 1.5 }}>{tr('Konta dzēšana ir neatgriezeniska. Visi tavi dati tiks dzēsti.', lang)}</p>
            {blockReason
              ? <div style={{ marginTop: 14, background: 'var(--amber-tint)', border: '1px solid #FDE68A', color: '#92400E', borderRadius: 10, padding: '11px 14px', fontSize: 13 }}>{blockReason}</div>
              : <button className="btn btn-secondary" style={{ marginTop: 14, color: 'var(--red)', borderColor: '#FECACA' }} onClick={() => setDelOpen(true)}><Icon d={I.trash} size={16} /> {tr('Dzēst manu kontu', lang)}</button>}
          </div>
        )}
      </div>
      {delOpen && <DeleteAccountModal onClose={() => setDelOpen(false)} />}
      {saved && (
        <div className="fade-in" style={{ position: 'fixed', right: 24, bottom: 24, zIndex: 120, display: 'flex', alignItems: 'center', gap: 10, background: '#0F172A', color: '#fff', borderRadius: 12, padding: '13px 16px', boxShadow: '0 10px 30px rgba(15,23,42,.28)', fontSize: 14, fontWeight: 540 }}>
          <span style={{ width: 22, height: 22, borderRadius: '50%', background: 'var(--green)', display: 'grid', placeItems: 'center', flex: 'none' }}><Icon d={I.check} size={14} sw={2.6} stroke="#fff" /></span>
          {tr('Izmaiņas saglabātas', lang)}
        </div>
      )}
    </div>
  );
}

function DeleteAccountModal({ onClose }) {
  const lang = useLang();
  const T = (s) => tr(s, lang);
  const [password, setPassword] = useState('');
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState('');
  const submit = async () => {
    if (!password) { setErr(T('Ievadi paroli.')); return; }
    setBusy(true); setErr('');
    try {
      if (window.KlipzyFirebase) await window.KlipzyFirebase.deleteOwnAccount(password);
      // Auth user is gone → the app's auth listener redirects to landing.
      location.hash = '';
    } catch (e) {
      const code = (e && e.code) || '';
      setErr(code.includes('wrong-password') || code.includes('invalid-credential') ? T('Nepareiza parole.') : T('Neizdevās dzēst kontu. Mēģini vēlreiz.'));
      setBusy(false);
    }
  };
  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(15,23,42,.45)', display: 'grid', placeItems: 'center', zIndex: 80, padding: 20 }}>
      <div onClick={(e) => e.stopPropagation()} className="card fade-in" style={{ width: 400, maxWidth: '100%', padding: 26 }}>
        <div style={{ width: 46, height: 46, borderRadius: 12, background: '#FEF2F2', color: 'var(--red)', display: 'grid', placeItems: 'center', marginBottom: 14 }}><Icon d={I.trash} size={22} /></div>
        <h3 style={{ fontSize: 18 }}>{T('Dzēst kontu?')}</h3>
        <p className="muted" style={{ fontSize: 14, marginTop: 6, lineHeight: 1.5 }}>{T('Ievadi savu paroli, lai apstiprinātu. Šī darbība ir neatgriezeniska.')}</p>
        <div style={{ marginTop: 16, display: 'flex', flexDirection: 'column', gap: 12 }}>
          <input className="input" type="password" placeholder={T('Parole')} value={password} onChange={(e) => setPassword(e.target.value)} autoFocus />
          {err && <div style={{ background: '#FEF2F2', border: '1px solid #FECACA', color: '#B91C1C', borderRadius: 'var(--r)', padding: '10px 13px', fontSize: 13.5 }}>{err}</div>}
          <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end' }}>
            <button className="btn btn-secondary" onClick={onClose}>{T('Atcelt')}</button>
            <button className="btn btn-primary" style={{ background: 'var(--red)' }} disabled={busy} onClick={submit}>{busy ? T('Dzēš…') : T('Dzēst kontu')}</button>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ClipperApp, SettingsStub });
