// weetjes-historiek.jsx, overzicht van alle weetjes per dag.
// Leest direct uit content.weetjes (zelfde bron als de WeetjeBalk),
// dus zodra er een nieuw weetje aan content/weetjes.json wordt toegevoegd
// of een nieuwe dag aanbreekt, verschijnt het hier automatisch.

const WEETJE_MAANDEN = [
  "januari", "februari", "maart", "april", "mei", "juni",
  "juli", "augustus", "september", "oktober", "november", "december"
];

function WeetjesHistoriekPagina({ weetjes, onBack, accent = "#E63946", fontScale, setFontScale }) {
  const isMobile = useIsMobile();
  const [zoek, setZoek] = React.useState("");
  const [openDatum, setOpenDatum] = React.useState(null);

  // bouw alle dagen van het jaar tot vandaag, nieuwste eerst
  const items = React.useMemo(() => {
    const map = weetjes?.weetjes || {};
    const today = new Date();
    const startYear = today.getFullYear();
    const all = [];
    for (let m = 0; m < 12; m++) {
      const daysInMonth = new Date(startYear, m + 1, 0).getDate();
      for (let d = 1; d <= daysInMonth; d++) {
        const dt = new Date(startYear, m, d);
        if (dt > today) continue;
        const mm = String(m + 1).padStart(2, "0");
        const dd = String(d).padStart(2, "0");
        const key = `${mm}-${dd}`;
        const v = map[key];
        if (!v) continue;
        const entry = typeof v === "string"
          ? { tekst: v, uitleg: null, grapje: null }
          : { tekst: v.tekst || "", uitleg: v.uitleg || null, grapje: v.grapje || null };
        all.push({
          key,
          datum: key,
          dt,
          dag: d,
          maand: m,
          ...entry,
        });
      }
    }
    all.sort((a, b) => b.dt - a.dt);
    return all;
  }, [weetjes]);

  const filtered = React.useMemo(() => {
    if (!zoek.trim()) return items;
    const q = zoek.toLowerCase();
    return items.filter(it =>
      it.tekst.toLowerCase().includes(q) ||
      (it.uitleg && it.uitleg.toLowerCase().includes(q)) ||
      (it.grapje && it.grapje.toLowerCase().includes(q))
    );
  }, [items, zoek]);

  // groepeer per maand voor de tijdlijn-headers
  const groups = React.useMemo(() => {
    const out = [];
    let cur = null;
    for (const it of filtered) {
      const label = `${WEETJE_MAANDEN[it.maand]} ${it.dt.getFullYear()}`;
      if (!cur || cur.label !== label) {
        cur = { label, items: [] };
        out.push(cur);
      }
      cur.items.push(it);
    }
    return out;
  }, [filtered]);

  const todayKey = (() => {
    const d = new Date();
    return `${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
  })();

  return (
    <div style={{
      background: "#D6EFC7", minHeight: "100%", width: "100%",
      fontFamily: "'Patrick Hand', cursive", color: "#1A1A1A",
      position: "relative",
    }}>
      <div style={{
        position: "absolute", inset: 0,
        backgroundImage: "radial-gradient(circle, rgba(0,0,0,0.06) 1.2px, transparent 1.4px)",
        backgroundSize: "12px 12px", pointerEvents: "none", zIndex: 0,
      }} />

      <div className="hp-topbar" style={{
        position: "sticky", top: 0, zIndex: 10, background: "#F0FAE6",
        borderBottom: "4px solid #1A1A1A",
        display: "flex", alignItems: "center", justifyContent: "space-between",
        gap: 10, flexWrap: "wrap",
      }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <div style={{
            fontFamily: "'Bangers', sans-serif",
            fontSize: isMobile ? 22 : 34,
            color: accent, letterSpacing: "0.05em",
            WebkitTextStroke: isMobile ? "1.2px #1A1A1A" : "1.5px #1A1A1A",
          }}>HETE PEPER</div>
        </div>
        <div style={{ display: "flex", gap: 10, alignItems: "center", flexWrap: "wrap" }}>
          {setFontScale && <FontSizer scale={fontScale} setScale={setFontScale} />}
          <button className="btn-comic" onClick={onBack} style={{ fontSize: 16, padding: "6px 14px" }}>
            ← HOME
          </button>
        </div>
      </div>

      {/* Hero */}
      <section className="hp-section" style={{ paddingTop: isMobile ? 16 : 32, paddingBottom: 10, position: "relative", zIndex: 1 }}>
        <div style={{
          background: "#F0FAE6", border: "5px solid #1A1A1A",
          boxShadow: isMobile ? "5px 5px 0 #1A1A1A" : "8px 8px 0 #1A1A1A",
          padding: isMobile ? "16px 18px" : "22px 28px",
          display: "flex",
          flexDirection: isMobile ? "column" : "row",
          justifyContent: "space-between",
          alignItems: isMobile ? "flex-start" : "center",
          gap: isMobile ? 14 : 20,
          position: "relative", transform: "rotate(-0.3deg)",
        }}>
          <div>
            <div style={{
              fontFamily: "'Bangers', sans-serif",
              fontSize: isMobile ? 14 : 18,
              color: "#6B5A3D", letterSpacing: "0.1em",
            }}>
              HETE PEPER · ARCHIEF
            </div>
            <div style={{
              fontFamily: "'Bangers', sans-serif",
              fontSize: isMobile ? 38 : 64,
              lineHeight: 0.95,
              color: "#E63946",
              WebkitTextStroke: isMobile ? "1.8px #1A1A1A" : "2.5px #1A1A1A",
              textShadow: isMobile ? "3px 3px 0 #1A1A1A" : "5px 5px 0 #1A1A1A",
              letterSpacing: "0.03em",
            }}>
              WEETJES&shy;GESCHIEDENIS
            </div>
            <div style={{ fontSize: isMobile ? 17 : 22, color: "#3A3025", maxWidth: 620 }}>
              Alle weetjes van dit jaar op één plek. {items.length} weetjes om opnieuw te lezen,
              de allerlaatste staat bovenaan.
            </div>
          </div>
          {!isMobile && (
            <img src="/assets/hete-peper-weetje.png" alt="Hete Peper denkt na"
              style={{
                width: 280, height: "auto", display: "block",
                marginTop: -30, marginBottom: -40, marginRight: -10,
                filter: "drop-shadow(6px 6px 0 rgba(0,0,0,0.22))",
                transform: "rotate(-3deg)",
                position: "relative", zIndex: 2,
              }} />
          )}
        </div>
      </section>

      {/* Zoekbalk */}
      <section className="hp-section" style={{ paddingTop: 18, paddingBottom: 4, position: "relative", zIndex: 1 }}>
        <div style={{
          display: "flex", alignItems: "center", gap: 8,
          background: "#F0FAE6", border: "3px solid #1A1A1A",
          padding: "4px 12px", boxShadow: "4px 4px 0 #1A1A1A",
          minHeight: 44,
          maxWidth: 520,
        }}>
          <span style={{ fontSize: 18 }}>🔍</span>
          <input
            value={zoek}
            onChange={e => setZoek(e.target.value)}
            placeholder="Zoek in alle weetjes..."
            style={{
              border: 0, outline: 0, background: "transparent",
              fontFamily: "'Patrick Hand', cursive", fontSize: 16,
              padding: "8px 0",
              width: "100%",
              minWidth: 0, flex: 1,
            }}
          />
        </div>
        <div style={{
          marginTop: 8, fontFamily: "'Patrick Hand', cursive",
          color: "#6B5A3D", fontSize: 15,
        }}>
          {filtered.length === items.length
            ? `📚 ${items.length} weetjes`
            : `📚 ${filtered.length} van ${items.length} weetjes`}
        </div>
      </section>

      {/* Tijdlijn */}
      <section className="hp-section" style={{ paddingTop: 12, paddingBottom: 40, position: "relative", zIndex: 1 }}>
        {filtered.length === 0 ? (
          <div style={{
            textAlign: "center", padding: 60, fontSize: 22, color: "#6B5A3D",
            background: "#F0FAE6", border: "4px dashed #6B5A3D",
          }}>
            Niets gevonden voor "{zoek}". Probeer iets anders!
          </div>
        ) : (
          groups.map(g => (
            <div key={g.label} style={{ marginBottom: 26 }}>
              <div style={{
                display: "inline-block",
                fontFamily: "'Bangers', sans-serif", fontSize: isMobile ? 22 : 28,
                background: "#1A1A1A", color: "#FFD23F",
                border: "3px solid #FFD23F", boxShadow: "4px 4px 0 #1A1A1A",
                padding: "4px 14px", letterSpacing: "0.08em",
                transform: "rotate(-1.5deg)",
                marginBottom: 14,
                textTransform: "uppercase",
              }}>
                {g.label}
              </div>
              <div style={{
                display: "grid",
                gridTemplateColumns: isMobile ? "1fr" : "repeat(auto-fill, minmax(320px, 1fr))",
                gap: 18,
              }}>
                {g.items.map(it => (
                  <WeetjeKaart key={it.key} weetje={it}
                    isToday={it.datum === todayKey}
                    open={openDatum === it.datum}
                    onToggle={() => setOpenDatum(openDatum === it.datum ? null : it.datum)} />
                ))}
              </div>
            </div>
          ))
        )}
      </section>
    </div>
  );
}

function WeetjeKaart({ weetje, isToday, open, onToggle }) {
  const heeftExtras = !!(weetje.uitleg || weetje.grapje);
  const dagLabel = `${weetje.dag} ${WEETJE_MAANDEN[weetje.maand]}`;

  return (
    <div style={{
      background: isToday ? "#FFD23F" : "#F0FAE6",
      border: isToday ? "5px solid #1A1A1A" : "4px solid #1A1A1A",
      boxShadow: isToday ? "8px 8px 0 #1A1A1A" : "5px 5px 0 #1A1A1A",
      padding: "14px 16px",
      position: "relative",
      transform: isToday ? "rotate(-0.6deg)" : "rotate(0.2deg)",
      display: "flex", flexDirection: "column", gap: 8,
    }}>
      <div style={{
        display: "flex", alignItems: "center", gap: 8,
        flexWrap: "wrap", justifyContent: "space-between",
      }}>
        <div style={{
          background: isToday ? "#E63946" : "#FFD23F",
          color: isToday ? "#FFF" : "#1A1A1A",
          border: "3px solid #1A1A1A", boxShadow: "2px 2px 0 #1A1A1A",
          padding: "3px 10px",
          fontFamily: "'Bangers', sans-serif", fontSize: 16,
          letterSpacing: "0.05em", whiteSpace: "nowrap",
          textShadow: isToday ? "1px 1px 0 #1A1A1A" : "none",
        }}>
          {dagLabel.toUpperCase()}
        </div>
        {isToday && (
          <div style={{
            background: "#1A1A1A", color: "#FFD23F",
            border: "3px solid #FFD23F", boxShadow: "2px 2px 0 #1A1A1A",
            padding: "3px 10px",
            fontFamily: "'Bangers', sans-serif", fontSize: 13,
            letterSpacing: "0.1em",
          }}>★ VANDAAG</div>
        )}
      </div>

      <div className="ballon" style={{
        fontSize: 17,
        lineHeight: 1.35,
        padding: "10px 14px",
        background: "#FFF",
      }}>
        {weetje.tekst}
      </div>

      {heeftExtras && (
        <div>
          <button onClick={onToggle} style={{
            background: open ? "#1A1A1A" : "#FFF",
            color: open ? "#FFD23F" : "#1A1A1A",
            border: "3px solid #1A1A1A",
            boxShadow: "3px 3px 0 #1A1A1A",
            padding: "5px 12px",
            fontFamily: "'Bangers', sans-serif", fontSize: 15,
            letterSpacing: "0.04em",
            cursor: "pointer",
            textShadow: open ? "1px 1px 0 #1A1A1A" : "none",
            transition: "background 0.12s, color 0.12s",
          }}>
            {open ? "▼ MINDER" : "▶ MEER LEZEN"}
          </button>
          {open && (
            <div style={{
              marginTop: 10, display: "flex", flexDirection: "column", gap: 8,
            }}>
              {weetje.uitleg && (
                <div style={{
                  background: "#F0FAE6", border: "3px solid #1A1A1A",
                  boxShadow: "3px 3px 0 #1A1A1A",
                  padding: "10px 14px", fontSize: 15, lineHeight: 1.35,
                }}>
                  <div style={{
                    fontFamily: "'Bangers', sans-serif", fontSize: 14,
                    color: "#6B5A3D", letterSpacing: "0.1em", marginBottom: 4,
                  }}>💡 UITLEG</div>
                  {weetje.uitleg}
                </div>
              )}
              {weetje.grapje && (
                <div style={{
                  background: "#FFE9F0", border: "3px solid #1A1A1A",
                  boxShadow: "3px 3px 0 #1A1A1A",
                  padding: "10px 14px", fontSize: 15, lineHeight: 1.35,
                }}>
                  <div style={{
                    fontFamily: "'Bangers', sans-serif", fontSize: 14,
                    color: "#B91566", letterSpacing: "0.1em", marginBottom: 4,
                  }}>😄 GRAPJE</div>
                  {weetje.grapje}
                </div>
              )}
            </div>
          )}
        </div>
      )}
    </div>
  );
}

Object.assign(window, { WeetjesHistoriekPagina });
