// Dagprogramma + Stemmen

function ProgramScreen({ me, now, demoDate }) {
  const H = window.kretaHelpers;
  const DATA = window.CORVEE_DATA;
  const today = demoDate || now;
  const todayStr = today.toISOString().slice(0, 10);
  const [selectedDate, setSelectedDate] = React.useState(todayStr);

  const state = H.loadState();
  const programs = state.programs || {};
  const program = programs[selectedDate] || [];

  const [newItem, setNewItem] = React.useState({ time: "10:00", text: "" });

  const saveProgram = (list) => {
    const s = H.loadState();
    s.programs = { ...(s.programs || {}), [selectedDate]: list };
    H.saveState(s);
  };

  const addItem = () => {
    if (!newItem.text.trim()) return;
    const list = [...program, { id: Date.now(), time: newItem.time, text: newItem.text.trim(), by: me.id }];
    list.sort((a, b) => a.time.localeCompare(b.time));
    saveProgram(list);
    setNewItem({ time: newItem.time, text: "" });
  };

  const remove = (id) => saveProgram(program.filter(x => x.id !== id));

  // Ideeën suggesties
  const ideeen = [
    { time: "09:00", text: "🏊 Ochtendzwem in zee" },
    { time: "10:00", text: "🚗 Uitstapje naar Chania oude stad" },
    { time: "11:00", text: "🫒 Olijfboerderij bezoek" },
    { time: "14:00", text: "🏖️ Stranddag Balos" },
    { time: "14:00", text: "🥾 Wandeling Samaria kloof" },
    { time: "15:00", text: "🍦 IJsjes in het dorp" },
    { time: "16:00", text: "🏺 Knossos archeologische site" },
    { time: "17:00", text: "🍸 Zonsondergang-drankje" },
    { time: "19:00", text: "🎭 Spelletjesavond" },
    { time: "20:00", text: "🎸 Muziekavond aan tafel" },
  ];

  return (
    <div className="screen">
      <h1 className="serif" style={{ fontSize: 30, margin: "8px 0 2px", letterSpacing: -0.6 }}>
        Dagprogramma 🏖️
      </h1>
      <div className="section-sub">Plan samen wat jullie gaan doen</div>

      <div className="hscroll" style={{ marginBottom: 18 }}>
        {DATA.days.map(d => {
          const isActive = d.date === selectedDate;
          const isToday = d.date === todayStr;
          const count = (programs[d.date] || []).length;
          return (
            <button
              key={d.date}
              onClick={() => setSelectedDate(d.date)}
              style={{
                appearance: "none", border: "none", cursor: "pointer",
                padding: "10px 12px", minWidth: 58, borderRadius: 14,
                background: isActive ? "var(--aegean)" : "white",
                color: isActive ? "white" : "var(--ink)",
                border: isActive ? "none" : "1px solid var(--line-soft)",
                fontFamily: "inherit",
                boxShadow: isActive ? "0 4px 12px rgba(26,84,144,0.3)" : "none",
                textAlign: "center", position: "relative",
              }}
            >
              <div style={{ fontSize: 10, fontWeight: 600, textTransform: "uppercase", opacity: 0.75 }}>
                {d.label.split(" ")[0]}
              </div>
              <div className="serif" style={{ fontSize: 18, fontWeight: 700, lineHeight: 1.1, marginTop: 2 }}>
                {d.label.split(" ")[1]}
              </div>
              {count > 0 && (
                <div style={{
                  position: "absolute", top: 4, right: 4,
                  minWidth: 16, height: 16, borderRadius: 8,
                  background: isActive ? "var(--sun)" : "var(--bougainvillea)",
                  color: "white", fontSize: 10, fontWeight: 700,
                  display: "flex", alignItems: "center", justifyContent: "center",
                  padding: "0 4px",
                }}>{count}</div>
              )}
              {isToday && !isActive && count === 0 && (
                <div style={{
                  position: "absolute", top: 4, right: 6,
                  width: 6, height: 6, borderRadius: "50%",
                  background: "var(--bougainvillea)",
                }} />
              )}
            </button>
          );
        })}
      </div>

      <div className="card" style={{ marginBottom: 14 }}>
        <div className="tiny-mute" style={{ marginBottom: 8, color: "var(--aegean)" }}>
          {H.formatDateNL(selectedDate)}
        </div>
        {program.length === 0 ? (
          <div style={{ padding: "20px 0", textAlign: "center", color: "var(--muted)", fontSize: 13 }}>
            Nog geen plannen. Voeg iets toe hieronder.
          </div>
        ) : (
          program.map((item, i) => {
            const p = H.getPerson(item.by);
            return (
              <div key={item.id} style={{
                display: "flex", gap: 12, alignItems: "center",
                padding: "10px 0",
                borderBottom: i < program.length - 1 ? "1px solid var(--line-soft)" : "none",
              }}>
                <div className="serif" style={{ fontSize: 18, fontWeight: 700, color: "var(--aegean)", width: 50 }}>
                  {item.time}
                </div>
                <div style={{ flex: 1, fontSize: 14 }}>
                  {item.text}
                  {p && <div style={{ fontSize: 11, color: "var(--muted)", marginTop: 2 }}>door {p.name}</div>}
                </div>
                <button onClick={() => remove(item.id)} style={{
                  appearance: "none", border: "none", background: "transparent",
                  cursor: "pointer", color: "var(--muted)", fontSize: 18,
                }}>✕</button>
              </div>
            );
          })
        )}
      </div>

      <div className="card" style={{ marginBottom: 14 }}>
        <div className="tiny-mute" style={{ marginBottom: 8 }}>Voeg toe</div>
        <div style={{ display: "flex", gap: 8, marginBottom: 8 }}>
          <input
            type="time"
            value={newItem.time}
            onChange={e => setNewItem(n => ({ ...n, time: e.target.value }))}
            style={{ padding: 10, borderRadius: 8, border: "1px solid var(--line)", fontFamily: "inherit", fontSize: 14, width: 100 }}
          />
          <input
            type="text"
            value={newItem.text}
            onChange={e => setNewItem(n => ({ ...n, text: e.target.value }))}
            onKeyDown={e => e.key === "Enter" && addItem()}
            placeholder="Wat gaan we doen?"
            style={{ flex: 1, padding: 10, borderRadius: 8, border: "1px solid var(--line)", fontFamily: "inherit", fontSize: 14 }}
          />
        </div>
        <button className="btn btn-primary" onClick={addItem} style={{ width: "100%", fontSize: 14 }}>
          + Toevoegen aan programma
        </button>
      </div>

      <div className="section-title" style={{ fontSize: 16 }}>Ideeën 💡</div>
      <div className="card" style={{ padding: 10 }}>
        <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
          {ideeen.map((idee, i) => (
            <button
              key={i}
              onClick={() => {
                const list = [...program, { id: Date.now() + i, time: idee.time, text: idee.text, by: me.id }];
                list.sort((a, b) => a.time.localeCompare(b.time));
                saveProgram(list);
              }}
              style={{
                appearance: "none", border: "1px solid var(--line)", cursor: "pointer",
                padding: "6px 10px", borderRadius: 999,
                background: "white", fontFamily: "inherit", fontSize: 12,
                color: "var(--ink-soft)",
              }}
            >
              + {idee.text}
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}

// Stemmen - 2 polls-ingebouwd + nieuwe maken
function VotingScreen({ me }) {
  const H = window.kretaHelpers;
  const [polls, setPolls] = React.useState(() => {
    const s = H.loadState();
    return s.polls || [
      {
        id: 1, question: "Waar gaan we morgen heen?",
        by: "marije", ts: Date.now() - 7200000,
        options: [
          { id: "a", text: "🏖️ Stranddag Balos", votes: {} },
          { id: "b", text: "🥾 Samaria kloof wandeling", votes: {} },
          { id: "c", text: "🏺 Knossos + lunch", votes: {} },
        ],
      },
      {
        id: 2, question: "Wat eten we zondag?",
        by: "martin", ts: Date.now() - 3600000,
        options: [
          { id: "a", text: "🐟 Gegrilde vis", votes: {} },
          { id: "b", text: "🍖 Souvlaki spiesjes", votes: {} },
          { id: "c", text: "🥗 Grote mezze-tafel", votes: {} },
        ],
      },
    ];
  });

  const [newPoll, setNewPoll] = React.useState({ question: "", options: ["", ""] });
  const [showNew, setShowNew] = React.useState(false);

  const save = (list) => {
    const s = H.loadState();
    s.polls = list;
    H.saveState(s);
    setPolls(list);
  };

  const vote = (pollId, optId) => {
    save(polls.map(p => {
      if (p.id !== pollId) return p;
      return {
        ...p,
        options: p.options.map(o => {
          const votes = { ...o.votes };
          if (o.id === optId) votes[me.id] = Date.now();
          else delete votes[me.id];
          return { ...o, votes };
        }),
      };
    }));
  };

  const addPoll = () => {
    if (!newPoll.question.trim() || newPoll.options.filter(o => o.trim()).length < 2) return;
    const opts = newPoll.options.filter(o => o.trim()).map((o, i) => ({ id: String.fromCharCode(97 + i), text: o, votes: {} }));
    save([{ id: Date.now(), question: newPoll.question.trim(), by: me.id, ts: Date.now(), options: opts }, ...polls]);
    setNewPoll({ question: "", options: ["", ""] });
    setShowNew(false);
  };

  return (
    <div className="screen">
      <h1 className="serif" style={{ fontSize: 30, margin: "8px 0 2px", letterSpacing: -0.6 }}>
        Stemmen 🗳️
      </h1>
      <div className="section-sub">Democratisch en al — samen beslissen</div>

      <button
        className="btn btn-primary"
        onClick={() => setShowNew(s => !s)}
        style={{ width: "100%", marginBottom: 14 }}
      >
        {showNew ? "Annuleer" : "+ Nieuwe stemming"}
      </button>

      {showNew && (
        <div className="card" style={{ marginBottom: 14 }}>
          <input
            type="text"
            placeholder="Wat is de vraag?"
            value={newPoll.question}
            onChange={e => setNewPoll(n => ({ ...n, question: e.target.value }))}
            style={{ width: "100%", padding: 10, borderRadius: 8, border: "1px solid var(--line)", fontFamily: "inherit", fontSize: 15, fontWeight: 600, marginBottom: 10 }}
          />
          {newPoll.options.map((o, i) => (
            <div key={i} style={{ display: "flex", gap: 8, marginBottom: 8 }}>
              <input
                type="text"
                placeholder={`Optie ${i + 1}`}
                value={o}
                onChange={e => setNewPoll(n => ({ ...n, options: n.options.map((x, j) => j === i ? e.target.value : x) }))}
                style={{ flex: 1, padding: 10, borderRadius: 8, border: "1px solid var(--line)", fontFamily: "inherit", fontSize: 13 }}
              />
              {newPoll.options.length > 2 && (
                <button onClick={() => setNewPoll(n => ({ ...n, options: n.options.filter((_, j) => j !== i) }))} style={{ appearance: "none", border: "none", background: "transparent", cursor: "pointer", color: "var(--muted)" }}>✕</button>
              )}
            </div>
          ))}
          <div style={{ display: "flex", gap: 8 }}>
            <button onClick={() => setNewPoll(n => ({ ...n, options: [...n.options, ""] }))} className="btn btn-ghost" style={{ flex: 1, fontSize: 12, padding: "8px 10px", border: "1px solid var(--line)" }}>
              + Optie
            </button>
            <button onClick={addPoll} className="btn btn-primary" style={{ flex: 1, fontSize: 13, padding: "8px 10px" }}>
              Plaats
            </button>
          </div>
        </div>
      )}

      {polls.map(poll => {
        const totalVotes = poll.options.reduce((s, o) => s + Object.keys(o.votes).length, 0);
        const myVote = poll.options.find(o => o.votes[me.id])?.id;
        const winningVotes = Math.max(...poll.options.map(o => Object.keys(o.votes).length));
        const by = H.getPerson(poll.by);
        return (
          <div key={poll.id} className="card" style={{ marginBottom: 14 }}>
            <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", marginBottom: 4 }}>
              <div style={{ fontSize: 11, color: "var(--muted)", fontWeight: 600, textTransform: "uppercase", letterSpacing: 0.5 }}>
                {by?.name || "?"} vraagt
              </div>
              <div style={{ fontSize: 11, color: "var(--muted)" }}>{totalVotes} {totalVotes === 1 ? "stem" : "stemmen"}</div>
            </div>
            <div className="serif" style={{ fontSize: 19, fontWeight: 700, marginBottom: 12, letterSpacing: -0.2 }}>
              {poll.question}
            </div>
            {poll.options.map(o => {
              const n = Object.keys(o.votes).length;
              const pct = totalVotes > 0 ? (n / totalVotes) * 100 : 0;
              const isMine = myVote === o.id;
              const isWinning = n > 0 && n === winningVotes;
              return (
                <div
                  key={o.id}
                  onClick={() => vote(poll.id, o.id)}
                  style={{
                    position: "relative",
                    padding: "10px 14px",
                    marginBottom: 6,
                    borderRadius: 10,
                    background: "var(--stucco)",
                    cursor: "pointer",
                    overflow: "hidden",
                    border: isMine ? "2px solid var(--aegean)" : "2px solid transparent",
                    transition: "all 0.15s",
                  }}
                >
                  <div style={{
                    position: "absolute", top: 0, left: 0, bottom: 0,
                    width: pct + "%",
                    background: isWinning ? "rgba(123,160,91,0.25)" : "rgba(26,84,144,0.12)",
                    transition: "width 0.5s",
                  }} />
                  <div style={{ position: "relative", display: "flex", alignItems: "center", gap: 10 }}>
                    <div style={{ flex: 1, fontWeight: isMine ? 700 : 500, fontSize: 14 }}>
                      {o.text}
                    </div>
                    <div style={{ display: "flex", gap: 4 }}>
                      {Object.keys(o.votes).slice(0, 5).map(pid => {
                        const p = H.getPerson(pid);
                        return <div key={pid} style={{
                          width: 20, height: 20, borderRadius: "50%", background: p?.color,
                          color: "white", fontSize: 10, fontWeight: 700,
                          display: "flex", alignItems: "center", justifyContent: "center",
                          border: "1.5px solid white",
                        }}>{p?.name[0]}</div>;
                      })}
                    </div>
                    <div style={{ fontWeight: 700, fontSize: 13, minWidth: 34, textAlign: "right" }}>
                      {Math.round(pct)}%
                    </div>
                  </div>
                </div>
              );
            })}
            {myVote && (
              <div style={{ fontSize: 11, color: "var(--muted)", textAlign: "center", marginTop: 4 }}>
                ✓ Je hebt gestemd · tik op een andere optie om te wijzigen
              </div>
            )}
          </div>
        );
      })}
    </div>
  );
}

Object.assign(window, { ProgramScreen, VotingScreen });
