// Leaderboard + Berichtenwall + Klusjes-randomizer

function LeaderboardScreen({ now, demoDate }) {
  const H = window.kretaHelpers;
  const DATA = window.CORVEE_DATA;
  const today = demoDate || now;
  const state = H.loadState();
  const done = state.done || {};

  // Uitgesloten van leaderboard
  const LB_EXCLUDE = new Set(["max", "cam"]);

  // Bereken score per persoon
  const scores = {};
  for (const p of DATA.people) {
    if (LB_EXCLUDE.has(p.id)) continue;
    scores[p.id] = { person: p, done: 0, total: 0 };
  }
  for (const sched of DATA.schedule) {
    for (const taskId of Object.keys(sched.tasks)) {
      const entry = sched.tasks[taskId];
      if (!entry.people) continue;
      const isDone = !!done[`${sched.date}:${taskId}`];
      for (const pid of entry.people) {
        if (!scores[pid]) continue;
        scores[pid].total += 1;
        if (isDone) scores[pid].done += 1;
      }
    }
  }

  const ranked = Object.values(scores)
    .filter(s => s.total > 0)
    .sort((a, b) => b.done - a.done || b.total - a.total);

  const maxDone = ranked[0]?.done || 1;
  const medals = ["🥇", "🥈", "🥉"];

  return (
    <div className="screen">
      <h1 className="serif" style={{ fontSize: 30, margin: "8px 0 2px", letterSpacing: -0.6 }}>
        Leaderboard 🏆
      </h1>
      <div className="section-sub">Wie is de MVP van Kreta?</div>

      <div className="card" style={{ padding: 14 }}>
        {ranked.map((s, i) => {
          const pct = maxDone > 0 ? (s.done / maxDone) * 100 : 0;
          const medal = medals[i];
          return (
            <div key={s.person.id} style={{
              display: "flex", alignItems: "center", gap: 12,
              padding: "10px 0",
              borderBottom: i < ranked.length - 1 ? "1px solid var(--line-soft)" : "none",
            }}>
              <div style={{ width: 28, textAlign: "center", fontSize: medal ? 22 : 14, fontWeight: 700, color: "var(--muted)" }}>
                {medal || `#${i + 1}`}
              </div>
              <Avatar person={s.person} size={36} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontWeight: 600, fontSize: 14 }}>{s.person.name}</div>
                <div style={{ height: 4, background: "rgba(26,84,144,0.1)", borderRadius: 4, marginTop: 4, overflow: "hidden" }}>
                  <div style={{ height: "100%", width: pct + "%", background: s.person.color, borderRadius: 4 }} />
                </div>
              </div>
              <div style={{ textAlign: "right", minWidth: 46 }}>
                <div className="serif" style={{ fontSize: 20, fontWeight: 700, color: s.person.color }}>
                  {s.done}
                </div>
                <div style={{ fontSize: 10, color: "var(--muted)", textTransform: "uppercase", letterSpacing: 0.5 }}>
                  /{s.total}
                </div>
              </div>
            </div>
          );
        })}
      </div>

      {/* Opa special */}
      <div className="card opa-card" style={{ marginTop: 14, padding: 14, textAlign: "center" }}>
        <div style={{ fontSize: 32 }}>👑</div>
        <div className="serif" style={{ fontWeight: 700, fontSize: 18, color: "#6b4a00", marginTop: 4 }}>
          Opa: buiten mededinging
        </div>
        <div style={{ fontSize: 12, color: "#8b6a20", marginTop: 2 }}>
          Score: ∞ (betaalt het hele feestje)
        </div>
      </div>
    </div>
  );
}

// Berichtenwall
function WallScreen({ me, isAdmin }) {
  const H = window.kretaHelpers;
  const B = window.kretaBackend;
  const [msgs, setMsgs] = React.useState(() => H.loadState().wall || []);
  const [text, setText] = React.useState("");

  // Live sync met backend
  React.useEffect(() => {
    const h = () => setMsgs(H.loadState().wall || []);
    window.addEventListener("kreta-state", h);
    return () => window.removeEventListener("kreta-state", h);
  }, []);

  const post = async () => {
    if (!text.trim()) return;
    await (B?.postWall?.(text.trim()) ?? Promise.resolve());
    setText("");
  };

  async function del(id) {
    if (!confirm("Dit bericht verwijderen?")) return;
    await B.deleteWall(id);
  }

  const fmt = (ts) => {
    const diff = Date.now() - ts;
    if (diff < 60000) return "nu";
    if (diff < 3600000) return `${Math.floor(diff / 60000)}m`;
    if (diff < 86400000) return `${Math.floor(diff / 3600000)}u`;
    return `${Math.floor(diff / 86400000)}d`;
  };

  return (
    <div className="screen">
      <h1 className="serif" style={{ fontSize: 30, margin: "8px 0 2px", letterSpacing: -0.6 }}>
        Prikbord 📌
      </h1>
      <div className="section-sub">Korte berichtjes voor de groep</div>

      <div className="card" style={{ padding: 12, marginBottom: 14 }}>
        <textarea
          value={text}
          onChange={e => setText(e.target.value)}
          placeholder="Schrijf iets lekkers…"
          rows={2}
          style={{
            width: "100%", border: "none", outline: "none",
            fontFamily: "inherit", fontSize: 14, resize: "none",
            background: "var(--stucco)", borderRadius: 8, padding: 10,
          }}
        />
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 8 }}>
          <div style={{ fontSize: 12, color: "var(--muted)" }}>
            Posten als <b style={{ color: me.color }}>{me.name}</b>
          </div>
          <button className="btn btn-primary" onClick={post} style={{ padding: "8px 14px", fontSize: 13 }}>
            Plak op bord
          </button>
        </div>
      </div>

      <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
        {[...msgs].reverse().map(m => {
          const p = H.getPerson(m.from);
          const canDel = isAdmin || m.from === me.id;
          return (
            <div key={m.id} className="card" style={{ padding: 12, display: "flex", gap: 10 }}>
              <Avatar person={p} size={32} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 2, gap: 8 }}>
                  <div style={{ fontWeight: 700, fontSize: 13, color: p?.color }}>{p?.name}</div>
                  <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
                    <div style={{ fontSize: 11, color: "var(--muted)" }}>{fmt(m.ts)}</div>
                    {canDel && (
                      <button
                        onClick={() => del(m.id)}
                        title="Verwijderen"
                        style={{
                          appearance: "none", border: "none", cursor: "pointer",
                          background: "transparent", color: "var(--muted)",
                          fontSize: 14, padding: 0, lineHeight: 1,
                        }}
                      >🗑️</button>
                    )}
                  </div>
                </div>
                <div style={{ fontSize: 14, lineHeight: 1.5, wordBreak: "break-word" }}>{m.text}</div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// Randomizer - wie doet X?
function RandomizerScreen({ me }) {
  const H = window.kretaHelpers;
  const DATA = window.CORVEE_DATA;
  const klusjes = [
    "doet de afwas 🍽️",
    "haalt broodjes 🥖",
    "dekt de tafel 🍴",
    "haalt nog een fles wijn 🍷",
    "ruimt de speelhoek op 🧸",
    "maakt een laatste rondje salade 🥗",
    "gaat zwemband oppompen 🏊",
    "draait Griekse muziek op 🎶",
    "haalt koffie ☕",
    "koopt ijsjes 🍦",
  ];
  const [klus, setKlus] = React.useState(klusjes[0]);
  const [chosen, setChosen] = React.useState(null);
  const [spinning, setSpinning] = React.useState(false);
  const [excluded, setExcluded] = React.useState({ opa: true, cam: true, max: true, milou: true });

  const poolPeople = DATA.people.filter(p => !excluded[p.id]);

  const spin = () => {
    if (poolPeople.length === 0) return;
    setSpinning(true);
    setChosen(null);
    let cycles = 0;
    const maxCycles = 18 + Math.floor(Math.random() * 6);
    const tick = () => {
      const p = poolPeople[Math.floor(Math.random() * poolPeople.length)];
      setChosen(p);
      cycles++;
      if (cycles < maxCycles) {
        setTimeout(tick, 60 + cycles * 12);
      } else {
        setSpinning(false);
        window.dispatchEvent(new CustomEvent("task-done"));
      }
    };
    tick();
  };

  const toggleEx = (id) => setExcluded(e => ({ ...e, [id]: !e[id] }));

  return (
    <div className="screen">
      <h1 className="serif" style={{ fontSize: 30, margin: "8px 0 2px", letterSpacing: -0.6 }}>
        Klusjeswiel 🎲
      </h1>
      <div className="section-sub">Als niemand het wil doen, laat het lot beslissen</div>

      <div className="card" style={{ marginBottom: 14 }}>
        <div className="tiny-mute" style={{ marginBottom: 6 }}>Het klusje is…</div>
        <select
          value={klus}
          onChange={e => setKlus(e.target.value)}
          style={{ width: "100%", padding: 10, borderRadius: 10, border: "1px solid var(--line)", fontFamily: "inherit", fontSize: 14 }}
        >
          {klusjes.map((k, i) => <option key={i} value={k}>{k}</option>)}
        </select>
      </div>

      <div style={{
        background: "linear-gradient(160deg, #1a5490, #0d3a6b)",
        borderRadius: 22,
        padding: "36px 24px",
        textAlign: "center",
        color: "white",
        minHeight: 200,
        boxShadow: "0 12px 32px rgba(13,58,107,0.25)",
      }}>
        {chosen ? (
          <>
            <div style={{ fontSize: 11, fontWeight: 700, textTransform: "uppercase", letterSpacing: 1.5, opacity: 0.8, marginBottom: 14 }}>
              {spinning ? "Aan het loten…" : "En de winnaar is…"}
            </div>
            <div style={{
              display: "inline-block",
              transform: spinning ? "scale(0.95)" : "scale(1)",
              transition: "transform 0.2s",
            }}>
              <div style={{ display: "flex", justifyContent: "center", marginBottom: 10 }}>
                <Avatar person={chosen} size={72} />
              </div>
              <div className="serif" style={{ fontSize: 32, fontWeight: 800, letterSpacing: -0.5 }}>
                {chosen.name}
              </div>
            </div>
            {!spinning && (
              <div style={{ marginTop: 12, fontSize: 14, opacity: 0.9 }}>
                <b>{chosen.name}</b> {klus}
              </div>
            )}
          </>
        ) : (
          <div style={{ padding: "40px 0", opacity: 0.75 }}>
            <div style={{ fontSize: 60, marginBottom: 6 }}>🎯</div>
            <div style={{ fontSize: 14 }}>Druk op draai om iemand te selecteren</div>
          </div>
        )}
      </div>

      <button className="btn btn-primary" onClick={spin} disabled={spinning || poolPeople.length === 0}
        style={{ width: "100%", marginTop: 14, fontSize: 15, padding: 14, opacity: spinning ? 0.6 : 1 }}>
        {spinning ? "🌀 Aan het draaien…" : "🎲 Draai het wiel"}
      </button>

      <div className="section-title" style={{ fontSize: 16 }}>Wie mag meedoen?</div>
      <div className="card" style={{ padding: 12 }}>
        <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
          {DATA.people.map(p => (
            <button
              key={p.id}
              onClick={() => toggleEx(p.id)}
              style={{
                appearance: "none", border: "none", cursor: "pointer",
                padding: "4px 10px 4px 4px",
                borderRadius: 999,
                background: excluded[p.id] ? "var(--stucco-shadow)" : "white",
                border: excluded[p.id] ? "1px solid var(--line)" : `1px solid ${p.color}66`,
                opacity: excluded[p.id] ? 0.45 : 1,
                display: "flex", alignItems: "center", gap: 6,
                fontFamily: "inherit", fontSize: 12, fontWeight: 600,
                color: excluded[p.id] ? "var(--muted)" : p.color,
                textDecoration: excluded[p.id] ? "line-through" : "none",
              }}
            >
              <span style={{
                width: 20, height: 20, borderRadius: "50%", background: p.color,
                color: "white", display: "inline-flex", alignItems: "center", justifyContent: "center",
                fontSize: 10, fontWeight: 700,
              }}>{p.name[0]}</span>
              {p.name}
            </button>
          ))}
        </div>
        <div style={{ fontSize: 11, color: "var(--muted)", marginTop: 8 }}>
          Opa is standaard uitgesloten (70+ privilege 👑)
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { LeaderboardScreen, WallScreen, RandomizerScreen });
