// App.jsx — strona główna zegrze.co: przedsprzedaż kalendarza 2027.
//
// Trzy widoki pod jednym index.html (patrz vercel.json):
//   /            okładka i przycisk „Kup kalendarz”
//   /zamow       checkout w czterech krokach (Checkout.jsx)
//   /dziekujemy  potwierdzenie po powrocie z płatności Stripe
// Cena i koszt dostawy przychodzą z /api/calendar-config.

const { useState, useEffect, useCallback } = React;

function readRoute() {
  const path = window.location.pathname.replace(/\/+$/, "") || "/";
  const params = new URLSearchParams(window.location.search);
  if (path === "/zamow") {
    const index = CHECKOUT_STEPS.findIndex((step) => step.id === params.get("krok"));
    return { view: "checkout", step: Math.max(0, index) };
  }
  if (path === "/dziekujemy") return { view: "thanks", sessionId: params.get("session_id") || "" };
  return { view: "landing" };
}

function routeUrl(route) {
  if (route.view === "checkout") return `/zamow?krok=${CHECKOUT_STEPS[route.step].id}`;
  return "/";
}

function Feature({ icon, title, children }) {
  return (
    <div style={{ display: "flex", gap: 12, alignItems: "flex-start" }}>
      <span aria-hidden="true" style={{
        flexShrink: 0, width: 38, height: 38, borderRadius: 12,
        display: "inline-flex", alignItems: "center", justifyContent: "center",
        background: "rgba(255,255,255,0.08)", boxShadow: LIQUID_SHADOW,
      }}>
        {icon}
      </span>
      <span>
        <span style={{ display: "block", fontWeight: 650, fontSize: 14.5 }}>{title}</span>
        <span style={{ display: "block", marginTop: 2, fontSize: 13.5, lineHeight: 1.5, color: "rgba(255,255,255,0.6)" }}>
          {children}
        </span>
      </span>
    </div>
  );
}

function Landing({ config, onBuy }) {
  return (
    <div className="zc-shell" style={{ paddingBottom: 24 }}>
      <header style={{ paddingTop: 32, display: "flex", alignItems: "center", justifyContent: "space-between", gap: 16 }}>
        <a href="/" aria-label="zegrze.co — strona główna">
          <img src="/kalendarz/assets/logo.webp" alt="zegrze.co" style={{
            height: 22, width: "auto", display: "block", filter: "drop-shadow(0 1px 20px rgba(255,255,255,0.22))",
          }}/>
        </a>
        <a href="/konkurs" className="zc-nav-link">Konkurs fotograficzny</a>
      </header>

      <section className="zc-hero">
        <div className="zc-cover-wrap">
          <img
            className="zc-cover"
            src={COVER_SRC}
            width="1414"
            height="1996"
            alt="Okładka kalendarza 2027 Jezioro Zegrzyńskie: dziecko w żółtej kurtce na pontonie patrzy na żaglówki"
          />
        </div>

        <div className="zc-hero-copy">
          <div style={MONO_LABEL}>Przedsprzedaż · Kalendarz 2027</div>
          <h1 className="zc-title">Jezioro Zegrzyńskie 2027</h1>
          <p className="zc-lead">
            Kalendarz ścienny na cały 2027 rok ze zdjęciami Jeziora Zegrzyńskiego.
            Zamów w przedsprzedaży, a wyślemy go prosto do wybranego Paczkomatu.
          </p>

          <div style={{ display: "flex", alignItems: "baseline", gap: 12, flexWrap: "wrap", marginTop: 26 }}>
            <span style={{ fontSize: 40, fontWeight: 700, letterSpacing: "-0.03em" }}>{formatMoney(config.unitAmount)}</span>
            <span style={{ fontSize: 14, color: "rgba(255,255,255,0.6)" }}>
              + dostawa do Paczkomatu {formatMoney(config.shippingAmount)}
            </span>
          </div>

          <div style={{ marginTop: 24, display: "flex", gap: 12, flexWrap: "wrap", alignItems: "center" }}>
            <GlassPill active onClick={onBuy} style={{ ...CTA_STYLE, padding: "16px 34px", fontSize: 16, minHeight: 54 }}>
              Kup kalendarz
            </GlassPill>
            {!config.salesOpen && (
              <span style={{ fontSize: 13, color: "rgba(255,200,120,0.95)" }}>Płatności uruchomimy za chwilę.</span>
            )}
          </div>

          <div className="zc-features">
            <Feature icon={<CalIcon.Locker size={20} />} title="Możliwość dostawy do Twojego Paczkomatu">
              Wybierasz punkt na mapie InPost.
            </Feature>
            <Feature icon={<CalIcon.Card size={20} />} title="Bezpieczna płatność">
              BLIK, karta lub przelew przez Stripe.
            </Feature>
            <Feature icon={<CalIcon.Mail size={20} />} title="Potwierdzenie e-mailem">
              Od razu po opłaceniu zamówienia.
            </Feature>
          </div>
        </div>
      </section>
    </div>
  );
}

function Thanks({ sessionId, onHome }) {
  const [state, setState] = useState({ loading: true, order: null, error: "" });

  useEffect(() => {
    let cancelled = false;
    let attempts = 0;
    const load = async () => {
      try {
        const response = await fetch(`/api/calendar-order?session_id=${encodeURIComponent(sessionId)}`);
        const payload = await response.json();
        if (!response.ok) throw new Error(payload.error || "Nie znaleziono zamówienia.");
        if (cancelled) return;
        setState({ loading: false, order: payload, error: "" });
        if (payload.paid) clearStoredOrder();
        else if (attempts++ < 6) setTimeout(load, 4000);
      } catch (err) {
        if (!cancelled) setState({ loading: false, order: null, error: err.message });
      }
    };
    load();
    return () => { cancelled = true; };
  }, [sessionId]);

  const { loading, order, error } = state;

  return (
    <div className="zc-shell" style={{ paddingTop: 32, paddingBottom: 64, maxWidth: 680 }}>
      <a href="/" aria-label="zegrze.co — strona główna">
        <img src="/kalendarz/assets/logo.webp" alt="zegrze.co" style={{ height: 20, width: "auto", display: "block" }} />
      </a>
      <GlassPanel padding={32} radius={28} style={{ marginTop: 40 }}>
        {loading ? (
          <div style={{ ...MONO_LABEL, textAlign: "center" }}>Sprawdzamy płatność…</div>
        ) : error ? (
          <>
            <h1 style={{ margin: 0, fontSize: 26 }}>Nie znaleźliśmy tego zamówienia</h1>
            <p style={{ color: "rgba(255,255,255,0.7)", lineHeight: 1.6 }}>
              Jeśli płatność się udała, potwierdzenie przyjdzie e-mailem od Stripe.
            </p>
          </>
        ) : (
          <>
            <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
              <span aria-hidden="true" style={{
                width: 48, height: 48, borderRadius: "50%", flexShrink: 0,
                background: order.paid ? "rgba(120,230,160,0.9)" : "rgba(255,205,0,0.9)", color: "#0a0a0a",
                display: "inline-flex", alignItems: "center", justifyContent: "center",
              }}>
                {order.paid ? <Icon.Check size={24} /> : <CalIcon.Calendar size={22} />}
              </span>
              <div>
                <h1 style={{ margin: 0, fontSize: "clamp(24px, 4vw, 30px)", letterSpacing: "-0.02em" }}>
                  {order.paid ? "Dziękujemy za zamówienie!" : "Czekamy na potwierdzenie płatności"}
                </h1>
                <div style={{ ...MONO_LABEL, fontSize: 10, marginTop: 6 }}>Zamówienie nr {order.orderNumber}</div>
              </div>
            </div>
            <p style={{ margin: "22px 0 0", fontSize: 15, lineHeight: 1.65, color: "rgba(255,255,255,0.78)" }}>
              {order.paid
                ? <>Potwierdzenie płatności wysłaliśmy na <strong>{order.email}</strong>. Gdy kalendarz wyruszy do Paczkomatu, InPost wyśle Ci SMS i e-mail z kodem odbioru.</>
                : <>Płatność jeszcze się przetwarza. Gdy bank ją potwierdzi, dostaniesz e-mail na <strong>{order.email}</strong>.</>}
            </p>
            <div style={{ display: "grid", gap: 0, marginTop: 22 }}>
              <div className="zc-summary-row zc-summary-row--static">
                <div style={{ ...MONO_LABEL, fontSize: 10 }}>Kalendarze</div>
                <div>{order.qty} szt.</div>
              </div>
              <div className="zc-summary-row zc-summary-row--static">
                <div style={{ ...MONO_LABEL, fontSize: 10 }}>Paczkomat</div>
                <div>
                  {order.locker.code}
                  {order.locker.address && <><br/><span style={{ color: "rgba(255,255,255,0.65)" }}>{order.locker.address}</span></>}
                </div>
              </div>
              <div className="zc-summary-row zc-summary-row--static">
                <div style={{ ...MONO_LABEL, fontSize: 10 }}>Zapłacono</div>
                <div>{formatMoney(order.amountTotal)}</div>
              </div>
            </div>
          </>
        )}
        <div style={{ marginTop: 28 }}>
          <GlassPill onClick={onHome}>Wróć na stronę główną</GlassPill>
        </div>
      </GlassPanel>
    </div>
  );
}

function App() {
  const [route, setRoute] = useState(readRoute);
  const [config, setConfig] = useState(FALLBACK_CONFIG);

  useEffect(() => {
    fetch("/api/calendar-config")
      .then((response) => (response.ok ? response.json() : null))
      .then((payload) => payload && setConfig({ ...FALLBACK_CONFIG, ...payload }))
      .catch(() => {});
  }, []);

  useEffect(() => {
    const onPop = () => setRoute(readRoute());
    window.addEventListener("popstate", onPop);
    return () => window.removeEventListener("popstate", onPop);
  }, []);

  const navigate = useCallback((nextRoute, { replace = false } = {}) => {
    const url = routeUrl(nextRoute);
    if (replace) window.history.replaceState(null, "", url);
    else window.history.pushState(null, "", url);
    setRoute(nextRoute);
    if (nextRoute.view !== "checkout") window.scrollTo({ top: 0 });
  }, []);

  const goToStep = useCallback(
    (step, options) => navigate({ view: "checkout", step }, options),
    [navigate]
  );
  const openCheckout = useCallback(() => goToStep(0), [goToStep]);
  const goHome = useCallback(() => navigate({ view: "landing" }), [navigate]);

  return (
    <div style={{ position: "relative", minHeight: "100vh" }}>
      <Backdrop />
      <main style={{ position: "relative", zIndex: 1 }}>
        {route.view === "checkout" && (
          <Checkout config={config} step={route.step} onStep={goToStep} onExit={goHome} />
        )}
        {route.view === "thanks" && <Thanks sessionId={route.sessionId} onHome={goHome} />}
        {route.view === "landing" && <Landing config={config} onBuy={openCheckout} />}
      </main>

      <footer className="zc-shell zc-footer">
        <span>© {new Date().getFullYear()} zegrze.co</span>
        <span>
          Stronę wykonał{" "}
          <a href="https://vantamedia.pl" target="_blank" rel="noopener noreferrer">VantaMedia.pl</a>
        </span>
      </footer>
    </div>
  );
}

window.App = App;
