/* Klipzy.lv — Marketplace + Campaign detail */
const platName = (p) => String(p || '').replace(/\s*reels?/i, '').replace(/\s*shorts?/i, '').replace(/^youtube$/i, 'YouTube').trim() || p;
const ALL_PLATFORMS = ['TikTok', 'Instagram', 'YouTube'];
const ALL_NICHES = ['Spēles', 'Sports', 'Izklaide', 'Tehnoloģijas', 'Pārtika', 'Finanses'];

function Marketplace({ go }) {
  const lang = useLang();
  const T = (s) => tr(s, lang);
  const { campaigns, loading } = useCampaigns();
  const [q, setQ] = useState('');
  const [plats, setPlats] = useState([]);
  const [niches, setNiches] = useState([]);
  const [minRate, setMinRate] = useState(0);
  const [sort, setSort] = useState('rate');
  const [filtersOpen, setFiltersOpen] = useState(false);

  const toggle = (arr, set, v) => set(arr.includes(v) ? arr.filter((x) => x !== v) : [...arr, v]);

  const filtered = useMemo(() => {
    let list = campaigns.filter((c) => {
      if (q && !(c.brand + ' ' + c.product + ' ' + c.niche).toLowerCase().includes(q.toLowerCase())) return false;
      if (plats.length && !c.platforms.some((p) => plats.includes(platName(p)))) return false;
      if (niches.length && !niches.includes(c.niche) && !niches.includes(c.niche2)) return false;
      if (c.rate < minRate) return false;
      return true;
    });
    list = [...list].sort((a, b) => {
      if (sort === 'rate') return b.rate - a.rate;
      if (sort === 'budget') return (b.budget - b.spent) - (a.budget - a.spent);
      if (sort === 'deadline') return (a.daysLeft ?? 1e9) - (b.daysLeft ?? 1e9);
      return 0;
    });
    return list;
  }, [campaigns, q, plats, niches, minRate, sort]);

  const activeFilters = plats.length + niches.length + (minRate > 0 ? 1 : 0);

  return (
    <div className="app-scroll fade-in" style={{ height: '100%' }}>
      <PublicNav go={go} route="marketplace" lang={lang} />
      <div className="container" style={{ padding: '36px 28px 60px' }}>
        <div style={{ marginBottom: 26 }}>
          <h1 style={{ fontSize: 30, letterSpacing: '-0.03em' }}>{T('Kampaņas')}</h1>
          <p className="muted" style={{ fontSize: 15.5, marginTop: 6 }}>{T('Atrodi kampaņu, izveido klipu un pelni par skatījumiem.')}</p>
        </div>

        {/* search */}
        <div className="mkt-searchrow" style={{ display: 'flex', gap: 12, marginBottom: 22 }}>
          <div style={{ position: 'relative', flex: 1 }}>
            <span style={{ position: 'absolute', left: 14, top: '50%', transform: 'translateY(-50%)', color: 'var(--muted-2)' }}><Icon d={I.search} size={18} /></span>
            <input className="input" style={{ paddingLeft: 42, height: 46 }} placeholder={T('Meklēt zīmolu, produktu vai nišu…')} value={q} onChange={(e) => setQ(e.target.value)} />
          </div>
          <div className="sortpills" style={{ display: 'inline-flex', gap: 3, padding: 4, background: '#F1F5F9', border: '1px solid var(--border)', borderRadius: 12, minHeight: 46, alignItems: 'center', flexWrap: 'wrap' }}>
            {[['rate', T('Augstākā cena')], ['budget', T('Lielākais budžets')], ['deadline', T('Drīz beidzas')]].map(([k, label]) => (
              <button key={k} onClick={() => setSort(k)} style={{ height: 38, padding: '0 14px', borderRadius: 9, border: 'none', cursor: 'pointer', fontSize: 13, fontWeight: 560, whiteSpace: 'nowrap', background: sort === k ? '#fff' : 'transparent', color: sort === k ? 'var(--accent-700)' : 'var(--text-2)', boxShadow: sort === k ? 'var(--sh-sm)' : 'none' }}>{label}</button>
            ))}
          </div>
        </div>

        <div className="r-rail" style={{ display: 'grid', gridTemplateColumns: '248px 1fr', gap: 28, alignItems: 'start' }}>
          {/* FILTER RAIL */}
          <div className="card r-rail-sticky r-filter-rail" style={{ padding: 20, position: 'sticky', top: 84 }}>
            <div className="spread r-filter-head" style={{ marginBottom: 16 }}>
              <button className="r-filter-toggle" onClick={() => setFiltersOpen((o) => !o)} style={{ background: 'none', border: 'none', padding: 0, font: 'inherit', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 8, fontWeight: 600, fontSize: 15 }}>
                {T('Filtri')}{activeFilters > 0 ? ' (' + activeFilters + ')' : ''}
                <span className="r-filter-caret" style={{ display: 'none' }}><Icon d={filtersOpen ? I.arrowUp : I.arrowDown} size={15} /></span>
              </button>
              {activeFilters > 0 && <button className="btn btn-ghost btn-sm" style={{ color: 'var(--accent-700)', padding: '0 6px' }} onClick={() => { setPlats([]); setNiches([]); setMinRate(0); }}>{T('Notīrīt')}</button>}
            </div>

            <div className={'r-filter-body' + (filtersOpen ? ' open' : '')}>
            <FilterGroup label={T('Platforma')}>
              {ALL_PLATFORMS.map((p) => (
                <CheckRow key={p} checked={plats.includes(p)} onClick={() => toggle(plats, setPlats, p)} label={p} />
              ))}
            </FilterGroup>

            <FilterGroup label={T('Niša')}>
              {ALL_NICHES.map((n) => (
                <CheckRow key={n} checked={niches.includes(n)} onClick={() => toggle(niches, setNiches, n)} label={T(n)} />
              ))}
            </FilterGroup>

            <FilterGroup label={T('Min. cena / 1000')} last>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <input type="range" min="0" max="6" step="0.1" value={minRate} onChange={(e) => setMinRate(+e.target.value)} style={{ flex: 1, accentColor: 'var(--accent)' }} />
                <div style={{ display: 'inline-flex', alignItems: 'center', gap: 3, border: '1px solid var(--border-strong)', borderRadius: 8, padding: '0 10px', height: 30, minWidth: 78 }}>
                  <span style={{ fontSize: 13, color: 'var(--muted)' }}>€</span>
                  <input type="number" min="0" max="6" step="0.1" value={minRate.toFixed(2)} onChange={(e) => setMinRate(Math.min(6, Math.max(0, +e.target.value || 0)))} style={{ width: 52, border: 'none', outline: 'none', background: 'none', fontSize: 13, fontWeight: 560, padding: 0, textAlign: 'right', fontFamily: 'inherit' }} />
                </div>
              </div>
            </FilterGroup>
            </div>
          </div>

          {/* GRID */}
          <div>
            <div className="spread" style={{ marginBottom: 16 }}>
              <span className="muted" style={{ fontSize: 14 }}><strong style={{ color: 'var(--text)' }}>{filtered.length}</strong> {filtered.length === 1 ? T('kampaņa') : T('kampaņas')}</span>
            </div>
            {loading ? (
              <div className="card" style={{ padding: 60, textAlign: 'center' }}>
                <div className="muted" style={{ fontSize: 14 }}>{T('Ielādē kampaņas…')}</div>
              </div>
            ) : filtered.length === 0 ? (
              <div className="card" style={{ padding: 60, textAlign: 'center' }}>
                <div style={{ color: 'var(--muted-2)', marginBottom: 10 }}><Icon d={I.search} size={32} /></div>
                <div style={{ fontWeight: 560 }}>{T('Nav atrasta neviena kampaņa')}</div>
                <p className="muted" style={{ fontSize: 14, marginTop: 6 }}>{T('Pamēģini mainīt filtrus vai meklēšanas vaicājumu.')}</p>
              </div>
            ) : (
              <div className="r-grid2" style={{ display: 'grid', gridTemplateColumns: 'repeat(2,1fr)', gap: 20 }}>
                {filtered.map((c) => <CampaignCard key={c.id} c={c} go={go} lang={lang} />)}
              </div>
            )}
          </div>
        </div>
      </div>
      <Footer go={go} lang={lang} />
    </div>
  );
}

function FilterGroup({ label, children, last }) {
  return (
    <div style={{ paddingBottom: last ? 0 : 16, marginBottom: last ? 0 : 16, borderBottom: last ? 'none' : '1px solid var(--border)' }}>
      <div className="eyebrow" style={{ marginBottom: 11 }}>{label}</div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 3 }}>{children}</div>
    </div>
  );
}
function CheckRow({ checked, onClick, label }) {
  return (
    <button onClick={onClick} style={{ display: 'flex', alignItems: 'center', gap: 10, background: 'none', border: 'none', padding: '5px 0', cursor: 'pointer', textAlign: 'left' }}>
      <span style={{
        width: 18, height: 18, borderRadius: 5, border: '1.5px solid ' + (checked ? 'var(--accent)' : 'var(--border-strong)'),
        background: checked ? 'var(--accent)' : '#fff', display: 'grid', placeItems: 'center', flex: 'none', transition: 'all .12s',
      }}>{checked && <Icon d={I.check} size={12} stroke="#fff" sw={2.6} />}</span>
      <span style={{ fontSize: 13.5, color: 'var(--text-2)', fontWeight: 500 }}>{label}</span>
    </button>
  );
}

/* ============ CAMPAIGN DETAIL ============ */
function CampaignDetail({ go, params, user }) {
  const lang = useLang();
  const T = (s) => tr(s, lang);
  const [shared, setShared] = useState(false);
  const [shareOpen, setShareOpen] = useState(false);
  const [assetModal, setAssetModal] = useState(null);
  const downloadFile = async (url, name) => {
    try {
      const res = await fetch(url); const blob = await res.blob();
      const a = document.createElement('a'); const obj = URL.createObjectURL(blob);
      a.href = obj; a.download = name || 'fails'; document.body.appendChild(a); a.click();
      a.remove(); setTimeout(() => URL.revokeObjectURL(obj), 4000);
    } catch (_) { window.open(url, '_blank', 'noopener'); }
  };
  useEffect(() => {
    if (!assetModal) return;
    const sc = document.querySelector('.app-scroll');
    const prev = sc ? sc.style.overflow : '';
    if (sc) sc.style.overflow = 'hidden';
    return () => { if (sc) sc.style.overflow = prev; };
  }, [assetModal]);
  useEffect(() => {
    if (!shareOpen) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    const scs = document.querySelectorAll('.app-scroll'); const saved = [];
    scs.forEach((el) => { saved.push([el, el.style.overflow]); el.style.overflow = 'hidden'; });
    return () => { document.body.style.overflow = prev; saved.forEach(([el, v]) => { el.style.overflow = v; }); };
  }, [shareOpen]);
  const { campaigns, loading } = useCampaigns();
  const c = campaigns.find((x) => x.id === params.id || (params.slug && x.slug === params.slug));
  if (loading) {
    return (<div className="app-scroll fade-in" style={{ height: '100%' }}><PublicNav go={go} route="marketplace" lang={lang} /><div className="container" style={{ padding: 60, textAlign: 'center' }}><span className="muted">{T('Ielādē…')}</span></div></div>);
  }
  if (!c) {
    return (<div className="app-scroll fade-in" style={{ height: '100%' }}><PublicNav go={go} route="marketplace" lang={lang} /><div className="container" style={{ padding: '40px 28px', textAlign: 'center' }}><h2 style={{ fontSize: 22 }}>{T('Kampaņa nav atrasta')}</h2><button className="btn btn-secondary" style={{ marginTop: 16 }} onClick={() => go('marketplace')}>{T('Visas kampaņas')}</button></div><Footer go={go} /></div>);
  }
  const K = window.KLIPZY;
  const remaining = c.budget - c.spent;
  // Example earnings: show the maximum a single clip can make on this campaign
  // (the per-clip cap when set, otherwise the earnings at 500k views).
  const at500k = Math.round((500000 / 1000) * c.rate * 100) / 100;
  const example = c.maxPerClip > 0 ? Math.min(c.maxPerClip, at500k) : at500k;
  const exampleViews = c.rate > 0 ? Math.round((example / c.rate) * 1000) : 500000;
  const role = user && user.profile && user.profile.role;
  const uid = user && user.user && user.user.uid;
  // A clipper can join only if they can post on at least one of the campaign's
  // platforms: YouTube is automatic; TikTok/Instagram require verification.
  const prof = (user && user.profile) || {};
  const canUsePlatform = (p) => {
    const cn = platName(p).toLowerCase();
    if (cn.includes('tiktok')) return !!prof.tiktok_verified;
    if (cn.includes('instagram')) return !!prof.instagram_verified;
    return true; // youtube
  };
  const eligible = !role || role !== 'clipper' || (c.platforms || []).some(canUsePlatform);
  const join = async () => {
    if (!uid) { go('auth', { mode: 'register' }); return; }
    if (role && role !== 'clipper') { go(homeForRole(role), { tab: 'panel' }); return; }
    if (!eligible) return;
    try { if (window.KlipzyFirebase) await window.KlipzyFirebase.joinCampaign(uid, c.id); } catch (_) {}
    go('clipper', { tab: 'campaigns', joined: c.brand });
  };

  return (
    <div className="app-scroll fade-in" style={{ height: '100%' }}>
      <PublicNav go={go} route="marketplace" lang={lang} />
      <div className="container" style={{ padding: '24px 28px 64px' }}>
        <button className="btn btn-ghost btn-sm" style={{ marginBottom: 18, paddingLeft: 6, color: 'var(--muted)' }} onClick={() => go('marketplace')}><Icon d={I.arrowL} size={16} /> {T('Visas kampaņas')}</button>

        <div className="r-rail" style={{ display: 'grid', gridTemplateColumns: '3fr 1fr', gap: 32, alignItems: 'start' }}>
          {/* LEFT — campaign (3/4) */}
          <div>
            {/* header */}
            <div style={{ marginBottom: 24 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap', marginBottom: 8 }}>
                <span className="pill pill-niche">{T(c.niche)}</span>
                {c.niche2 && <span className="pill pill-niche">{T(c.niche2)}</span>}
                {c.platforms.map((p) => <span key={p} className="pill" style={{ height: 26, fontSize: 12 }}>{platName(p)}</span>)}
              </div>
              <h1 style={{ fontSize: 30, letterSpacing: '-0.03em' }}>{c.name || c.product}</h1>
              <p className="muted" style={{ fontSize: 15, marginTop: 5 }}>{c.brand}{c.tagline ? ' · ' + c.tagline : ''}</p>
            </div>

            {/* campaign facts band */}
            <div className="card" style={{ padding: 20, marginBottom: 26 }}>
              <div className="r-grid4" style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 16 }}>
                <div>
                  <div className="eyebrow" style={{ fontSize: 10 }}>{T('Izmaksa')}</div>
                  <div className="tnum" style={{ fontSize: 22, fontWeight: 600, color: 'var(--accent-700)', marginTop: 4 }}>{eur(c.rate)}</div>
                  <div className="muted" style={{ fontSize: 12 }}>{T('par 1 000 skatījumiem')}</div>
                </div>
                <div>
                  <div className="eyebrow" style={{ fontSize: 10 }}>{T('Min. slieksnis')}</div>
                  <div className="tnum" style={{ fontSize: 22, fontWeight: 600, marginTop: 4 }}>{c.minViews > 0 ? numLv(c.minViews) : '—'}</div>
                  <div className="muted" style={{ fontSize: 12 }}>{c.minViews > 0 ? T('skatījumi izmaksai') : T('no 1 000 skatījumiem')}</div>
                </div>
                <div>
                  <div className="eyebrow" style={{ fontSize: 10 }}>{T('Atlikušais budžets')}</div>
                  <div className="tnum" style={{ fontSize: 22, fontWeight: 600, marginTop: 4 }}>{eur0(remaining)}</div>
                  <div className="muted" style={{ fontSize: 12 }}>{T('no')} {eur0(c.budget)}</div>
                </div>
                <div>
                  <div className="eyebrow" style={{ fontSize: 10 }}>{T('Termiņš')}</div>
                  <div className="tnum" style={{ fontSize: 22, fontWeight: 600, marginTop: 4 }}>{c.daysLeft != null ? c.daysLeft + ' ' + T('d.') : '—'}</div>
                  <div className="muted" style={{ fontSize: 12 }}>{c.deadline}</div>
                </div>
              </div>
              <div style={{ marginTop: 16 }}><Budget spent={c.spent} budget={c.budget} showLabel={false} /></div>
              {c.minViews > 0 && (
                <div style={{ marginTop: 16, display: 'flex', gap: 10, background: 'var(--accent-tint)', borderRadius: 10, padding: '11px 14px', fontSize: 13, color: 'var(--accent-700)', lineHeight: 1.5 }}>
                  <span style={{ flex: 'none', marginTop: 1 }}><Icon d={I.spark} size={16} /></span>
                  <span>{T('Izmaksa sākas, kad klips sasniedz')} <strong className="tnum">{numLv(c.minViews)}</strong> {T('skatījumus — pēc tam tiek izmaksāts par katriem nākamajiem skatījumiem.')}</span>
                </div>
              )}
            </div>

            <Section title={T('Apraksts')}>
              <p style={{ fontSize: 15.5, color: 'var(--text-2)', lineHeight: 1.6 }}>{c.desc}</p>
            </Section>

            <Section title={T('Vadlīnijas')}>
              <div className="r-grid2" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20 }}>
                <GuideList title={T('Ieteicams')} items={c.dos.length ? c.dos : [T('Seko zīmola vadlīnijām.')]} ok />
                <GuideList title={T('Izvairies')} items={c.donts.length ? c.donts : [T('Neizmanto neatļautu saturu.')]} />
              </div>
            </Section>

            <Section title={T('Atļautās platformas')}>
              <div style={{ display: 'flex', gap: 8 }}>
                {c.platforms.map((p) => <span key={p} className="pill pill-accent" style={{ height: 32, fontSize: 13 }}>{platName(p)}</span>)}
              </div>
            </Section>

            <Section title={T('Resursi / Materiāli')}>
              {(() => {
                const links = (c.assetsLinks && c.assetsLinks.length ? c.assetsLinks : (c.assetsLink ? [c.assetsLink] : []));
                const files = (c.assets || []);
                if (!links.length && !files.length) return <div className="muted" style={{ fontSize: 14 }}>{T('Zīmols nav pievienojis materiālus.')}</div>;
                return (
                  <div className="r-grid2" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                    <button className="card" disabled={!files.length} style={{ padding: '18px 16px', display: 'flex', alignItems: 'center', gap: 13, textAlign: 'left', cursor: files.length ? 'pointer' : 'default', opacity: files.length ? 1 : 0.5, border: '1px solid var(--border)', background: 'var(--card)' }} onClick={() => files.length && setAssetModal('files')}>
                      <span style={{ width: 42, height: 42, borderRadius: 11, background: 'var(--accent-tint)', color: 'var(--accent-700)', display: 'grid', placeItems: 'center', flex: 'none' }}><Icon d={I.file} size={20} /></span>
                      <div style={{ minWidth: 0 }}>
                        <div style={{ fontSize: 14.5, fontWeight: 560 }}>{T('Faili')}</div>
                        <div className="muted" style={{ fontSize: 12.5 }}>{files.length} {files.length === 1 ? T('fails') : T('faili')}</div>
                      </div>
                    </button>
                    <button className="card" disabled={!links.length} style={{ padding: '18px 16px', display: 'flex', alignItems: 'center', gap: 13, textAlign: 'left', cursor: links.length ? 'pointer' : 'default', opacity: links.length ? 1 : 0.5, border: '1px solid var(--border)', background: 'var(--card)' }} onClick={() => links.length && setAssetModal('links')}>
                      <span style={{ width: 42, height: 42, borderRadius: 11, background: 'var(--accent-tint)', color: 'var(--accent-700)', display: 'grid', placeItems: 'center', flex: 'none' }}><Icon d={I.link} size={20} /></span>
                      <div style={{ minWidth: 0 }}>
                        <div style={{ fontSize: 14.5, fontWeight: 560 }}>{T('Saites')}</div>
                        <div className="muted" style={{ fontSize: 12.5 }}>{links.length} {links.length === 1 ? T('saite') : T('saites')}</div>
                      </div>
                    </button>
                    {assetModal && ReactDOM.createPortal((
                      <div onClick={() => setAssetModal(null)} style={{ position: 'fixed', inset: 0, zIndex: 200, background: 'rgba(15,23,42,.5)', backdropFilter: 'blur(2px)', display: 'grid', placeItems: 'center', padding: 20 }}>
                        <div className="card" onClick={(e) => e.stopPropagation()} style={{ width: 'min(460px, 100%)', maxHeight: '80vh', overflowY: 'auto', padding: 0 }}>
                          <div className="spread" style={{ padding: '16px 20px', borderBottom: '1px solid var(--border)', position: 'sticky', top: 0, background: 'var(--card)' }}>
                            <h3 style={{ fontSize: 16 }}>{assetModal === 'files' ? T('Faili') : T('Saites')}</h3>
                            <button className="btn btn-ghost btn-sm" style={{ padding: 6 }} onClick={() => setAssetModal(null)}><Icon d={I.x} size={18} /></button>
                          </div>
                          <div style={{ padding: 16, display: 'flex', flexDirection: 'column', gap: 8 }}>
                            {assetModal === 'files' ? files.map((file, i) => (
                              <a key={i} href={file.url} target="_blank" rel="noopener noreferrer" onClick={(e) => { e.preventDefault(); downloadFile(file.url, file.name); }} style={{ padding: '11px 14px', display: 'flex', alignItems: 'center', gap: 12, textDecoration: 'none', border: '1px solid var(--border)', borderRadius: 'var(--r)', cursor: 'pointer' }}>
                                <span style={{ width: 34, height: 34, borderRadius: 9, background: 'var(--accent-tint)', color: 'var(--accent-700)', display: 'grid', placeItems: 'center', flex: 'none' }}><Icon d={I.file} size={16} /></span>
                                <div style={{ flex: 1, minWidth: 0, fontSize: 13.5, fontWeight: 540, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{file.name || T('Materiāls')}</div>
                                <span className="btn btn-secondary btn-sm" style={{ flex: 'none' }}>{T('Lejupielādēt')}</span>
                              </a>
                            )) : links.map((lnk, i) => (
                              <a key={i} href={lnk} target="_blank" rel="noopener noreferrer" style={{ padding: '11px 14px', display: 'flex', alignItems: 'center', gap: 12, textDecoration: 'none', border: '1px solid var(--border)', borderRadius: 'var(--r)' }}>
                                <span style={{ width: 34, height: 34, borderRadius: 9, background: 'var(--accent-tint)', color: 'var(--accent-700)', display: 'grid', placeItems: 'center', flex: 'none' }}><Icon d={I.link} size={16} /></span>
                                <div className="muted" style={{ flex: 1, minWidth: 0, fontSize: 12.5, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{lnk.replace(/^https?:\/\//, '')}</div>
                                <span className="btn btn-secondary btn-sm" style={{ flex: 'none' }}>{T('Atvērt')}</span>
                              </a>
                            ))}
                          </div>
                        </div>
                      </div>
                    ), document.body)}
                  </div>
                );
              })()}
            </Section>

            {(c.exampleClips && c.exampleClips.length > 0) && (
              <Section title={T('Piemēra klipi')} last>
                <div className="r-grid4" style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 12 }}>
                  {c.exampleClips.slice(0, 8).map((ex, i) => (
                    <ExampleClipTile key={ex.url || i} ex={ex} grad={K.thumbGrads[i % K.thumbGrads.length]} />
                  ))}
                </div>
              </Section>
            )}
          </div>

          {/* RIGHT — brand + join (1/4) */}
          <div style={{ position: 'sticky', top: 84, display: 'flex', flexDirection: 'column', gap: 16 }}>
            <button className="btn btn-primary btn-lg btn-block" onClick={join} disabled={!eligible} title={!eligible ? T('Verificē kādu no šīs kampaņas platformām, lai pievienotos.') : undefined} style={!eligible ? { opacity: .5, cursor: 'not-allowed' } : undefined}>{T('Pievienoties kampaņai')}</button>
            {!eligible && <div style={{ display: 'flex', alignItems: 'center', gap: 8, background: 'var(--amber-tint)', border: '1px solid #FDE68A', borderRadius: 10, padding: '10px 13px', fontSize: 12.5, color: '#92400E' }}><Icon d={I.alert} size={15} /> {T('Verificē kādu no šīs kampaņas platformām, lai pievienotos.')}</div>}

            <div className="card" style={{ padding: 22 }}>
              <span className="eyebrow">{T('Par zīmolu')}</span>
              <div style={{ display: 'flex', alignItems: 'center', gap: 13, margin: '14px 0 16px' }}>
                <BrandLogo initials={c.initials} grad={c.grad} src={c.brandLogo} size={52} radius={13} />
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontSize: 16.5, fontWeight: 600 }}>{c.brand}</div>
                  <div className="muted" style={{ fontSize: 13 }}>{T(c.niche)}</div>
                </div>
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
                <div className="spread"><span className="muted" style={{ fontSize: 13.5 }}>{T('Izmaksa')}</span><span className="tnum" style={{ fontWeight: 560, fontSize: 14, color: 'var(--accent-700)' }}>{eur(c.rate)} / 1 000</span></div>
                <div className="spread"><span className="muted" style={{ fontSize: 13.5 }}>{T('Aktīvi klipotāji')}</span><span className="tnum" style={{ fontWeight: 560, fontSize: 14 }}>{c.clippers}</span></div>
                <div className="spread"><span className="muted" style={{ fontSize: 13.5 }}><Icon d={I.calendar} size={14} style={{ verticalAlign: -2, marginRight: 5 }} />{T('Termiņš')}</span><span style={{ fontWeight: 560, fontSize: 14 }}>{c.deadline}</span></div>
              </div>
              <button className="btn btn-primary btn-block" style={{ marginTop: 18 }} onClick={async () => { if (uid && window.KlipzyFirebase) { try { await window.KlipzyFirebase.joinCampaign(uid, c.id); } catch (_) {} } go('clipper', { tab: 'submit', campaignId: c.id }); }}>{T('Iesniegt klipu')}</button>
            </div>

            <button className="btn btn-secondary btn-block" style={{ gap: 8 }} onClick={() => setShareOpen(true)}><Icon d={I.link} size={16} sw={2.2} /> {T('Dalīties ar kampaņu')}</button>

            <div className="card" style={{ padding: 20, background: 'linear-gradient(180deg,#F8FBFF,#fff)', borderColor: 'var(--accent-tint-2)' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
                <span style={{ color: 'var(--accent)' }}><Icon d={I.spark} size={18} /></span>
                <span style={{ fontWeight: 600, fontSize: 14.5 }}>{T('Piemēra ieņēmumi')}</span>
              </div>
              <p style={{ fontSize: 14, color: 'var(--text-2)', lineHeight: 1.5 }}>{c.maxPerClip > 0 && example >= c.maxPerClip
                ? <>{T('Maksimālais, ko var nopelnīt ar vienu klipu')} (<strong className="tnum">{numLv(exampleViews)}</strong> {T('skatījumi')})</>
                : <>{T('Ja tavs klips sasniedz')} <strong>500 000 {T('skatījumus')}</strong>, {T('tu nopelni')}</>}</p>
              <div className="tnum" style={{ fontSize: 28, fontWeight: 600, color: 'var(--accent-700)', marginTop: 6 }}>{eur(example)}</div>
            </div>
          </div>
        </div>
      </div>
      <Footer go={go} lang={lang} />
      {shareOpen && (() => {
        const url = location.origin + (window.KLIPZY_BASE || '/').replace(/\/+$/, '/') + 'kampanas/' + (c.slug || c.id);
        const enc = encodeURIComponent(url);
        const txt = encodeURIComponent(c.brand + ' · Klipzy');
        const links = [
          ['WhatsApp', 'https://wa.me/?text=' + txt + '%20' + enc],
          ['Telegram', 'https://t.me/share/url?url=' + enc + '&text=' + txt],
          ['Facebook', 'https://www.facebook.com/sharer/sharer.php?u=' + enc],
          ['X', 'https://twitter.com/intent/tweet?url=' + enc + '&text=' + txt],
          ['E-pasts', 'mailto:?subject=' + txt + '&body=' + enc],
        ];
        const copy = () => { const done = () => { setShared(true); setTimeout(() => setShared(false), 1600); }; if (navigator.clipboard && navigator.clipboard.writeText) navigator.clipboard.writeText(url).then(done).catch(done); else { const ta = document.createElement('textarea'); ta.value = url; ta.style.position = 'fixed'; ta.style.opacity = '0'; document.body.appendChild(ta); ta.select(); try { document.execCommand('copy'); } catch (_) {} document.body.removeChild(ta); done(); } };
        return (
          <div onClick={() => setShareOpen(false)} style={{ position: 'fixed', inset: 0, zIndex: 300, background: 'rgba(15,23,42,.55)', backdropFilter: 'blur(4px)', WebkitBackdropFilter: 'blur(4px)', display: 'grid', placeItems: 'center', padding: 20 }}>
            <div onClick={(e) => e.stopPropagation()} className="card" style={{ width: 'min(420px,94vw)', padding: 24 }}>
              <div className="spread" style={{ marginBottom: 16 }}>
                <h3 style={{ fontSize: 18 }}>{T('Dalīties ar kampaņu')}</h3>
                <button className="btn btn-ghost btn-sm" style={{ padding: 6 }} onClick={() => setShareOpen(false)}><Icon d={I.x} size={18} /></button>
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2,1fr)', gap: 10, marginBottom: 16 }}>
                {links.map(([name, href]) => (
                  <a key={name} href={href} target="_blank" rel="noopener noreferrer" className="btn btn-secondary" style={{ justifyContent: 'center' }}>{name}</a>
                ))}
              </div>
              <div style={{ display: 'flex', gap: 8, alignItems: 'center', background: '#F8FAFC', border: '1px solid var(--border)', borderRadius: 10, padding: '8px 10px' }}>
                <span className="muted tnum" style={{ flex: 1, minWidth: 0, fontSize: 12.5, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{url}</span>
                <button className="btn btn-primary btn-sm" style={{ gap: 6, flex: 'none' }} onClick={copy}><Icon d={shared ? I.check : I.link} size={15} sw={2.2} /> {shared ? T('Nokopēts') : T('Kopēt')}</button>
              </div>
            </div>
          </div>
        );
      })()}
    </div>
  );
}
function ExampleClipTile({ ex, grad }) {
  const url = String(ex.url || '');
  const ytId = (url.match(/(?:shorts\/|v=|youtu\.be\/|embed\/)([\w-]{6,})/) || [])[1];
  // Instagram/TikTok CDN images are hotlink-blocked and their signed URLs
  // expire, so route them through our own proxy. YouTube is public + stable.
  const initial = ytId
    ? `https://img.youtube.com/vi/${ytId}/hqdefault.jpg`
    : `https://europe-west1-klipzy-225a7.cloudfunctions.net/clipThumb?url=${encodeURIComponent(url)}`;
  const [thumb, setThumb] = React.useState(initial);
  return (
    <a href={url} target="_blank" rel="noopener noreferrer" style={{ textDecoration: 'none', display: 'block' }}>
      <GradTile grad={grad} radius={12} style={{ aspectRatio: '9/16', display: 'grid', placeItems: 'center', position: 'relative', overflow: 'hidden' }}>
        {thumb && <img src={thumb} alt="" loading="lazy" referrerPolicy="no-referrer" onError={() => setThumb('')}
          style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' }} />}
        {thumb && <span style={{ position: 'absolute', inset: 0, background: 'linear-gradient(180deg,rgba(0,0,0,.05),rgba(0,0,0,.45))' }} />}
        <span style={{ position: 'relative', width: 40, height: 40, borderRadius: 999, background: 'rgba(255,255,255,.25)', backdropFilter: 'blur(4px)', display: 'grid', placeItems: 'center', color: '#fff' }}><Icon d={I.play} size={18} fill="#fff" stroke="none" /></span>
        <span style={{ position: 'absolute', left: 8, bottom: 8, background: 'rgba(15,23,42,.6)', color: '#fff', fontSize: 10.5, fontWeight: 600, borderRadius: 999, padding: '2px 8px' }}>
          {PLATFORM_LABEL[ex.platform] || ex.platform || ''}
        </span>
      </GradTile>
    </a>
  );
}

function Section({ title, children, last }) {
  return (
    <div style={{ paddingBottom: last ? 0 : 26, marginBottom: last ? 0 : 26, borderBottom: last ? 'none' : '1px solid var(--border)' }}>
      <h3 style={{ fontSize: 17, marginBottom: 14 }}>{title}</h3>
      {children}
    </div>
  );
}
function GuideList({ title, items, ok }) {
  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 7, marginBottom: 10, fontSize: 13.5, fontWeight: 560, color: ok ? 'var(--green)' : 'var(--red)' }}>
        <Icon d={ok ? I.check : I.x} size={16} sw={2.2} /> {title}
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
        {items.map((it, i) => (
          <div key={i} style={{ display: 'flex', gap: 9, fontSize: 14, color: 'var(--text-2)', lineHeight: 1.45 }}>
            <span style={{ color: ok ? 'var(--green)' : 'var(--muted-2)', flex: 'none', marginTop: 2 }}><Icon d={ok ? I.check : I.x} size={14} sw={2.4} /></span>
            {it}
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { Marketplace, CampaignDetail, ALL_PLATFORMS, ALL_NICHES });
