// App — Proton wspiera landing page (redesign 1:1 wg makiety)
const { useState, useEffect, useMemo, useRef, createContext, useContext } = React;

// Kontekst danych — dostępny w każdym komponencie
const DataCtx = createContext(null);
const SelCtx = createContext(null);

// ---------- kontekst wyboru: token (telefon/BaseLinker) lub order_id (online/IdoSell) ----------
const SEL_Q = new URLSearchParams(window.location.search);
// Odrzuć pusty ORAZ niepodstawiony placeholder [iai:...] (async/defer lub podgląd).
// Bez tego wszyscy klienci dostaliby ten sam klucz proton_choice_o_[iai:order_sn]
// i pierwszy wybór pokazałby "Dziękujemy" reszcie. Placeholder → brak kontekstu (mode 'info').
const realId = (v) => { v = (v || '').trim(); return (!v || v.indexOf('[iai:') !== -1) ? '' : v; };
const SEL = {
  token:       realId(SEL_Q.get('token')),
  order_id:    realId(SEL_Q.get('order_id')),
  email:       SEL_Q.get('email') || SEL_Q.get('customer_email') || '',
  order_value: SEL_Q.get('order_value') || SEL_Q.get('value') || '',
  // Tryb TEST: ?konto=1|2|3 wybiera odbiorcę powiadomień (1 Jarosław, 2 Ariana, 3 Marcin).
  // Bez tego W3 wysyła mail #1 zawsze na konto 3.
  konto:       SEL_Q.get('konto') || SEL_Q.get('konto_testowe') || '',
};
SEL.mode = SEL.token ? 'telefon' : (SEL.order_id ? 'online' : 'info');
SEL.key  = SEL.token ? ('proton_choice_t_' + SEL.token)
         : SEL.order_id ? ('proton_choice_o_' + SEL.order_id) : '';

const N8N_CHOICE = {
  telefon: 'https://primary-production-94d6b.up.railway.app/webhook/pw-v2-landing',
  online:  'https://primary-production-94d6b.up.railway.app/webhook/pw-v2-wybor-online',
};

// Zapis wyboru. Telefon → W3 pw-v2-landing; online → W1 pw-v2-wybor-online.
async function submitChoice(campaign) {
  if (SEL.mode === 'info') return { ok: false, status: 'no_context' };
  const konto = SEL.konto ? { konto_testowe: SEL.konto } : {};
  const body = SEL.mode === 'telefon'
    ? { token: SEL.token, campaign_id: campaign.id, ...konto }
    : { order_id: SEL.order_id, campaign_id: campaign.id, customer_email: SEL.email, order_value: SEL.order_value, ...konto };
  const r = await fetch(N8N_CHOICE[SEL.mode], {
    method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body),
  });
  if (!r.ok) throw new Error('HTTP ' + r.status);
  let data = {}; try { data = await r.json(); } catch (e) { data = { status: 'ok' }; }
  const status = data.status || 'ok';
  return { ok: status === 'ok', status };
}

// ---------- helpers ----------
const fmtPln = (n) =>
  n.toLocaleString('pl-PL', { maximumFractionDigits: 0 }) + ' zł';
const fmtNum = (n) => n.toLocaleString('pl-PL');

// ---------- LOADING / ERROR ----------
function LoadingScreen() {
  return (
    <div className="screen">
      <div className="spinner" />
      <p style={{ color: 'var(--gray)', margin: 0 }}>Ładowanie zbiórek…</p>
    </div>
  );
}

function ErrorScreen({ error }) {
  return (
    <div className="screen">
      <p style={{ color: 'var(--red)', margin: 0 }}>
        Nie udało się załadować danych.<br />
        <small style={{ color: 'var(--gray-2)' }}>{error}</small>
      </p>
      <button className="btn-red" style={{ maxWidth: 200 }} onClick={() => window.location.reload()}>
        Spróbuj ponownie
      </button>
    </div>
  );
}

// ---------- HERO ----------
function Hero() {
  return (
    <section className="hero">
      <div className="hero-left">
        <div className="hero-inner">
          <div className="hero-logo">
            <span className="hero-logo-box" aria-hidden="true"></span>
            <img src="uploads/proton-wordmark-white.png" alt="Proton" />
          </div>

          <div className="eyebrow">Dziękujemy za zamówienie</div>
          <h1>Wskaż zbiórkę, której<br/>Proton pomoże dzięki Tobie</h1>
          <p className="hero-lead">
            <em>Wybierz jedną z organizacji</em> poniżej. <em>Nic nie dopłacasz</em>,
            część wartości Twojego zamówienia przekażemy na wybraną zbiórkę.
          </p>

          <a href="#zbiorki" className="btn-hero">Wybierz zbiórkę ↓</a>

          <div className="hero-note">
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none">
              <circle cx="12" cy="12" r="9" stroke="#7E7E7E" strokeWidth="1.6" />
              <path d="M12 7v5l3 2" stroke="#7E7E7E" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" />
            </svg>
            <span>To zajmie mniej niż 10 sekund • <em>wybór jest dobrowolny</em></span>
          </div>
        </div>
      </div>

      <div className="hero-right">
        <img
          src="uploads/hero-collage.png"
          alt="Proton wspiera — kolaż osób, którym pomagamy"
          loading="eager"
        />
      </div>
    </section>
  );
}

// ---------- CAMPAIGN CARD ----------
function CampaignCard({ c, inView }) {
  const { CATEGORIES } = useContext(DataCtx);
  const sel = useContext(SelCtx);
  const [fill, setFill] = useState(0);

  useEffect(() => {
    if (inView) {
      const id = setTimeout(() => setFill(c.pct), 80);
      return () => clearTimeout(id);
    }
  }, [inView, c.pct]);

  const catLabel = (CATEGORIES.find(x => x.id === c.cat)?.label || 'Zbiórka').toUpperCase();

  return (
    <article className="card">
      <div className="card-media">
        <img src={c.img} alt={c.title} loading="lazy" />
      </div>
      <div className="card-body">
        <div className="card-cat">{catLabel}</div>
        <h3 className="card-title">{c.title}</h3>
        {c.short && <p className="card-desc">{c.short}</p>}

        <div className="card-progress">
          <div className="bar"><i style={{ width: fill + '%' }} /></div>
          <div className="amounts">
            <span>{fmtPln(c.raised)} z {fmtPln(c.goal)}</span>
            <span>{c.pct}%</span>
          </div>
        </div>

        <div className="card-actions">
          <a href={`zbiorka?id=${c.id}`} className="btn-outline">Czytaj więcej</a>
          {sel && sel.mode !== 'info' && (
            sel.chosen
              ? <button className="btn-red" disabled style={{ opacity: .55, cursor: 'default' }}>Wybrano</button>
              : <button className="btn-red" onClick={() => sel.openConfirm(c)}>Wybieram</button>
          )}
        </div>
      </div>
    </article>
  );
}

// ---------- AKTYWNE ZBIÓRKI ----------
function CampaignsSection() {
  const { CAMPAIGNS, CATEGORIES } = useContext(DataCtx);
  const [cat, setCat] = useState('all');
  const [inView, setInView] = useState(false);
  const sectionRef = useRef(null);

  useEffect(() => {
    const io = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) { setInView(true); io.disconnect(); }
    }, { threshold: 0.05 });
    if (sectionRef.current) io.observe(sectionRef.current);
    return () => io.disconnect();
  }, []);

  const filtered = useMemo(
    () => (cat === 'all' ? CAMPAIGNS : CAMPAIGNS.filter(c => c.cat === cat)),
    [cat, CAMPAIGNS]
  );

  return (
    <section className="section campaigns" id="zbiorki" ref={sectionRef}>
      <div className="container">
        <h2 className="section-title">Aktywne <em>zbiórki</em></h2>

        <div className="campaigns-sub">
          <img className="wspiera-logo" src="uploads/proton-wspiera-logo-v2.png" alt="Proton wspiera" />
          <span>dzięki Twojemu zamówieniu</span>
        </div>

        <div className="chips">
          {CATEGORIES.map(c => (
            <button
              key={c.id}
              className={'chip' + (cat === c.id ? ' active' : '')}
              onClick={() => setCat(c.id)}
            >
              {c.label}
            </button>
          ))}
        </div>

        <div className="grid">
          {filtered.length === 0 ? (
            <div className="empty">Brak zbiórek w tej kategorii.</div>
          ) : (
            filtered.map(c => <CampaignCard key={c.id} c={c} inView={inView} />)
          )}
        </div>
      </div>
    </section>
  );
}

// ---------- JAK TO DZIAŁA ----------
function HowItWorks() {
  const steps = [
    {
      n: '01',
      title: 'Kupujesz',
      desc: 'Twoje zamówienie w Protonie zostało przyjęte. Część jego wartości czeka na wskazanie zbiórki.',
      icon: (
        <svg width="20" height="20" viewBox="0 0 18 18" fill="none">
          <path d="M4.5 1.5L2.25 4.5V15C2.25 15.3978 2.40804 15.7794 2.68934 16.0607C2.97064 16.342 3.35218 16.5 3.75 16.5H14.25C14.6478 16.5 15.0294 16.342 15.3107 16.0607C15.592 15.7794 15.75 15.3978 15.75 15V4.5L13.5 1.5H4.5Z" stroke="#FF0000" strokeWidth="1.5" />
          <path d="M2.25 4.5H15.75" stroke="#FF0000" strokeWidth="1.5" />
          <path d="M12 7.5C12 8.29565 11.6839 9.05871 11.1213 9.62132C10.5587 10.1839 9.79565 10.5 9 10.5C8.20435 10.5 7.44129 10.1839 6.87868 9.62132C6.31607 9.05871 6 8.29565 6 7.5" stroke="#FF0000" strokeWidth="1.5" />
        </svg>
      ),
    },
    {
      n: '02',
      title: 'Wybierasz zbiórkę po dostawie',
      desc: 'Wybierasz konkretną zbiórkę z listy powyżej. Nic nie dopłacasz, a Proton finansuje całą wpłatę ze swoich środków.',
      icon: (
        <svg width="20" height="20" viewBox="0 0 18 18" fill="none">
          <path d="M15.75 3H2.25V16.5H15.75V3Z" stroke="#FF0000" strokeWidth="1.5" />
          <path d="M12 1.5V4.5" stroke="#FF0000" strokeWidth="1.5" />
          <path d="M6 1.5V4.5" stroke="#FF0000" strokeWidth="1.5" />
          <path d="M2.25 7.5H15.75" stroke="#FF0000" strokeWidth="1.5" />
        </svg>
      ),
    },
    {
      n: '03',
      title: 'Proton przekazuje środki',
      desc: 'Śledzisz na bieżąco, ile razem skierowaliśmy do potrzebujących. Twój wybór ma mierzalny efekt.',
      icon: (
        <svg width="20" height="20" viewBox="0 0 18 18" fill="none">
          <path d="M15.6296 3.45753C15.2465 3.07428 14.7917 2.77026 14.2911 2.56284C13.7905 2.35542 13.254 2.24866 12.7121 2.24866C12.1702 2.24866 11.6337 2.35542 11.1331 2.56284C10.6325 2.77026 10.1777 3.07428 9.7946 3.45753L8.9996 4.25253L8.2046 3.45753C7.43083 2.68376 6.38138 2.24906 5.2871 2.24906C4.19283 2.24906 3.14337 2.68376 2.3696 3.45753C1.59583 4.2313 1.16113 5.28075 1.16113 6.37503C1.16113 7.4693 1.59583 8.51876 2.3696 9.29253L3.1646 10.0875L8.9996 15.9225L14.8346 10.0875L15.6296 9.29253C16.0128 8.90946 16.3169 8.45464 16.5243 7.95404C16.7317 7.45345 16.8385 6.91689 16.8385 6.37503C16.8385 5.83316 16.7317 5.2966 16.5243 4.79601C16.3169 4.29542 16.0128 3.84059 15.6296 3.45753Z" stroke="#FF0000" strokeWidth="1.5" />
        </svg>
      ),
    },
  ];

  return (
    <section className="how" id="jak">
      <h2 className="section-title">Jak to działa?</h2>
      <div className="how-grid">
        {steps.map((s, i) => (
          <div key={s.n} className="how-step">
            <div className="how-num">{s.n}</div>
            <div className="how-head">
              {s.icon}
              <h3>{s.title}</h3>
              {i < steps.length - 1 && (
                <span className="how-arrow" aria-hidden="true">
                  <svg width="36" height="14" viewBox="0 0 36 14" fill="none">
                    <path d="M0 7H32M28 1L34 7L28 13" stroke="#CCCCCC" strokeWidth="1.5" />
                  </svg>
                </span>
              )}
            </div>
            <p>{s.desc}</p>
          </div>
        ))}
      </div>
    </section>
  );
}

// ---------- ZREALIZOWANE ----------
function SuccessStories() {
  const { COMPLETED } = useContext(DataCtx);
  if (!COMPLETED.length) return null;

  return (
    <section className="stories" id="sukcesy">
      <div className="container">
        <div className="stories-head">
          <h2 className="section-title">Zbiórki, które udało się zrealizować razem</h2>
          <p>Każda decyzja klienta Proton trafia do konkretnych ludzi. Tak razem budujemy trwałe zmiany.</p>
        </div>
        <div className="stories-grid">
          {COMPLETED.map(d => (
            <article key={d.id} className="story">
              <div className="story-media">
                <img src={d.img} alt={d.title} loading="lazy" />
                <span className="badge-done">ZREALIZOWANE</span>
              </div>
              <div className="story-body">
                <div className="story-label">Proton wspiera</div>
                <h3 className="story-title">{d.title}</h3>
                {d.story && <p className="story-desc">{d.story}</p>}
              </div>
              <div className="story-foot">
                <div className="raised">Zebrano: <b>{fmtPln(d.raised)}</b></div>
                <a href={`zbiorka?id=${d.id}`} className="btn-outline">Czytaj więcej</a>
              </div>
            </article>
          ))}
        </div>
      </div>
    </section>
  );
}

// ---------- FAQ FORMALNE ----------
function FormalFAQ() {
  const items = [
    {
      q: 'Skąd są środki?',
      a: 'Z budżetu marketingowego operatora programu Proton Wspiera. To Proton finansuje całą wpłatę ze środków własnych.',
    },
    {
      q: 'Czy klient przekazuje pieniądze?',
      a: 'Nie. Klient nie jest darczyńcą — nie przekazuje własnych pieniędzy ani nie powstaje po jego stronie żaden obowiązek podatkowy.',
    },
    {
      q: 'Co dokładnie robi klient?',
      a: 'Pełni rolę współdecydenta — wskazuje organizację pożytku publicznego, do której Proton skieruje część wartości jego zamówienia.',
    },
    {
      q: 'Jak to działa od strony formalnej?',
      a: 'Proton przekazuje darowiznę na rzecz wybranej organizacji pożytku publicznego ze środków własnych, w ramach programu wsparcia społecznego.',
    },
  ];
  const [open, setOpen] = useState(0);

  return (
    <section className="faq">
      <div className="container">
        <h2 className="section-title">Jak to działa od strony formalnej?</h2>
        <div className="faq-list">
          {items.map((it, i) => (
            <div key={i} className={'faq-item' + (open === i ? ' open' : '')}>
              <button className="faq-q" onClick={() => setOpen(open === i ? -1 : i)}>
                <span>{it.q}</span>
                <span className="faq-icon">{open === i ? '×' : '+'}</span>
              </button>
              <div className="faq-a"><p>{it.a}</p></div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ---------- FOOTER ----------
function Footer() {
  return (
    <footer className="footer" id="partnerzy">
      <div className="container">
        <div className="footer-top">
          <div className="footer-addr">
            <img className="footer-logo" src="uploads/proton-logo-white.png" alt="Proton" />
            <p>Olendry małe 28, 98-200 Sieradz</p>
            <p>NIP: 8272279664</p>
            <p>REGON: 382317235</p>
          </div>
          <div className="footer-col">
            <h4>Program</h4>
            <ul>
              <li><a href="#">Raport roczny</a></li>
              <li><a href="zglos-zbiorke.html">Zgłoś zbiórkę</a></li>
              <li><a href="regulamin.html">Regulamin</a></li>
              <li><a href="rodo.html">Klauzula RODO</a></li>
              <li><a href="#">Polityka prywatności</a></li>
            </ul>
          </div>
          <div className="footer-col">
            <h4>Kontakt i pomoc</h4>
            <ul>
              <li><a href="mailto:kontakt@proton-polska.pl">kontakt@proton-polska.pl</a></li>
              <li><a href="tel:+48433070000">+48 43 307 00 00</a></li>
            </ul>
          </div>
        </div>
        <div className="footer-bottom">
          <span>© 2026 PROTON</span>
          <span>Program wsparcia społecznego Proton</span>
        </div>
      </div>
    </footer>
  );
}

// ---------- MODAL POTWIERDZENIA / BANER PODZIĘKOWANIA (inline, bez zależności CSS) ----------
function ConfirmModal({ campaign, onCancel, onConfirm, busy, error }) {
  if (!campaign) return null;
  return (
    <div onClick={onCancel} style={{ position: 'fixed', inset: 0, background: 'rgba(20,15,12,.55)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20, zIndex: 1000 }}>
      <div onClick={(e) => e.stopPropagation()} style={{ background: '#fff', borderRadius: 16, maxWidth: 420, width: '100%', padding: '24px 22px', boxShadow: '0 20px 60px -20px rgba(0,0,0,.4)' }}>
        <h3 style={{ fontSize: 19, fontWeight: 800, color: '#1A1513', marginBottom: 8 }}>Potwierdź wybór</h3>
        <p style={{ fontSize: 14, color: '#4A403C', marginBottom: 4 }}>Wspierasz: <b style={{ color: '#FF0000' }}>{campaign.title}</b></p>
        <p style={{ fontSize: 12.5, color: '#7A6E69', marginBottom: 18 }}>Wybór jest jednorazowy — po potwierdzeniu nie można go zmienić.</p>
        {error && <p style={{ fontSize: 13, color: '#FF0000', marginBottom: 12 }}>{error}</p>}
        <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end' }}>
          <button onClick={onCancel} disabled={busy} style={{ padding: '10px 16px', borderRadius: 0, border: '1px solid #E7E1DD', background: '#fff', color: '#4A403C', fontWeight: 600, cursor: 'pointer' }}>Anuluj</button>
          <button onClick={onConfirm} disabled={busy} style={{ padding: '10px 18px', borderRadius: 0, border: 0, background: '#FF0000', color: '#fff', fontWeight: 700, cursor: 'pointer' }}>{busy ? 'Zapisywanie…' : 'Tak, wybieram'}</button>
        </div>
      </div>
    </div>
  );
}
function ThanksModal({ title, onClose }) {
  useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [onClose]);
  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(20,15,12,.6)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20, zIndex: 1100 }}>
      <div onClick={(e) => e.stopPropagation()} style={{ background: '#fff', borderRadius: 16, maxWidth: 460, width: '100%', padding: '34px 28px 26px', textAlign: 'center', boxShadow: '0 24px 70px -20px rgba(0,0,0,.45)' }}>
        <div style={{ width: 62, height: 62, margin: '0 auto 18px', borderRadius: '50%', background: '#FF0000', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <svg width="30" height="30" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12.5l4.2 4.2L19 6.5" /></svg>
        </div>
        <h3 style={{ fontSize: 24, fontWeight: 900, color: '#1A1513', marginBottom: 14, lineHeight: 1.2 }}>Dziękujemy za Twój wybór!</h3>
        <p style={{ fontSize: 14.5, color: '#4A403C', marginBottom: 6 }}>Twój zakup wraz z <b>Proton wspiera</b> wesprze:</p>
        <p style={{ fontSize: 19, fontWeight: 800, color: '#FF0000', marginBottom: 14, lineHeight: 1.3 }}>{title}</p>
        <p style={{ fontSize: 13.5, color: '#7A6E69', marginBottom: 24, lineHeight: 1.55 }}>Będziemy informować Cię o postępach zbiórki na e-mail. Nic nie dopłacasz — środki przekazuje Proton.</p>
        <button onClick={onClose} style={{ padding: '13px 30px', borderRadius: 0, border: 0, background: '#FF0000', color: '#fff', fontWeight: 700, fontSize: 15, cursor: 'pointer' }}>Zamknij</button>
      </div>
    </div>
  );
}
function ThanksBanner({ title }) {
  return (
    <div style={{ position: 'sticky', top: 0, zIndex: 900, background: '#FF0000', color: '#fff', padding: '12px 18px', textAlign: 'center', fontSize: 14, fontWeight: 600 }}>
      ✓ Dziękujemy za Twój wybór! Twój zakup wesprze: {title}. Będziemy informować Cię o postępach na e-mail.
    </div>
  );
}

// ---------- APP ----------
function App() {
  const [appData, setAppData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error,   setError]   = useState(null);

  // wybór akcji (telefon/online)
  const [confirmC, setConfirmC] = useState(null);
  const [busy,     setBusy]     = useState(false);
  const [chErr,    setChErr]    = useState(null);
  const [chosen,   setChosen]   = useState(null);
  const [thanks,   setThanks]   = useState(null);

  useEffect(() => {
    window.loadProtonData()
      .then(d => { setAppData(d); setLoading(false); })
      .catch(e => { setError(e.message); setLoading(false); });
  }, []);

  useEffect(() => {
    if (loading || error) return;
    return window.subscribeToRealtimeStats((newStats) => {
      setAppData(prev => ({ ...prev, STATS: { ...prev.STATS, ...newStats } }));
    });
  }, [loading, error]);

  // już wybrano dla tego kontekstu? (UX; serwer i tak jest autorytatywny)
  useEffect(() => {
    if (!SEL.key) return;
    try { const v = localStorage.getItem(SEL.key); if (v) setChosen({ title: v }); } catch (e) {}
  }, []);

  const openConfirm = (c) => { if (SEL.mode === 'info') return; setChErr(null); setConfirmC(c); };
  const doConfirm = async () => {
    if (!confirmC) return;
    setBusy(true); setChErr(null);
    try {
      const res = await submitChoice(confirmC);
      if (res.ok) {
        try { localStorage.setItem(SEL.key, confirmC.title); } catch (e) {}
        setChosen({ title: confirmC.title });
        setThanks({ title: confirmC.title });
        setConfirmC(null);
      } else {
        setChErr(
          res.status === 'invalid_token' ? 'Ten link został już wykorzystany lub jest nieprawidłowy.'
          : res.status === 'campaign_unavailable' ? 'Ta zbiórka nie jest już dostępna.'
          : res.status === 'no_context' ? 'Otwórz tę stronę z linku, który otrzymałeś w wiadomości.'
          : 'Nie udało się zapisać wyboru. Spróbuj ponownie.'
        );
      }
    } catch (e) { setChErr('Błąd połączenia. Spróbuj ponownie za chwilę.'); }
    setBusy(false);
  };

  if (loading) return <LoadingScreen />;
  if (error)   return <ErrorScreen error={error} />;

  return (
    <DataCtx.Provider value={appData}>
      <SelCtx.Provider value={{ mode: SEL.mode, openConfirm, chosen: !!chosen }}>
        {chosen && <ThanksBanner title={chosen.title} />}
        <Hero />
        <CampaignsSection />
        <HowItWorks />
        <SuccessStories />
        <FormalFAQ />
        <Footer />
        <ConfirmModal campaign={confirmC} onCancel={() => setConfirmC(null)} onConfirm={doConfirm} busy={busy} error={chErr} />
        {thanks && <ThanksModal title={thanks.title} onClose={() => setThanks(null)} />}
      </SelCtx.Provider>
    </DataCtx.Provider>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
