// Voting.jsx — siatka zdjęć konkursowych i głosowanie.
//
// Układ karty zgodny z makietą: zdjęcie wypełnia górę karty (stałe proporcje,
// object-fit: cover), pod spodem „Autor zdjęcia”, „Miejsce” i „Liczba głosów”,
// a po prawej przycisk ZAGŁOSUJ. Kliknięcie przycisku otwiera modal z polami
// imię (wymagane), miejscowość (wymagana) i e-mail (opcjonalny). Po oddaniu
// głosu licznik przy zdjęciu aktualizuje się bez przeładowania strony.

// Nazwa zdjęcia do etykiet: tytuł, w razie braku miejsce, a ostatecznie numer.
function entryLabel(entry) {
  return entry.title || entry.location || `Zdjęcie nr ${entry.id}`;
}

function entrySubtitle(entry) {
  return [entry.authorName, entry.location].filter(Boolean).join(" · ");
}

// Escape zamyka okno, a strona pod spodem nie przewija się. Rodzic przekazuje
// `onClose` jako nową funkcję przy każdym przerysowaniu (zegar tyka co sekundę),
// więc trzymamy ją w ref — efekt zależy tylko od tego, czy okno jest otwarte.
function useModalBehavior(open, onClose) {
  const onCloseRef = React.useRef(onClose);
  onCloseRef.current = onClose;

  React.useEffect(() => {
    if (!open) return undefined;
    const onKeyDown = (event) => {
      if (event.key === "Escape") onCloseRef.current();
    };
    window.addEventListener("keydown", onKeyDown);
    document.body.style.overflow = "hidden";
    return () => {
      window.removeEventListener("keydown", onKeyDown);
      document.body.style.overflow = "";
    };
  }, [open]);
}

function Lightbox({ entry, onClose }) {
  useModalBehavior(Boolean(entry), onClose);

  if (!entry) return null;

  return (
    <div
      role="dialog"
      aria-modal="true"
      aria-label={`Zdjęcie: ${entryLabel(entry)}`}
      onClick={onClose}
      style={{
        position: "fixed",
        inset: 0,
        zIndex: 120,
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        padding: 20,
        background: "rgba(0,0,0,0.72)",
        backdropFilter: "blur(16px)",
        WebkitBackdropFilter: "blur(16px)",
      }}
    >
      <div
        onClick={(event) => event.stopPropagation()}
        style={{ maxWidth: "min(1100px, 100%)", maxHeight: "100%", display: "flex", flexDirection: "column", gap: 14 }}
      >
        <img
          src={entry.previewUrl}
          alt={entryLabel(entry)}
          style={{
            maxWidth: "100%",
            maxHeight: "72vh",
            objectFit: "contain",
            borderRadius: 18,
            display: "block",
            boxShadow: "0 30px 80px rgba(0,0,0,0.6)",
          }}
        />
        <div style={{
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          gap: 16,
          flexWrap: "wrap",
        }}>
          <div>
            <div style={{ fontSize: 16, fontWeight: 600 }}>{entryLabel(entry)}</div>
            <div style={{ marginTop: 3, fontSize: 13, color: "rgba(255,255,255,0.6)" }}>
              Nr {entry.id}{entrySubtitle(entry) ? ` · ${entrySubtitle(entry)}` : ""}
            </div>
          </div>
          <GlassPill onClick={onClose} style={{ fontSize: 12.5, letterSpacing: "0.12em", textTransform: "uppercase" }}>
            Zamknij
          </GlassPill>
        </div>
      </div>
    </div>
  );
}

function MetaRow({ label, value, mono }) {
  return (
    <div style={{
      fontSize: 13,
      lineHeight: 1.75,
      whiteSpace: "nowrap",
      overflow: "hidden",
      textOverflow: "ellipsis",
    }}>
      <span style={{ fontWeight: 600, color: "rgba(255,255,255,0.95)" }}>{label}:</span>{" "}
      <span style={{
        color: "rgba(255,255,255,0.68)",
        fontFamily: mono ? "'JetBrains Mono', monospace" : undefined,
        fontSize: mono ? 12.5 : undefined,
      }}>
        {value}
      </span>
    </div>
  );
}

function EntryCard({ entry, rank, votingOpen, hasVoted, onVote, onOpen }) {
  const [hover, setHover] = React.useState(false);

  return (
    <article
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        display: "flex",
        flexDirection: "column",
        borderRadius: 20,
        overflow: "hidden",
        background: "rgba(255,255,255,0.06)",
        border: "1px solid rgba(255,255,255,0.12)",
        boxShadow: hover ? "0 22px 50px rgba(0,0,0,0.42)" : "0 10px 30px rgba(0,0,0,0.26)",
        transform: hover ? "translateY(-3px)" : "translateY(0)",
        transition: "transform 260ms cubic-bezier(.2,.9,.3,1.2), box-shadow 260ms ease",
      }}
    >
      <button
        type="button"
        onClick={() => onOpen(entry)}
        aria-label={`Powiększ zdjęcie: ${entryLabel(entry)}`}
        style={{
          position: "relative",
          border: "none",
          padding: 0,
          cursor: "zoom-in",
          background: "rgba(255,255,255,0.04)",
          aspectRatio: "3 / 2",
          overflow: "hidden",
          display: "block",
          width: "100%",
        }}
      >
        {entry.previewUrl ? (
          <img
            src={entry.previewUrl}
            alt={entryLabel(entry)}
            loading="lazy"
            style={{
              width: "100%",
              height: "100%",
              objectFit: "cover",
              display: "block",
              transform: hover ? "scale(1.04)" : "scale(1)",
              transition: "transform 520ms cubic-bezier(.2,.9,.3,1)",
            }}
          />
        ) : (
          <div style={{
            width: "100%",
            height: "100%",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            color: "rgba(255,255,255,0.35)",
          }}>
            <Icon.Camera size={28} />
          </div>
        )}

        {entry.title && (
          <span style={{
            position: "absolute",
            top: 12,
            left: 12,
            maxWidth: "calc(100% - 24px)",
            padding: "5px 10px",
            borderRadius: 999,
            fontFamily: "'JetBrains Mono', monospace",
            fontSize: 10,
            letterSpacing: "0.14em",
            textTransform: "uppercase",
            color: "#fff",
            background: "rgba(0,0,0,0.45)",
            backdropFilter: "blur(10px)",
            whiteSpace: "nowrap",
            overflow: "hidden",
            textOverflow: "ellipsis",
          }}>
            {entry.title}
          </span>
        )}
      </button>

      <div style={{
        padding: "14px 16px 16px",
        display: "flex",
        alignItems: "center",
        gap: 12,
        flex: 1,
      }}>
        <div style={{ flex: 1, minWidth: 0 }}>
          {rank != null ? (
            <div style={{
              fontSize: 13,
              lineHeight: 1.75,
              fontWeight: 700,
              color: rank <= 3 ? "#fff" : "rgba(255,255,255,0.95)",
            }}>
              Miejsce {rank}
            </div>
          ) : (
            <MetaRow label="Nr" value={entry.id} mono />
          )}
          <MetaRow label="Autor zdjęcia" value={entry.authorName || "—"} />
          {entry.location && <MetaRow label="Miejsce" value={entry.location} />}
          <MetaRow label="Liczba głosów" value={formatVotes(entry.votes)} mono />
        </div>

        <GlassPill
          active={hasVoted}
          disabled={hasVoted || !votingOpen}
          onClick={() => onVote(entry)}
          ariaLabel={
            hasVoted
              ? `Oddano głos na zdjęcie: ${entryLabel(entry)}`
              : `Zagłosuj na zdjęcie: ${entryLabel(entry)}`
          }
          style={{
            padding: "11px 16px",
            fontSize: 11.5,
            letterSpacing: "0.12em",
            textTransform: "uppercase",
            minHeight: 40,
            flexShrink: 0,
          }}
        >
          {hasVoted ? (
            <>
              <Icon.Check size={13} />
              Oddano głos
            </>
          ) : (
            "Zagłosuj"
          )}
        </GlassPill>
      </div>
    </article>
  );
}

function VoteModal({ entry, onClose, onVoted }) {
  const [form, setForm] = React.useState(readVoterInfo);
  const [errors, setErrors] = React.useState({});
  const [serverError, setServerError] = React.useState("");
  const [submitting, setSubmitting] = React.useState(false);

  useModalBehavior(Boolean(entry), onClose);

  // Pola wypełniają się zapamiętanymi danymi tylko przy otwarciu okna dla
  // nowego zdjęcia — nigdy w trakcie wpisywania.
  const entryId = entry?.id ?? null;
  React.useEffect(() => {
    if (entryId == null) return;
    setErrors({});
    setServerError("");
    setForm(readVoterInfo());
  }, [entryId]);

  if (!entry) return null;

  const setField = (key, value) => {
    setForm((current) => ({ ...current, [key]: value }));
    setErrors((current) => (current[key] ? { ...current, [key]: undefined } : current));
    setServerError("");
  };

  const validate = () => {
    const next = {};
    if (form.name.trim().length < 2) next.name = "Podaj swoje imię.";
    if (form.place.trim().length < 2) next.place = "Podaj miejscowość.";
    const email = form.email.trim();
    if (email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      next.email = "Podaj poprawny adres e-mail albo zostaw pole puste.";
    }
    setErrors(next);
    return Object.keys(next).length === 0;
  };

  const handleSubmit = async (event) => {
    event.preventDefault();
    if (submitting) return;
    setServerError("");
    if (!validate()) return;

    setSubmitting(true);
    try {
      const fingerprint = await getDeviceFingerprint();
      const response = await fetch("/api/contest-vote", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          entryId: entry.id,
          name: form.name.trim(),
          place: form.place.trim(),
          email: form.email.trim(),
          fingerprint,
        }),
      });
      const payload = await response.json().catch(() => ({}));

      if (response.ok) {
        storeVoterInfo({ name: form.name.trim(), place: form.place.trim(), email: form.email.trim() });
        onVoted(entry.id, payload.votes, payload.myVotes || []);
        onClose();
        return;
      }

      if (response.status === 409) {
        // Serwer już zna ten głos — oznacz zdjęcie jako „oddano głos” także lokalnie.
        onVoted(entry.id, null, payload.myVotes || []);
      }
      setServerError(payload.error || "Nie udało się oddać głosu. Spróbuj ponownie.");
    } catch (_) {
      setServerError("Błąd połączenia. Sprawdź internet i spróbuj ponownie.");
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div
      role="dialog"
      aria-modal="true"
      aria-label={`Zagłosuj na zdjęcie: ${entryLabel(entry)}`}
      onClick={onClose}
      style={{
        position: "fixed",
        inset: 0,
        zIndex: 140,
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        padding: 16,
        background: "rgba(0,0,0,0.7)",
        backdropFilter: "blur(14px)",
        WebkitBackdropFilter: "blur(14px)",
        overflowY: "auto",
      }}
    >
      <div
        onClick={(event) => event.stopPropagation()}
        style={{
          width: "min(440px, 100%)",
          maxHeight: "calc(100vh - 32px)",
          overflowY: "auto",
          borderRadius: 24,
          padding: "26px 24px",
          background: "rgba(20,28,40,0.88)",
          border: "1px solid rgba(255,255,255,0.14)",
          boxShadow: LIQUID_SHADOW + ", 0 30px 80px rgba(0,0,0,0.55)",
          backdropFilter: "blur(40px) saturate(180%)",
          WebkitBackdropFilter: "blur(40px) saturate(180%)",
        }}
      >
        <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 12 }}>
          <div>
            <h3 style={{ margin: 0, fontSize: 20, fontWeight: 700, letterSpacing: "-0.01em" }}>
              Zagłosuj na to zdjęcie
            </h3>
            <p style={{ margin: "6px 0 0", fontSize: 13, lineHeight: 1.5, color: "rgba(255,255,255,0.62)" }}>
              Nr {entry.id}{entry.title ? ` · „${entry.title}”` : ""}{entrySubtitle(entry) ? ` · ${entrySubtitle(entry)}` : ""}
            </p>
          </div>
          <GlassCircle size={36} onClick={onClose} ariaLabel="Zamknij okno głosowania">
            <Icon.Close size={15} />
          </GlassCircle>
        </div>

        <form
          onSubmit={handleSubmit}
          noValidate
          style={{ display: "flex", flexDirection: "column", gap: 16, marginTop: 22 }}
        >
          <TextField
            id="vote-name"
            label="Imię"
            required
            value={form.name}
            onChange={(value) => setField("name", value)}
            placeholder="Jan"
            autoComplete="given-name"
            disabled={submitting}
            error={errors.name}
          />

          <TextField
            id="vote-place"
            label="Miejscowość"
            required
            value={form.place}
            onChange={(value) => setField("place", value)}
            placeholder="np. Nieporęt"
            autoComplete="address-level2"
            disabled={submitting}
            error={errors.place}
          />

          <TextField
            id="vote-email"
            label="Adres e-mail (opcjonalnie)"
            type="email"
            value={form.email}
            onChange={(value) => setField("email", value)}
            placeholder="jan@example.com"
            autoComplete="email"
            disabled={submitting}
            error={errors.email}
          />

          {serverError && (
            <div style={{
              padding: "12px 14px",
              borderRadius: 12,
              fontSize: 13,
              lineHeight: 1.5,
              color: "rgba(255,190,190,0.98)",
              background: "rgba(150,40,40,0.28)",
              border: "1px solid rgba(255,120,120,0.35)",
            }}>
              {serverError}
            </div>
          )}

          <GlassPill
            type="submit"
            active
            disabled={submitting}
            style={{
              width: "100%",
              padding: "15px 24px",
              fontSize: 12.5,
              letterSpacing: "0.18em",
              textTransform: "uppercase",
              fontWeight: 700,
            }}
          >
            {submitting ? "Zapisywanie głosu…" : "Potwierdzam głos"}
          </GlassPill>

          <p style={{
            margin: 0,
            fontSize: 11.5,
            lineHeight: 1.55,
            textAlign: "center",
            color: "rgba(255,255,255,0.42)",
          }}>
            Na jedno zdjęcie można oddać tylko jeden głos.
          </p>
        </form>
      </div>
    </div>
  );
}

// Losowanie Fishera-Yatesa z crypto, żeby każde wejście na stronę dawało
// niezależną, równomierną kolejność.
function shuffleIds(ids) {
  const result = [...ids];
  const random = new Uint32Array(result.length);
  if (window.crypto?.getRandomValues) window.crypto.getRandomValues(random);
  for (let i = result.length - 1; i > 0; i -= 1) {
    const roll = window.crypto?.getRandomValues ? random[i] / 4294967296 : Math.random();
    const j = Math.floor(roll * (i + 1));
    [result[i], result[j]] = [result[j], result[i]];
  }
  return result;
}

// Kolejność ustalana jest raz na wejście: w okresie losowania — tasowana,
// później — tak jak przyszła z API (od największej liczby głosów). Kolejne
// odświeżenia liczników zachowują ułożenie, a nowe zdjęcia trafiają na koniec.
function reconcileOrder(current, entries) {
  const ids = entries.map((entry) => entry.id);
  const present = new Set(ids);
  const kept = current.filter((id) => present.has(id));
  const known = new Set(kept);
  return [...kept, ...ids.filter((id) => !known.has(id))];
}

const SORT_OPTIONS = [
  { value: "random", label: "Kolejność losowa" },
  { value: "votes", label: "Liczba głosów" },
];

function SortSelect({ mode, onChange }) {
  const [focused, setFocused] = React.useState(false);
  return (
    <div style={{
      display: "flex",
      justifyContent: "flex-end",
      alignItems: "center",
      gap: 12,
    }}>
      <label
        htmlFor="sort-mode"
        style={{
          fontFamily: "'JetBrains Mono', monospace",
          fontSize: 11,
          letterSpacing: "0.22em",
          textTransform: "uppercase",
          color: "rgba(255,255,255,0.6)",
          whiteSpace: "nowrap",
        }}
      >
        Sortuj wg:
      </label>
      <select
        id="sort-mode"
        value={mode}
        onChange={(event) => onChange(event.target.value)}
        onFocus={() => setFocused(true)}
        onBlur={() => setFocused(false)}
        style={{
          ...fieldSurface(focused, false),
          width: "auto",
          minWidth: 200,
          padding: "10px 40px 10px 14px",
          fontSize: 14,
          appearance: "none",
          WebkitAppearance: "none",
          cursor: "pointer",
          backgroundImage:
            "linear-gradient(45deg, transparent 50%, rgba(255,255,255,0.6) 50%), linear-gradient(135deg, rgba(255,255,255,0.6) 50%, transparent 50%)",
          backgroundPosition: "calc(100% - 20px) 50%, calc(100% - 14px) 50%",
          backgroundSize: "6px 6px, 6px 6px",
          backgroundRepeat: "no-repeat",
        }}
      >
        {SORT_OPTIONS.map((option) => (
          <option key={option.value} value={option.value} style={{ background: "#11151c" }}>
            {option.label}
          </option>
        ))}
      </select>
    </div>
  );
}

function Voting({ data, votingOpen, shuffleActive }) {
  const [entries, setEntries] = React.useState(data.entries || []);
  const [order, setOrder] = React.useState(() => {
    const ids = (data.entries || []).map((entry) => entry.id);
    return shuffleActive ? shuffleIds(ids) : ids;
  });
  const [voted, setVoted] = React.useState(
    () => new Set([...(data.myVotes || []), ...readStoredVotes(data.edition)])
  );
  const [modalEntry, setModalEntry] = React.useState(null);
  const [lightboxEntry, setLightboxEntry] = React.useState(null);

  // Świeże dane z API (odświeżanie co pół minuty) nadpisują listę, ale lokalna
  // wiedza o oddanych głosach jest dołączana, żeby przyciski się nie cofały.
  React.useEffect(() => {
    setEntries(data.entries || []);
    setOrder((current) => reconcileOrder(current, data.entries || []));
    setVoted((current) =>
      new Set([...current, ...(data.myVotes || []), ...readStoredVotes(data.edition)])
    );
  }, [data]);

  // „random” pokazuje wylosowaną przy wejściu kolejność, „votes” — ranking od
  // największej liczby głosów. W okresie losowania startujemy od losowej,
  // później od rankingu; przełącznik nad siatką pozwala to zmienić w każdej chwili.
  const [sortMode, setSortMode] = React.useState(shuffleActive ? "random" : "votes");

  const byId = new Map(entries.map((entry) => [entry.id, entry]));
  const orderedEntries =
    sortMode === "votes"
      ? [...entries].sort((a, b) => b.votes - a.votes || a.id.localeCompare(b.id))
      : order.map((id) => byId.get(id)).filter(Boolean);

  // W rankingu zamiast numeru zdjęcia pokazujemy miejsce. Zdjęcia z tą samą
  // liczbą głosów dzielą miejsce (1, 2, 2, 4…).
  const rankById = new Map();
  if (sortMode === "votes") {
    orderedEntries.forEach((entry, index) => {
      const previous = orderedEntries[index - 1];
      const rank = previous && previous.votes === entry.votes ? rankById.get(previous.id) : index + 1;
      rankById.set(entry.id, rank);
    });
  }

  const markVoted = (entryId, votes, myVotes) => {
    storeVotedEntry(data.edition, entryId);
    setVoted((current) => new Set([...current, entryId, ...(myVotes || [])]));
    if (typeof votes === "number") {
      setEntries((current) =>
        current.map((item) => (item.id === entryId ? { ...item, votes } : item))
      );
    }
  };

  if (entries.length === 0) {
    return (
      <GlassPanel padding={28} style={{ textAlign: "center" }}>
        <div style={{ opacity: 0.5, marginBottom: 12 }}><Icon.Camera size={28} /></div>
        <h3 style={{ margin: "0 0 8px", fontSize: 19, fontWeight: 700 }}>Zdjęcia pojawią się wkrótce</h3>
        <p style={{ margin: 0, fontSize: 14.5, lineHeight: 1.6, color: "rgba(255,255,255,0.65)" }}>
          Organizator przygotowuje galerię konkursową. Zajrzyj tu za chwilę.
        </p>
      </GlassPanel>
    );
  }

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
      <SortSelect mode={sortMode} onChange={setSortMode} />

      <div className="k-grid">
        {orderedEntries.map((entry) => (
          <EntryCard
            key={entry.id}
            entry={entry}
            rank={rankById.get(entry.id) ?? null}
            votingOpen={votingOpen}
            hasVoted={voted.has(entry.id)}
            onVote={setModalEntry}
            onOpen={setLightboxEntry}
          />
        ))}
      </div>

      <VoteModal
        entry={modalEntry}
        onClose={() => setModalEntry(null)}
        onVoted={markVoted}
      />
      <Lightbox entry={lightboxEntry} onClose={() => setLightboxEntry(null)} />
    </div>
  );
}

Object.assign(window, { EntryCard, Lightbox, MetaRow, VoteModal, Voting });
