// Vandaag-scherm: persoonlijke focus, volgende taak, countdown, afvinken

function TaskRow({ task, dateStr, state, setState, me }) {
  const { taskId, type, people = [], dish, special, time: overrideTime } = task;
  const { getPerson, isTaskDone, setTaskDone } = window.kretaHelpers;
  const done = isTaskDone(state, dateStr, taskId);

  const amIInvolved = me && people.includes(me.id);
  const peepObjects = people.map(id => getPerson(id)).filter(Boolean);

  const specialLabel = special === "GRIEKS" ? `🏛️ Uit eten Grieks${overrideTime ? ` — ${overrideTime}` : ""}` :
                       special === "AFHAAL" ? "🥡 Afhaal vanavond" : null;

  return (
    <div className={"task-row" + (done ? " done" : "")}>
      {!special && peepObjects.length > 0 ? (
        <Checkbox done={done} onClick={() => {
          const ns = setTaskDone({...state}, dateStr, taskId, !done);
          setState(ns);
          if (!done) {
            // confetti alleen op eigen taak
            if (amIInvolved) window.dispatchEvent(new CustomEvent("task-done"));
          }
        }} />
      ) : (
        <div style={{ width: 26, height: 26, display: "flex", alignItems: "center", justifyContent: "center", fontSize: 18 }}>
          {type.icon}
        </div>
      )}
      <div className="info">
        <div className="top">
          {!special && <span style={{ fontSize: 17 }}>{type.icon}</span>}
          <span className="label">{type.label}</span>
          <span className="time">{overrideTime || type.time}</span>
          {amIInvolved && !done && <span className="pill" style={{ background: "var(--sun)", color: "#6b4a00" }}>jij</span>}
        </div>
        {specialLabel ? (
          <div className="sub" style={{ fontWeight: 600 }}>{specialLabel}</div>
        ) : (
          <>
            <div style={{ display: "flex", gap: 6, flexWrap: "wrap", marginTop: 6 }}>
              {peepObjects.map(p => <PersonChip key={p.id} person={p} compact />)}
            </div>
            {dish && (
              <div className="sub" style={{ fontStyle: "italic", marginTop: 6 }}>
                🍴 {dish}
              </div>
            )}
          </>
        )}
      </div>
    </div>
  );
}

function CountdownDisplay({ toDate, now, compact }) {
  const { countdown } = window.kretaHelpers;
  const c = countdown(toDate, now);
  if (c.totalMs < 0) return <span style={{ opacity: 0.7 }}>Nu bezig</span>;
  return (
    <div className="countdown">
      <div className="unit"><div className="num">{c.days}</div><div className="lbl">dag</div></div>
      <div className="unit"><div className="num">{c.hours}</div><div className="lbl">uur</div></div>
      <div className="unit"><div className="num">{c.minutes}</div><div className="lbl">min</div></div>
      <div className="unit"><div className="num">{c.seconds}</div><div className="lbl">sec</div></div>
    </div>
  );
}

function VandaagScreen({ me, state, setState, now, demoDate }) {
  const H = window.kretaHelpers;
  const DATA = window.CORVEE_DATA;

  // Gebruik demo-datum of echte nu
  const today = demoDate || now;
  const todayStr = today.toISOString().slice(0, 10);

  const day = H.getDay(todayStr);
  const sched = H.getSchedule(todayStr);

  const tripStart = H.parseDateTime(DATA.trip.startDate);
  const tripEnd = H.parseDateTime(DATA.trip.endDate, "23:59");
  const beforeTrip = today < tripStart;
  const afterTrip = today > tripEnd;

  // Volgende taak voor mij
  const myNext = me ? H.nextTaskForPerson(me.id, today) : null;

  // Opa easter egg
  const isOpa = me && me.id === "opa";

  return (
    <div className="screen">
      {/* Hero */}
      {beforeTrip ? (
        <div className="hero">
          <div className="hero-inner">
            <div className="tiny-mute" style={{ opacity: 0.8, color: "rgba(255,255,255,0.7)" }}>Nog even geduld…</div>
            <h2 className="serif" style={{ margin: "6px 0 16px", fontSize: 28, fontWeight: 700, lineHeight: 1.1 }}>
              Kreta wacht op je ☀️
            </h2>
            <CountdownDisplay toDate={tripStart} now={today} />
            <div style={{ marginTop: 14, fontSize: 13, opacity: 0.85 }}>
              Tot <b>donderdag 23 april</b> — reisdag
            </div>
          </div>
        </div>
      ) : afterTrip ? (
        <div className="hero">
          <div className="hero-inner">
            <h2 className="serif" style={{ margin: 0, fontSize: 26 }}>Weer thuis 🏠</h2>
            <div style={{ opacity: 0.85, marginTop: 6 }}>Ευχαριστώ voor de mooie week!</div>
          </div>
        </div>
      ) : (
        <div className="hero">
          <div className="hero-inner">
            <div className="tiny-mute" style={{ color: "rgba(255,255,255,0.7)" }}>
              {day?.dayName} {day?.label.split(" ")[1]}
              {day?.note && <> · {day.note}</>}
            </div>
            {isOpa ? (
              <OpaHero />
            ) : myNext ? (
              <>
                <h2 className="serif" style={{ margin: "6px 0 4px", fontSize: 24, fontWeight: 700, lineHeight: 1.15 }}>
                  Jouw volgende taak
                </h2>
                <div style={{ fontSize: 18, marginBottom: 14 }}>
                  {myNext.type.icon} <b>{myNext.type.label}</b> — {myNext.type.time}
                </div>
                <CountdownDisplay toDate={myNext.dateTime} now={today} />
                <div style={{ marginTop: 12, fontSize: 13, opacity: 0.85 }}>
                  {myNext.date === todayStr ? "Vandaag" : H.formatDateNL(myNext.date)}
                  {myNext.dish && ` · ${myNext.dish}`}
                </div>
              </>
            ) : (
              <>
                <h2 className="serif" style={{ margin: "6px 0 8px", fontSize: 24 }}>
                  Geen taken meer 🏖️
                </h2>
                <div style={{ opacity: 0.85 }}>Je hebt alles gehad. Geniet!</div>
              </>
            )}
          </div>
        </div>
      )}

      {/* Opa's verjaardag! */}
      {!beforeTrip && !afterTrip && todayStr === "2026-05-02" && <OpaBirthdayCard isOpa={isOpa} />}

      {/* Urgent banner */}
      {!beforeTrip && !afterTrip && myNext && <UrgencyBanner task={myNext} now={today} />}

      {/* Reisdag card */}
      {day?.travel && (
        <div style={{ marginTop: 16 }}>
          <div className="card travel-card">
            <div style={{ fontSize: 28 }}>✈️</div>
            <div className="serif" style={{ fontSize: 20, fontWeight: 700, marginTop: 4, color: "var(--aegean-deep)" }}>
              Reisdag
            </div>
            <div style={{ fontSize: 13, color: "var(--ink-soft)", marginTop: 4 }}>
              {todayStr === "2026-04-23" ? "Op naar het eiland. Kalí sas mazí!" : "Tijd om naar huis te gaan. Καλό ταξίδι!"}
            </div>
            {todayStr === "2026-04-23" && (
              <div style={{ marginTop: 12 }}>
                <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 4 }}>Klaarzetten voor morgen:</div>
                <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
                  {sched?.tasks.ontbijt_klaar?.people.map(id => {
                    const p = H.getPerson(id);
                    return <PersonChip key={id} person={p} compact />;
                  })}
                </div>
              </div>
            )}
          </div>
        </div>
      )}

      {/* Weer */}
      {!beforeTrip && !afterTrip && <WeerCard date={todayStr} />}

      {/* Kudos — compliment van de dag */}
      {!beforeTrip && !afterTrip && me && !isOpa && <KudosCard me={me} />}

      {/* Alle taken vandaag */}
      {sched && Object.keys(sched.tasks).length > 0 && !day?.travel && (
        <>
          <div className="section-title">Vandaag in huis</div>
          <div className="section-sub">
            {day?.dayName} {day?.label.split(" ")[1]} · alles op een rij
          </div>
          <div className="card">
            {DATA.taskTypes.map(tt => {
              const entry = sched.tasks[tt.id];
              if (!entry) return null;
              return (
                <TaskRow
                  key={tt.id}
                  task={{ taskId: tt.id, type: tt, ...entry }}
                  dateStr={todayStr}
                  state={state}
                  setState={setState}
                  me={me}
                />
              );
            })}
          </div>

          {/* Progress */}
          <TodayProgress sched={sched} state={state} dateStr={todayStr} />
        </>
      )}

      {/* Morgen preview */}
      {!beforeTrip && !afterTrip && me && !isOpa && <TomorrowPreview today={today} me={me} />}

      {/* Opa extra */}
      {isOpa && <OpaExtras />}
    </div>
  );
}

function OpaBirthdayCard({ isOpa }) {
  const B = window.OPA_BIRTHDAY;
  const [jokeIdx, setJokeIdx] = React.useState(0);
  const joke = B.jokes[jokeIdx % B.jokes.length];

  return (
    <div className="bday-hero" style={{ marginTop: 16 }}>
      <div style={{ position: "relative", zIndex: 2, textAlign: "center" }}>
        <div className="crown-bounce" style={{ fontSize: 50, marginBottom: 4 }}>👑</div>
        <div style={{ fontSize: 11, fontWeight: 700, textTransform: "uppercase", letterSpacing: 2, opacity: 0.9, marginBottom: 4 }}>
          Χρόνια Πολλά!
        </div>
        <h2 className="serif" style={{ margin: "4px 0 6px", fontSize: 32, fontWeight: 800, lineHeight: 1.05, letterSpacing: -0.5 }}>
          {isOpa ? "Het is jouw dag, Opa!" : "Opa is jarig! 🎂"}
        </h2>
        <div style={{ fontSize: 15, opacity: 0.92, marginBottom: 16 }}>
          {isOpa ? "71 jaar jong vandaag" : "Vandaag wordt Opa 71"}
        </div>

        {/* Cake */}
        <div style={{
          display: "inline-block",
          padding: "12px 20px",
          background: "rgba(255,255,255,0.18)",
          backdropFilter: "blur(8px)",
          borderRadius: 14,
          border: "1px solid rgba(255,255,255,0.3)",
          fontSize: 38,
          marginBottom: 14,
        }}>
          🎂🕯️🎉
        </div>

        {/* Joke */}
        <div
          onClick={() => setJokeIdx(i => i + 1)}
          style={{
            cursor: "pointer",
            padding: "12px 14px",
            background: "rgba(255,255,255,0.2)",
            backdropFilter: "blur(8px)",
            borderRadius: 12,
            fontSize: 13,
            fontStyle: "italic",
            lineHeight: 1.5,
            border: "1px solid rgba(255,255,255,0.25)",
          }}
        >
          <div style={{ fontSize: 10, fontWeight: 700, textTransform: "uppercase", letterSpacing: 1, opacity: 0.75, marginBottom: 4 }}>
            Grap #{(jokeIdx % window.OPA_BIRTHDAY.jokes.length) + 1} · tik voor meer
          </div>
          "{joke}"
        </div>

        {/* Button to trigger confetti */}
        <button
          onClick={() => window.dispatchEvent(new CustomEvent("task-done"))}
          style={{
            marginTop: 12,
            appearance: "none", border: "none", cursor: "pointer",
            padding: "10px 18px",
            background: "white",
            color: "#c13584",
            borderRadius: 999,
            fontFamily: "inherit", fontWeight: 700, fontSize: 14,
            boxShadow: "0 4px 12px rgba(0,0,0,0.15)",
          }}
        >
          🎊 Gooi confetti
        </button>

        {/* Wishes */}
        {!isOpa && (
          <div style={{ marginTop: 16, textAlign: "left" }}>
            <div style={{ fontSize: 10, fontWeight: 700, textTransform: "uppercase", letterSpacing: 1, opacity: 0.85, marginBottom: 8 }}>
              Wensen van de groep
            </div>
            {B.wishes.map((w, i) => (
              <div key={i} style={{
                padding: "10px 12px",
                background: "rgba(255,255,255,0.15)",
                borderRadius: 10,
                marginBottom: 6,
                fontSize: 12,
                lineHeight: 1.5,
                border: "1px solid rgba(255,255,255,0.15)",
              }}>
                <div style={{ fontWeight: 700, fontSize: 11, marginBottom: 2, opacity: 0.9 }}>— {w.from}</div>
                <div style={{ fontStyle: "italic" }}>"{w.text}"</div>
              </div>
            ))}
          </div>
        )}

        {isOpa && (
          <div style={{ marginTop: 14, padding: 12, background: "rgba(255,255,255,0.2)", borderRadius: 12, fontSize: 13, lineHeight: 1.5 }}>
            Vandaag is <b>alles</b> gratis (voor jou).
            De hele familie staat tot je beschikking.
            Proost op <b>71</b>! 🥂
          </div>
        )}
      </div>
    </div>
  );
}

window.OpaBirthdayCard = OpaBirthdayCard;

function UrgencyBanner({ task, now }) {
  const H = window.kretaHelpers;
  const c = H.countdown(task.dateTime, now);
  if (c.totalMs <= 0) {
    return (
      <div className="banner-warn banner-urgent" style={{ marginTop: 14 }}>
        <div style={{ fontSize: 22 }}>🔔</div>
        <div>
          <div style={{ fontWeight: 700, marginBottom: 2 }}>NU aan de beurt!</div>
          <div style={{ fontSize: 13 }}>{task.type.label} — aan de slag!</div>
        </div>
      </div>
    );
  }
  if (c.totalMs < 30 * 60 * 1000) {
    return (
      <div className="banner-warn" style={{ marginTop: 14 }}>
        <div style={{ fontSize: 22 }}>⏰</div>
        <div>
          <div style={{ fontWeight: 700, marginBottom: 2 }}>
            Bijna aan de beurt — {c.minutes} min
          </div>
          <div style={{ fontSize: 13 }}>{task.type.label} om {task.type.time}</div>
        </div>
      </div>
    );
  }
  return null;
}

function TodayProgress({ sched, state, dateStr }) {
  const H = window.kretaHelpers;
  const all = Object.keys(sched.tasks).filter(k => {
    const e = sched.tasks[k];
    return e.people && e.people.length > 0;
  });
  const done = all.filter(k => H.isTaskDone(state, dateStr, k)).length;
  const pct = all.length > 0 ? Math.round((done / all.length) * 100) : 0;
  return (
    <div style={{ marginTop: 14, padding: "12px 16px", background: "rgba(255,255,255,0.6)", borderRadius: 12 }}>
      <div style={{ display: "flex", justifyContent: "space-between", fontSize: 13, fontWeight: 600, marginBottom: 6 }}>
        <span>Voortgang vandaag</span>
        <span>{done}/{all.length}</span>
      </div>
      <div className="progress"><div style={{ width: pct + "%" }} /></div>
    </div>
  );
}

function TomorrowPreview({ today, me }) {
  const H = window.kretaHelpers;
  const tom = new Date(today); tom.setDate(tom.getDate() + 1);
  const tomStr = tom.toISOString().slice(0, 10);
  const tomTasks = H.tasksForPersonOnDay(me.id, tomStr);
  if (tomTasks.length === 0) return null;
  return (
    <>
      <div className="section-title">Morgen voor jou</div>
      <div className="card" style={{ padding: 14 }}>
        {tomTasks.map((t, i) => (
          <div key={i} style={{ display: "flex", alignItems: "center", gap: 10, padding: "8px 0", borderBottom: i < tomTasks.length - 1 ? "1px solid var(--line-soft)" : "none" }}>
            <div style={{ fontSize: 22 }}>{t.type.icon}</div>
            <div style={{ flex: 1 }}>
              <div style={{ fontWeight: 600, fontSize: 14 }}>{t.type.label}</div>
              <div style={{ fontSize: 12, color: "var(--muted)" }}>{t.type.time}{t.dish ? ` · ${t.dish}` : ""}</div>
            </div>
          </div>
        ))}
      </div>
    </>
  );
}

function OpaHero() {
  const phrases = [
    "Vandaag: NIETS. Lekker zo blijven.",
    "Agenda: zonnebank, ouzo, herhalen.",
    "Taak van de dag: de portemonnee luchten.",
    "Activiteit: kijken hoe anderen werken.",
  ];
  const [i] = React.useState(Math.floor(Math.random() * phrases.length));
  return (
    <>
      <h2 className="serif" style={{ margin: "6px 0 4px", fontSize: 26, fontWeight: 700 }}>
        Opa, geluksvogel 👑
      </h2>
      <div style={{ fontSize: 14, opacity: 0.9, marginBottom: 14 }}>
        {phrases[i]}
      </div>
      <div style={{ padding: 12, background: "rgba(244,196,48,0.2)", borderRadius: 12, fontSize: 13 }}>
        Omdat je <b>70</b> bent en dit hele feestje betaalt,
        hoef jij deze week <b>niets</b>. Wij zijn je eeuwig dankbaar 🙏
      </div>
    </>
  );
}

function OpaExtras() {
  return (
    <>
      <div className="section-title">Opa's VIP-dagagenda</div>
      <div className="card opa-card" style={{ padding: 18 }}>
        {[
          { t: "09:00", act: "Uitslapen op terras", icon: "☕" },
          { t: "11:00", act: "Kleinkinderen knuffelen", icon: "🤗" },
          { t: "13:00", act: "Lunchen (door anderen klaargemaakt)", icon: "🥖" },
          { t: "15:00", act: "Middagdutje", icon: "😴" },
          { t: "17:00", act: "Ouzo bij de zonsondergang", icon: "🍸" },
          { t: "19:00", act: "Diner (ook klaargemaakt)", icon: "🍽️" },
          { t: "21:00", act: "Verhalen vertellen", icon: "📖" },
        ].map((x, i) => (
          <div key={i} style={{ display: "flex", gap: 10, alignItems: "center", padding: "6px 0" }}>
            <div style={{ fontSize: 20 }}>{x.icon}</div>
            <div style={{ fontSize: 13, fontWeight: 600, color: "#8b6a20", width: 50 }}>{x.t}</div>
            <div style={{ fontSize: 14, color: "#6b4a00" }}>{x.act}</div>
          </div>
        ))}
        <div style={{ marginTop: 10, padding: "10px 12px", background: "rgba(255,255,255,0.5)", borderRadius: 10, fontSize: 12, fontStyle: "italic", color: "#6b4a00" }}>
          "De beste taak is geen taak." — Σωκράτης (niet echt)
        </div>
      </div>
    </>
  );
}

function WeerCard({ date }) {
  // Fake weer voor Kreta - april/mei is warm en zonnig
  const weerOpties = {
    "2026-04-23": { icon: "☀️", temp: 22, desc: "Zonnig" },
    "2026-04-24": { icon: "☀️", temp: 23, desc: "Strakblauw" },
    "2026-04-25": { icon: "⛅", temp: 21, desc: "Wolkjes" },
    "2026-04-26": { icon: "☀️", temp: 24, desc: "Zonnig" },
    "2026-04-27": { icon: "🌤️", temp: 25, desc: "Beetje bewolkt" },
    "2026-04-28": { icon: "☀️", temp: 26, desc: "Heet & mooi" },
    "2026-04-29": { icon: "☀️", temp: 27, desc: "Zomers" },
    "2026-04-30": { icon: "🌤️", temp: 25, desc: "Fijn weer" },
    "2026-05-01": { icon: "☀️", temp: 28, desc: "Zonbrand mee" },
    "2026-05-02": { icon: "⛅", temp: 24, desc: "Wisselend" },
    "2026-05-03": { icon: "☀️", temp: 25, desc: "Zonnig" },
  };
  const w = weerOpties[date] || { icon: "☀️", temp: 24, desc: "Zonnig" };
  return (
    <div style={{
      marginTop: 14, display: "flex", alignItems: "center", gap: 14,
      background: "linear-gradient(135deg, #e8f1f8, #c5e4f0)",
      padding: "12px 16px", borderRadius: 14,
      border: "1px solid rgba(135,206,235,0.3)",
    }}>
      <div style={{ fontSize: 36 }}>{w.icon}</div>
      <div style={{ flex: 1 }}>
        <div style={{ fontFamily: "Fraunces, serif", fontWeight: 700, fontSize: 22, color: "var(--aegean-deep)" }}>
          {w.temp}°C
        </div>
        <div style={{ fontSize: 12, color: "var(--ink-soft)" }}>
          Kreta · {w.desc}
        </div>
      </div>
      <div style={{ fontSize: 11, color: "var(--muted)", textTransform: "uppercase", letterSpacing: 0.5 }}>
        Chania
      </div>
    </div>
  );
}

Object.assign(window, { VandaagScreen, TaskRow, CountdownDisplay });

// ---- Kudos-component (compliment van de dag) ----
function KudosCard({ me }) {
  const H = window.kretaHelpers;
  const DATA = window.CORVEE_DATA;
  const B = window.kretaBackend;
  const [list, setList] = React.useState([]);
  const [open, setOpen] = React.useState(false);
  const [to, setTo] = React.useState("");
  const [txt, setTxt] = React.useState("");
  const [sending, setSending] = React.useState(false);
  const [err, setErr] = React.useState("");
  const today = new Date().toISOString().slice(0, 10);

  async function refresh() {
    if (!B?.fetchKudos) return;
    const all = await B.fetchKudos(40);
    setList(all);
  }
  React.useEffect(() => { refresh(); const t = setInterval(refresh, 30000); return () => clearInterval(t); }, []);

  const todays = list.filter(k => k.day === today);
  const myToday = todays.filter(k => k.from_person === me.id).length;
  const canSend = myToday < 3;

  async function send() {
    if (!to || sending) return;
    setSending(true); setErr("");
    const r = await B.sendKudos(to, txt.trim());
    setSending(false);
    if (r.ok) {
      setTo(""); setTxt(""); setOpen(false);
      window.dispatchEvent(new CustomEvent("task-done"));
      refresh();
    } else if (r.reason === "limit") {
      setErr("Je hebt je 3 kudos voor vandaag al gegeven 💛");
    } else {
      setErr("Oeps, verzenden lukte niet");
    }
  }

  const others = DATA.people.filter(p => p.id !== me.id);

  return (
    <>
      <div className="section-title" style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <span>Kudos 💛</span>
        {canSend && (
          <button
            onClick={() => setOpen(o => !o)}
            style={{
              appearance: "none", border: "1px solid var(--line)", cursor: "pointer",
              padding: "6px 12px", borderRadius: 999, background: "white",
              fontFamily: "inherit", fontSize: 12, fontWeight: 700, color: "var(--aegean-deep)",
            }}
          >
            {open ? "× Sluiten" : `+ Kudo geven (${3 - myToday} over)`}
          </button>
        )}
      </div>
      <div className="section-sub">Geef complimenten, zonder moeite</div>

      {open && (
        <div className="card" style={{ marginBottom: 12 }}>
          <div className="tiny-mute" style={{ marginBottom: 6 }}>Voor wie?</div>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 6, marginBottom: 10 }}>
            {others.map(p => {
              const sel = to === p.id;
              return (
                <button key={p.id} onClick={() => setTo(p.id)} style={{
                  appearance: "none", cursor: "pointer",
                  padding: "5px 10px 5px 5px", borderRadius: 999,
                  border: sel ? `2px solid ${p.color}` : "1px solid var(--line)",
                  background: sel ? p.color + "18" : "white",
                  display: "inline-flex", alignItems: "center", gap: 6,
                  fontFamily: "inherit", fontSize: 12, fontWeight: 600,
                  color: sel ? p.color : "var(--ink)",
                }}>
                  <span style={{
                    width: 22, height: 22, borderRadius: "50%", background: p.color,
                    color: "white", display: "inline-flex", alignItems: "center", justifyContent: "center",
                    fontSize: 11, fontWeight: 700,
                  }}>{p.name[0]}</span>
                  {p.name}
                </button>
              );
            })}
          </div>

          <div className="tiny-mute" style={{ marginBottom: 6 }}>Waarvoor? (optioneel)</div>
          <input
            value={txt}
            onChange={e => setTxt(e.target.value.slice(0, 120))}
            placeholder="bv. super afwas gedaan! 🌟"
            style={{
              width: "100%", padding: 10, borderRadius: 8,
              border: "1px solid var(--line)", fontFamily: "inherit", fontSize: 14,
              boxSizing: "border-box",
            }}
          />
          <div style={{ display: "flex", gap: 8, marginTop: 10, alignItems: "center" }}>
            <button onClick={send} disabled={!to || sending} className="btn btn-primary" style={{
              padding: "10px 14px", fontSize: 13, opacity: (!to || sending) ? 0.5 : 1,
            }}>
              💛 Verstuur kudo
            </button>
            {err && <div style={{ fontSize: 12, color: "#9b2226" }}>{err}</div>}
          </div>
        </div>
      )}

      {/* Tally per persoon vandaag */}
      {todays.length > 0 ? (
        <div className="card" style={{ padding: 14, marginBottom: 4 }}>
          {(() => {
            const tally = {};
            for (const k of todays) {
              tally[k.to_person] = tally[k.to_person] || { count: 0, texts: [] };
              tally[k.to_person].count++;
              if (k.text) tally[k.to_person].texts.push({ from: k.from_person, text: k.text });
            }
            const ranked = Object.keys(tally)
              .map(id => ({ p: H.getPerson(id), ...tally[id] }))
              .filter(x => x.p)
              .sort((a, b) => b.count - a.count);
            const top = ranked[0];
            return (
              <>
                {top && (
                  <div style={{
                    display: "flex", alignItems: "center", gap: 12,
                    padding: 10, borderRadius: 12,
                    background: `linear-gradient(135deg, ${top.p.color}22, ${top.p.color}08)`,
                    marginBottom: 10,
                  }}>
                    <div style={{ fontSize: 28 }}>💛</div>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontSize: 11, fontWeight: 700, textTransform: "uppercase", letterSpacing: 1, color: "var(--muted)" }}>
                        Kudo-koning(in) van vandaag
                      </div>
                      <div className="serif" style={{ fontSize: 22, fontWeight: 700, color: top.p.color, letterSpacing: -0.3 }}>
                        {top.p.name}
                      </div>
                    </div>
                    <div style={{
                      padding: "4px 10px", borderRadius: 999,
                      background: top.p.color, color: "white",
                      fontSize: 13, fontWeight: 800,
                    }}>
                      {top.count} 💛
                    </div>
                  </div>
                )}
                {ranked.slice(1).map(r => (
                  <div key={r.p.id} style={{
                    display: "flex", alignItems: "center", gap: 10,
                    padding: "6px 4px",
                  }}>
                    <div style={{
                      width: 24, height: 24, borderRadius: "50%", background: r.p.color,
                      color: "white", display: "flex", alignItems: "center", justifyContent: "center",
                      fontSize: 11, fontWeight: 700,
                    }}>{r.p.name[0]}</div>
                    <div style={{ flex: 1, fontSize: 13, fontWeight: 600 }}>{r.p.name}</div>
                    <div style={{ fontSize: 13, color: "var(--muted)" }}>{r.count} 💛</div>
                  </div>
                ))}

                {/* Recente teksten */}
                {todays.filter(k => k.text).slice(0, 3).map(k => {
                  const from = H.getPerson(k.from_person);
                  const to = H.getPerson(k.to_person);
                  return (
                    <div key={k.id} style={{
                      marginTop: 10, padding: "8px 10px",
                      background: "var(--stucco)", borderRadius: 10,
                      fontSize: 12, lineHeight: 1.5,
                    }}>
                      <b style={{ color: from?.color }}>{from?.name}</b> → <b style={{ color: to?.color }}>{to?.name}</b>
                      <div style={{ fontStyle: "italic", color: "var(--ink-soft)", marginTop: 2 }}>"{k.text}"</div>
                    </div>
                  );
                })}
              </>
            );
          })()}
        </div>
      ) : (
        <div className="card" style={{ padding: 14, textAlign: "center", color: "var(--muted)" }}>
          <div style={{ fontSize: 28, marginBottom: 4 }}>💛</div>
          <div style={{ fontSize: 13 }}>Nog geen kudos vandaag — maak jij het begin?</div>
        </div>
      )}
    </>
  );
}

window.KudosCard = KudosCard;
