/* ============================================================
   wellbeing.jsx — Habits, Mood, Water, Sport, BalanceWheel
   ============================================================ */

function HabitsWidget() {
  const [habits, setHabits] = useLocalState("habits", HABITS_SEED);
  const [adding, setAdding] = useState(false);
  const [newName, setNewName] = useState("");
  const [newColor, setNewColor] = useState("var(--accent)");
  const todayIdx = (new Date().getDay() + 6) % 7; // Mon=0
  const doneToday = habits.filter(h => h.week[todayIdx]).length;

  const palette = ["var(--accent)", "var(--sage)", "var(--blue)", "var(--lilac)", "var(--amber)", "var(--rose)", "var(--teal)"];
  const icons = ["sparkle", "leaf", "book", "dumbbell", "moon", "compass", "heart", "droplet", "coffee", "sun"];

  const toggle = (id, dayIdx) => {
    setHabits(hs => hs.map(h => {
      if (h.id !== id) return h;
      const week = [...h.week];
      week[dayIdx] = week[dayIdx] ? 0 : 1;
      let streak = h.streak;
      if (dayIdx === todayIdx) streak = week[dayIdx] ? h.streak + 1 : Math.max(0, h.streak - 1);
      return { ...h, week, streak };
    }));
  };
  const addHabit = () => {
    const n = newName.trim();
    if (!n) return;
    const icon = icons[habits.length % icons.length];
    setHabits(hs => [...hs, { id: "h" + Date.now(), name: n, icon, color: newColor, streak: 0, week: [0,0,0,0,0,0,0] }]);
    setNewName(""); setNewColor("var(--accent)"); setAdding(false);
  };
  const removeHabit = (id) => setHabits(hs => hs.filter(h => h.id !== id));

  return (
    <div className="card fade-in" style={{ animationDelay: "0.12s" }}>
      <WHead icon="checkCircle" title="Gewoontes" sub={`${doneToday}/${habits.length} vandaag gedaan`} accent
        action={<Icon name="plus" style={{ transform: adding ? "rotate(45deg)" : "none", transition: "transform 0.2s" }} />}
        onAction={() => setAdding(a => !a)} />

      {adding && (
        <div style={{ display: "flex", flexDirection: "column", gap: 8, marginBottom: 12, padding: 12, borderRadius: 12, background: "var(--surface-2)", border: "1px solid var(--border)" }}>
          <div style={{ display: "flex", gap: 8 }}>
            <input autoFocus value={newName} onChange={e => setNewName(e.target.value)} onKeyDown={e => e.key === "Enter" && addHabit()}
              placeholder="Nieuwe gewoonte…"
              style={{ flex: 1, height: 36, border: "1px solid var(--border)", background: "var(--surface)", borderRadius: 9, padding: "0 11px", fontSize: 13.5, outline: "none" }} />
            <button className="btn btn-sm btn-accent" style={{ flexShrink: 0 }} onClick={addHabit}>Toevoegen</button>
          </div>
          <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
            {palette.map(c => (
              <button key={c} onClick={() => setNewColor(c)}
                style={{ width: 22, height: 22, borderRadius: "50%", background: c, flexShrink: 0,
                  boxShadow: newColor === c ? "0 0 0 2px var(--surface), 0 0 0 3.5px " + c : "inset 0 0 0 1px rgba(0,0,0,0.06)" }} />
            ))}
          </div>
        </div>
      )}

      <div style={{ display: "flex", justifyContent: "space-between", padding: "0 0 8px 0", marginLeft: "auto", gap: 4 }}>
        <span style={{ flex: 1 }} />
        {NL_DAYS.slice(1).concat(NL_DAYS[0]).map((d, i) => (
          <span key={i} style={{ width: 22, textAlign: "center", fontSize: 10.5, fontWeight: 700,
            color: i === todayIdx ? "var(--accent)" : "var(--text-3)" }}>{d}</span>
        ))}
        <span style={{ width: 24 }} />
      </div>
      <div style={{ display: "grid", gap: 8, flex: 1 }}>
        {habits.map(h => (
          <div key={h.id} className="habit-row" style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8, flex: 1, minWidth: 0 }}>
              <div style={{ width: 30, height: 30, borderRadius: 9, background: "var(--surface-3)", color: h.color, display: "grid", placeItems: "center", flexShrink: 0 }}>
                <Icon name={h.icon} width="16" height="16" />
              </div>
              <div style={{ minWidth: 0, flex: 1 }}>
                <div style={{ fontSize: 13, fontWeight: 650, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{h.name}</div>
                <div style={{ display: "flex", alignItems: "center", gap: 3, fontSize: 11, color: "var(--text-3)", fontWeight: 600 }}>
                  <Icon name="flame" width="11" height="11" style={{ color: "var(--accent)" }} /> {h.streak}
                </div>
              </div>
            </div>
            <div style={{ display: "flex", gap: 3, flexShrink: 0 }}>
              {h.week.map((on, di) => (
                <button key={di} onClick={() => toggle(h.id, di)} title={NL_DAYS_FULL[(di+1)%7]}
                  style={{
                    width: 22, height: 22, borderRadius: 7, flexShrink: 0,
                    border: di === todayIdx ? `1.5px solid ${on ? h.color : "var(--border-strong)"}` : "1.5px solid transparent",
                    background: on ? h.color : "var(--surface-3)",
                    color: "#fff", display: "grid", placeItems: "center",
                    transition: "all 0.15s",
                  }}>
                  {on ? <Icon name="check" width="13" height="13" /> : null}
                </button>
              ))}
            </div>
            <button className="row-del" onClick={() => removeHabit(h.id)} title="Verwijderen"><Icon name="minus" width="15" height="15" /></button>
          </div>
        ))}
        {habits.length === 0 && <div style={{ textAlign: "center", color: "var(--text-3)", fontSize: 13, padding: "16px 0", fontWeight: 600 }}>Nog geen gewoontes — voeg er een toe ✦</div>}
      </div>
    </div>
  );
}

function MoodWidget() {
  const [log, setLog] = useLocalState("mood", MOOD_SEED);
  const today = log[log.length - 1];
  const setToday = (v) => setLog(l => { const n = [...l]; n[n.length - 1] = v; return n; });
  const avg = (log.reduce((s, v) => s + v, 0) / log.length);
  const curMood = MOODS.find(m => m.v === today) || MOODS[2];

  return (
    <div className="card fade-in" style={{ animationDelay: "0.14s" }}>
      <WHead icon="smile" title="Stemming" sub={`Gem. ${avg.toFixed(1)} · 14 dagen`} accent />
      <div style={{ textAlign: "center", marginBottom: 4 }}>
        <div style={{ fontSize: 13, color: "var(--text-2)", fontWeight: 600 }}>Hoe voel je je vandaag?</div>
        <div style={{ display: "flex", justifyContent: "center", gap: 6, marginTop: 12 }}>
          {MOODS.map(m => (
            <button key={m.v} onClick={() => setToday(m.v)}
              style={{
                width: 46, height: 46, borderRadius: 13, fontSize: 23,
                background: today === m.v ? m.color : "var(--surface-3)",
                transform: today === m.v ? "scale(1.08)" : "scale(1)",
                filter: today === m.v ? "none" : "grayscale(0.4) opacity(0.7)",
                transition: "all 0.18s", lineHeight: 1,
              }}>{m.face}</button>
          ))}
        </div>
        <div style={{ marginTop: 10, fontSize: 13, fontWeight: 700, color: curMood.color }}>{curMood.label}</div>
      </div>
      <div className="divider" />
      <div>
        <div className="lbl" style={{ marginBottom: 8 }}>Afgelopen 14 dagen</div>
        <div style={{ display: "flex", alignItems: "flex-end", gap: 3, height: 52 }}>
          {log.map((v, i) => {
            const m = MOODS.find(mm => mm.v === v) || MOODS[2];
            return <div key={i} title={m.label} style={{ flex: 1, height: `${(v/5)*100}%`, background: m.color,
              borderRadius: 3, opacity: i === log.length - 1 ? 1 : 0.55, transition: "all 0.3s" }} />;
          })}
        </div>
      </div>
    </div>
  );
}

function WaterWidget({ goal = WATER_GOAL }) {
  const [glasses, setGlasses] = useLocalState("water", WATER_START);
  const pct = Math.round((glasses / goal) * 100);
  return (
    <div className="card fade-in" style={{ animationDelay: "0.16s" }}>
      <WHead icon="droplet" title="Water" sub={`Doel ${goal} glazen`} accent />
      <div style={{ display: "flex", alignItems: "center", gap: 16, flex: 1 }}>
        <Ring value={glasses} max={goal} size={88} stroke={10} color="var(--blue)">
          <div>
            <div className="big-num" style={{ fontSize: 22, color: "var(--blue)" }}>{glasses}</div>
            <div style={{ fontSize: 10, color: "var(--text-3)", fontWeight: 700 }}>{pct}%</div>
          </div>
        </Ring>
        <div style={{ flex: 1 }}>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 6, marginBottom: 12 }}>
            {Array.from({ length: goal }).map((_, i) => (
              <div key={i} style={{
                width: 18, height: 24, borderRadius: "4px 4px 6px 6px",
                border: `1.5px solid ${i < glasses ? "var(--blue)" : "var(--border-strong)"}`,
                background: i < glasses ? "var(--blue)" : "transparent",
                transition: "all 0.2s",
              }} />
            ))}
          </div>
          <div style={{ display: "flex", gap: 8 }}>
            <button className="round-btn" onClick={() => setGlasses(g => Math.max(0, g - 1))}><Icon name="minus" /></button>
            <button className="btn btn-sm" style={{ flex: 1, background: "var(--blue)", color: "#fff" }}
              onClick={() => setGlasses(g => Math.min(goal + 4, g + 1))}>
              <Icon name="plus" /> Glas
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

function SportWidget({ goal = SPORT_GOAL_MIN }) {
  const total = SPORT_MIN_WEEK.reduce((s, m) => s + m, 0);
  const sessions = SPORT_WEEK.filter(Boolean).length;
  const pct = Math.round((total / goal) * 100);
  const maxMin = Math.max(...SPORT_MIN_WEEK, 1);
  return (
    <div className="card fade-in" style={{ animationDelay: "0.18s" }}>
      <WHead icon="dumbbell" title="Beweging" sub={`${sessions} sessies deze week`} accent />
      <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
        <Ring value={total} max={goal} size={84} stroke={10} color="var(--accent)">
          <div>
            <div className="big-num" style={{ fontSize: 18 }}>{total}</div>
            <div style={{ fontSize: 9.5, color: "var(--text-3)", fontWeight: 700 }}>MIN</div>
          </div>
        </Ring>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 12.5, color: "var(--text-2)", fontWeight: 600 }}>Weekdoel</div>
          <div className="big-num" style={{ fontSize: 16 }}>{pct}% <span style={{ color: "var(--text-3)", fontSize: 12 }}>van {goal} min</span></div>
          <div style={{ display: "flex", alignItems: "flex-end", gap: 4, height: 38, marginTop: 10 }}>
            {SPORT_MIN_WEEK.map((m, i) => (
              <div key={i} style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center", gap: 3 }}>
                <div style={{ width: "100%", height: 28, display: "flex", alignItems: "flex-end" }}>
                  <div style={{ width: "100%", height: `${clamp((m/maxMin)*100, m?12:0, 100)}%`,
                    background: m ? "var(--accent)" : "var(--surface-3)", borderRadius: 3, transition: "height 0.4s" }} />
                </div>
                <span style={{ fontSize: 9, color: "var(--text-3)", fontWeight: 700 }}>{NL_DAYS.slice(1).concat(NL_DAYS[0])[i]}</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

function BalanceWheelWidget() {
  const [data, setData] = useLocalState("balance", BALANCE_SEED);
  const size = 168, cx = size / 2, cy = size / 2, R = 64;
  const n = data.length;
  const angle = (i) => (Math.PI * 2 * i) / n - Math.PI / 2;
  const pt = (i, frac) => [cx + Math.cos(angle(i)) * R * frac, cy + Math.sin(angle(i)) * R * frac];
  const poly = data.map((d, i) => pt(i, d.v / 10).join(",")).join(" ");
  const bump = (i) => setData(arr => arr.map((d, j) => j === i ? { ...d, v: d.v >= 10 ? 3 : d.v + 1 } : d));
  const avg = (data.reduce((s, d) => s + d.v, 0) / n).toFixed(1);

  return (
    <div className="card fade-in" style={{ animationDelay: "0.2s" }}>
      <WHead icon="compass" title="Levensbalans" sub={`Gem. ${avg}/10 · tik om aan te passen`} accent />
      <div style={{ display: "flex", gap: 8, alignItems: "center", flex: 1 }}>
        <svg width={size} height={size} style={{ flexShrink: 0 }}>
          {[0.25, 0.5, 0.75, 1].map((f, k) => (
            <polygon key={k} points={data.map((_, i) => pt(i, f).join(",")).join(" ")}
              fill="none" stroke="var(--border)" strokeWidth="1" />
          ))}
          {data.map((_, i) => {
            const [x, y] = pt(i, 1);
            return <line key={i} x1={cx} y1={cy} x2={x} y2={y} stroke="var(--border)" strokeWidth="1" />;
          })}
          <polygon points={poly} fill="var(--accent-weak)" stroke="var(--accent)" strokeWidth="2"
            style={{ transition: "all 0.4s" }} />
          {data.map((d, i) => {
            const [x, y] = pt(i, d.v / 10);
            return <circle key={i} cx={x} cy={y} r="3.5" fill="var(--surface)" stroke={d.color} strokeWidth="2.2"
              style={{ transition: "all 0.4s" }} />;
          })}
        </svg>
        <div style={{ display: "grid", gap: 5, flex: 1 }}>
          {data.map((d, i) => (
            <button key={i} onClick={() => bump(i)}
              style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8,
                padding: "5px 8px", borderRadius: 8, background: "var(--surface-2)", border: "1px solid var(--border)", transition: "all 0.15s" }}>
              <span style={{ display: "flex", alignItems: "center", gap: 6, fontSize: 12, fontWeight: 650 }}>
                <span style={{ width: 7, height: 7, borderRadius: 99, background: d.color }} />{d.label}
              </span>
              <span className="mono" style={{ fontSize: 12.5, fontWeight: 700, color: d.color }}>{d.v}</span>
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { HabitsWidget, MoodWidget, WaterWidget, SportWidget, BalanceWheelWidget });
