// Fluchkasse „Fluchen für den guten Zweck“.
// Eigene Seite (Kasse, Spendenziel, Rangliste) und ein Kasten fürs Profil mit
// den gefundenen Kartenteilen. Die Teile haben dieselbe gerissene Form wie im
// OBS-Overlay (gleicher Zufallsstartwert), damit beides gleich aussieht.
const { useState: useFState, useEffect: useFEffect, useMemo: useFMemo } = React;

const FLUCH_PIECES = 50;
const FLUCH_IMAGE = "cards/promo/Promo_C1911_Fluchkasse.webp";

function fluchVisible() {
  return !!((window.FEATURES || {}).fluchkasse || (window.MY_FEATURES || {}).fluchkasse);
}

// Gleiche Berechnung wie im Overlay (fluchkasse.html, formSeed 9419, 5 x 10).
const FLUCH_TEILE = (() => {
  function mulberry32(a) {
    return function () {
      a |= 0; a = a + 0x6D2B79F5 | 0;
      let t = Math.imul(a ^ a >>> 15, 1 | a);
      t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t;
      return ((t ^ t >>> 14) >>> 0) / 4294967296;
    };
  }
  const W = 920, H = 1320, C = 5, R = 10;
  const cw = W / C, rh = H / R, r = mulberry32(9419);
  const V = [];
  for (let y = 0; y <= R; y++) {
    V[y] = [];
    for (let x = 0; x <= C; x++) {
      let px = x * cw, py = y * rh;
      if (x > 0 && x < C) px += (r() - .5) * cw * .24;
      if (y > 0 && y < R) py += (r() - .5) * rh * .24;
      V[y][x] = [px, py];
    }
  }
  function riss(a, b, aussen) {
    if (aussen) return [a, b];
    const n = 18, dx = b[0] - a[0], dy = b[1] - a[1], len = Math.hypot(dx, dy);
    const nx = -dy / len, ny = dx / len, phase = r() * Math.PI * 2, amp = len * .06;
    const pts = [a];
    for (let i = 1; i < n; i++) {
      const t = i / n + (r() - .5) * .45 / n;
      const huelle = Math.sin(t * Math.PI);
      const off = Math.sin(t * Math.PI * 2 + phase) * amp * huelle + (r() - .5) * 11 * Math.min(1, huelle * 3);
      pts.push([a[0] + dx * t + nx * off, a[1] + dy * t + ny * off]);
    }
    pts.push(b);
    return pts;
  }
  const HE = [], VE = [];
  for (let y = 0; y <= R; y++) { HE[y] = []; for (let x = 0; x < C; x++) HE[y][x] = riss(V[y][x], V[y][x + 1], y === 0 || y === R); }
  for (let y = 0; y < R; y++) { VE[y] = []; for (let x = 0; x <= C; x++) VE[y][x] = riss(V[y][x], V[y + 1][x], x === 0 || x === C); }
  const liste = [];
  for (let y = 0; y < R; y++) for (let x = 0; x < C; x++) {
    const pts = [...HE[y][x], ...VE[y][x + 1].slice(1), ...HE[y + 1][x].slice().reverse().slice(1), ...VE[y][x].slice().reverse().slice(1, -1)];
    liste.push("M" + pts.map((p) => p[0].toFixed(1) + " " + p[1].toFixed(1)).join(" L") + " Z");
  }
  return liste;
})();

let fluchUid = 0;

// Die Karte aus Teilen. Fehlende Teile schimmern grau durch.
function FluchPuzzle({ teile, image, width = 200 }) {
  const id = useFMemo(() => "fp" + (++fluchUid), []);
  const has = new Set(teile || []);
  const img = image || FLUCH_IMAGE;
  // Das Bild hat 40 px transparenten Rand (1000 x 1400), sichtbar sind 920 x 1320.
  const picture = (extra) => <image href={img} x="-40" y="-40" width="1000" height="1400" {...extra} />;
  const complete = has.size >= FLUCH_PIECES;
  return (
    <svg className={`fl-puzzle ${complete ? "complete" : ""}`} viewBox="0 0 920 1320" width={width} style={{ height: "auto" }} aria-label={`${has.size} von ${FLUCH_PIECES} Teilen`}>
      <defs>
        <filter id={id + "g"}><feColorMatrix type="saturate" values="0" /></filter>
        <clipPath id={id + "c"}><rect width="920" height="1320" rx="40" /></clipPath>
        <clipPath id={id + "h"}>
          {FLUCH_TEILE.map((d, i) => has.has(i) ? <path key={i} d={d} /> : null)}
        </clipPath>
      </defs>
      <g clipPath={`url(#${id}c)`}>
        <rect width="920" height="1320" fill="#120f1a" />
        {picture({ filter: `url(#${id}g)`, opacity: 0.12 })}
        {has.size > 0 && picture({ clipPath: `url(#${id}h)` })}
        {!complete && FLUCH_TEILE.map((d, i) => has.has(i)
          ? <path key={i} d={d} fill="none" stroke="rgba(255,255,255,.35)" strokeWidth="2.5" strokeLinejoin="round" />
          : <path key={i} d={d} fill="rgba(255,255,255,.03)" stroke="rgba(255,255,255,.16)" strokeWidth="2" strokeDasharray="5 7" strokeLinejoin="round" />)}
      </g>
    </svg>
  );
}

const fluchEuro = (x) => {
  const n = Math.round((Number(x) || 0) * 100) / 100;
  return n.toLocaleString("de-DE", { minimumFractionDigits: n % 1 ? 2 : 0, maximumFractionDigits: 2 }) + " €";
};
const FLUCH_MONTHS = ["Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"];
function fluchMonthKey(d = new Date()) {
  return d.getFullYear() + "-" + String(d.getMonth() + 1).padStart(2, "0");
}

// Kasten fürs Profil (eigenes und fremdes).
function FluchProfileBox({ fluch, own, compact }) {
  if (!fluch || !fluchVisible()) return null;
  const n = (fluch.teile || []).length;
  const pct = Math.round((n / FLUCH_PIECES) * 100);
  const img = (fluch.card && fluch.card.image) || FLUCH_IMAGE;
  return (
    <div className={`fl-box ${compact ? "compact" : ""} ${n >= FLUCH_PIECES ? "done" : ""}`}>
      <FluchPuzzle teile={fluch.teile} image={img} width={compact ? 84 : 132} />
      <div className="fl-box-body">
        <div className="label">Fluchkasse</div>
        <div className="fl-box-count"><b>{n}</b> von {FLUCH_PIECES} Teilen</div>
        <div className="fl-bar"><span style={{ width: pct + "%" }} /></div>
        <div className="fl-box-sub">
          {n >= FLUCH_PIECES
            ? "Karte komplett"
            : fluch.meldungen
              ? `${fluch.meldungen} bestätigte ${fluch.meldungen === 1 ? "Meldung" : "Meldungen"}`
              : own ? "Melde Flüche im Stream mit !fluch" : "Noch keine Meldung"}
        </div>
      </div>
    </div>
  );
}

// Eigene Seite.
function FluchView({ me, onUser }) {
  const [data, setData] = useFState(null);
  useFEffect(() => {
    let alive = true;
    fetch("/api/leaderboard?fluch=1")
      .then((r) => (r.ok ? r.json() : Promise.reject(r)))
      .then((d) => alive && setData(d))
      .catch(() => alive && setData(false));
    return () => { alive = false; };
  }, []);

  if (data === null) return <div className="empty"><h3>Lädt …</h3></div>;
  if (data === false) return <div className="empty"><h3>Die Fluchkasse ist gerade nicht erreichbar</h3><div>Versuch es gleich nochmal.</div></div>;

  const k = data.kasse || {};
  const mk = fluchMonthKey();
  const month = (k.monate || {})[mk] || { betrag: 0, flueche: 0 };
  const monthName = FLUCH_MONTHS[new Date().getMonth()];
  const user = me && me.user;
  const mine = me && me.fluch;
  const img = (data.card && data.card.image) || FLUCH_IMAGE;
  const list = data.sammler || [];

  return (
    <>
      <div className="page-head">
        <div>
          <div className="eyebrow">Fluchkasse</div>
          <h1 className="page-title">Fluchen für den<br /><span style={{ color: "var(--gold-2)" }}>guten Zweck</span></h1>
          <p className="page-sub">
            Jeder Fluch im Stream füllt die Kasse. Meldet ihn mit <b>!fluch</b>, und wenn DoJa bestätigt, habt ihr eine Chance auf eins von {FLUCH_PIECES} Kartenteilen. Am Monatsende geht alles an den guten Zweck.
          </p>
        </div>
      </div>

      <div className="fl-stats">
        <div className="fl-stat main">
          <div className="label">{monthName} in der Kasse</div>
          <div className="value">{fluchEuro(month.betrag)}</div>
          <div className="sub">{month.flueche} {month.flueche === 1 ? "Fluch" : "Flüche"}{k.betrag ? `   ${fluchEuro(k.betrag)} pro Fluch` : ""}</div>
        </div>
        <div className="fl-stat">
          <div className="label">Spendenziel</div>
          <div className="value small">{k.ziel || "kommt bald"}</div>
          <div className="sub">wählt die Community im Discord</div>
        </div>
        <div className="fl-stat">
          <div className="label">Insgesamt</div>
          <div className="value">{fluchEuro(k.gesamt)}</div>
          <div className="sub">seit dem Start</div>
        </div>
      </div>

      <div className="fl-grid">
        <div className="fl-card-col">
          <div className="fl-panel">
            <div className="eyebrow">{user ? "Deine Fluchkarte" : "Die Fluchkarte"}</div>
            <div className="fl-card-wrap">
              <FluchPuzzle teile={user && mine ? mine.teile : []} image={img} width={260} />
            </div>
            {user && mine ? (
              <>
                <div className="fl-box-count big"><b>{mine.teile.length}</b> von {FLUCH_PIECES} Teilen</div>
                <div className="fl-bar"><span style={{ width: Math.round(mine.teile.length / FLUCH_PIECES * 100) + "%" }} /></div>
                <div className="fl-box-sub">{mine.teile.length >= FLUCH_PIECES ? "Komplett. Die Karte liegt in deiner Sammlung." : `${mine.meldungen || 0} bestätigte Meldungen`}</div>
              </>
            ) : (
              <div className="fl-box-sub">Wer alle {FLUCH_PIECES} Teile findet, bekommt die Promokarte in seine Sammlung. Logg dich ein, um deinen Stand zu sehen.</div>
            )}
          </div>
        </div>

        <div className="leaderboard fl-board">
          <div style={{ padding: "26px 28px 14px" }}>
            <div className="eyebrow">Sammler</div>
            <div style={{ fontSize: 28, fontWeight: 900, marginTop: 8, letterSpacing: "-0.02em" }}>Wer hat die meisten Teile?</div>
          </div>
          {list.length === 0 ? (
            <div className="empty" style={{ margin: "4px 16px 24px" }}>
              <h3>Noch keine Sammler</h3>
              <div>Melde den ersten Fluch im Stream mit !fluch.</div>
            </div>
          ) : (
            <>
              <div className="fl-head">
                <div>Rang</div>
                <div>Wer</div>
                <div>Teile</div>
                <div><span className="lb-h-long">Meldungen</span><span className="lb-h-short">Meld.</span></div>
              </div>
              {list.map((u, i) => {
                const you = user && u.login && u.login === user.login;
                const click = u.login && onUser ? () => onUser(u.login) : undefined;
                return (
                  <div key={u.name + i} className={`fl-row ${you ? "you" : ""}`} onClick={click} style={click ? { cursor: "pointer" } : undefined}>
                    <div className={`lb-rank ${i === 0 ? "gold" : i === 1 ? "silver" : i === 2 ? "bronze" : ""}`}>{String(i + 1).padStart(2, "0")}</div>
                    <div className="fl-name">
                      {u.name}
                      {you && <span className="fl-you">das bist du</span>}
                    </div>
                    <div className="fl-pieces">
                      <div className="fl-bar small"><span style={{ width: Math.round(u.teile / FLUCH_PIECES * 100) + "%" }} /></div>
                      <span className="fl-num">{u.teile}<span>/{FLUCH_PIECES}</span></span>
                    </div>
                    <div className="lb-stat">{u.meldungen}</div>
                  </div>
                );
              })}
            </>
          )}
        </div>
      </div>
    </>
  );
}

Object.assign(window, { FluchView, FluchProfileBox, FluchPuzzle, fluchVisible });
