(function(){
// ============================================================
// habits.jsx — Gewohnheiten-Tracker
// Components: HabitView, HabitForm, SportIcon
// Depends on (window): todayISO, localISO
// ============================================================

const { useState } = React;

// Alle verfügbaren Icons aus habit-icons/
const HABIT_ICONS = [
  // Sport
  { key: "runner",     label: "Laufen"      },
  { key: "bicycle",    label: "Velo"        },
  { key: "dumbbell",   label: "Gym"         },
  { key: "swimming",   label: "Schwimmen"   },
  { key: "yoga",       label: "Yoga"        },
  { key: "walk",       label: "Spazieren"   },
  { key: "hiking",     label: "Wandern"     },
  { key: "stretch",    label: "Dehnen"      },
  { key: "activity",   label: "Aktivität"   },
  { key: "basketball", label: "Basketball"  },
  { key: "boxing",     label: "Boxen"       },
  { key: "soccer",     label: "Fussball"    },
  { key: "tennis",     label: "Tennis"      },
  { key: "golf",       label: "Golf"        },
  { key: "stopwatch",  label: "Workout"     },
  { key: "target",     label: "Ziel"        },
  { key: "trophy",     label: "Trophy"      },
  // Gesundheit & Lifestyle
  { key: "water",      label: "Wasser"      },
  { key: "sleep",      label: "Schlafen"    },
  { key: "vitamins",   label: "Vitamine"    },
  { key: "medicine",   label: "Medizin"     },
  { key: "healthy",    label: "Gesund"      },
  { key: "skincare",   label: "Hautpflege"  },
  { key: "teeth",      label: "Zähne"       },
  { key: "sunrise",    label: "Frühaufsteher"},
  // Geist & Entspannung
  { key: "meditation", label: "Meditation"  },
  { key: "reading",    label: "Lesen"       },
  { key: "journaling", label: "Tagebuch"    },
  { key: "gratitude",  label: "Dankbarkeit" },
  { key: "pray",       label: "Beten"       },
  // Produktivität
  { key: "study",      label: "Lernen"      },
  { key: "coding",     label: "Coden"       },
  { key: "music",      label: "Musik"       },
  { key: "money",      label: "Finanzen"    },
  // Haushalt
  { key: "cook",       label: "Kochen"      },
  { key: "cleaning",   label: "Putzen"      },
  { key: "laundry",    label: "Wäsche"      },
  // Verzicht
  { key: "nosmoking",  label: "Nicht rauchen"},
  { key: "alcohol",    label: "Kein Alkohol" },
  { key: "nophone",    label: "Kein Handy"   },
  { key: "screentime", label: "Weniger Screen"},
];

// Fallback: alte icon-keys auf neue mappen
const ICON_KEY_MAP = {
  run: "runner", bike: "bicycle", gym: "dumbbell", swim: "swimming",
  walk: "walk", yoga: "yoga", stretch: "stretch", other: "activity"
};

function resolveIconKey(key) {
  if (!key) return "activity";
  if (ICON_KEY_MAP[key]) return ICON_KEY_MAP[key];
  if (HABIT_ICONS.find(i => i.key === key)) return key;
  return "activity";
}

function SportIcon({ iconKey, size, color }) {
  size = size || 20;
  const resolved = resolveIconKey(iconKey);
  // color filter: wenn accent-farbe → CSS filter; sonst grau
  const isAccent = !color || color === "var(--col-accent)";
  const style = {
    width: size, height: size,
    display: "block",
    opacity: isAccent ? 1 : 0.45,
    filter: isAccent ? "var(--icon-accent-filter, none)" : "none",
  };
  return React.createElement("img", {
    src: "./habit-icons/" + resolved + ".svg",
    width: size, height: size,
    alt: resolved,
    style,
    draggable: false
  });
}

function HabitView({ habits, onAdd, onUpdate, onDelete, isMobile }) {
  const [showForm, setShowForm] = useState(false);
  const [viewMode, setViewMode] = useState("week"); // FEATURE: Monats-Habittracker
  const [monthOffset, setMonthOffset] = useState(0);
  const today = todayISO();
  habits = (habits || []).filter(h => !h.deletedAt);

  // Letzte 7 Tage (älteste zuerst, heute letzte)
  const DAY_KEYS=["habit.day.sun","habit.day.mon","habit.day.tue","habit.day.wed","habit.day.thu","habit.day.fri","habit.day.sat"];
  const days = Array.from({length: 7}, (_, i) => {
    const d = new Date();
    d.setDate(d.getDate() - 6 + i);
    const iso = localISO(d);
    return {
      iso,
      label: t(DAY_KEYS[d.getDay()]),
      date: d.getDate(),
      isToday: iso === today
    };
  });

  // Tage des angezeigten Monats (für Monats-Ansicht)
  const monthBase = new Date();
  monthBase.setDate(1);
  monthBase.setMonth(monthBase.getMonth() + monthOffset);
  const monthLabel = monthBase.toLocaleDateString(window.currentLang==="en"?"en-GB":"de-CH", {month:"long", year:"numeric"});
  const daysInMonth = new Date(monthBase.getFullYear(), monthBase.getMonth()+1, 0).getDate();
  const monthDays = Array.from({length: daysInMonth}, (_, i) => {
    const d = new Date(monthBase.getFullYear(), monthBase.getMonth(), i+1);
    const iso = localISO(d);
    return { iso, date: i+1, isToday: iso === today };
  });

  function isCompleted(habit, iso) {
    return (habit.completions || []).includes(iso);
  }

  function toggleCompletion(habit, iso) {
    if (iso > today) return;
    const c = habit.completions || [];
    onUpdate({...habit,
      completions: c.includes(iso) ? c.filter(d => d !== iso) : [...c, iso],
      updatedAt: Date.now()
    });
  }

  // Returns Monday-ISO of the week containing dateIso
  function weekOf(dateIso) {
    const d = new Date(dateIso + "T12:00:00");
    const dow = (d.getDay() + 6) % 7; // 0=Mon
    d.setDate(d.getDate() - dow);
    return localISO(d);
  }

  function getStreak(habit) {
    const set = new Set(habit.completions || []);
    let streak = 0, gapUsed = false; // FIXED C3: grace day option added
    const d = new Date(today + "T12:00:00");
    for (let i = 0; i < 365; i++) {
      if (set.has(localISO(d))) { streak++; }
      else if (habit.graceDay && !gapUsed) { gapUsed = true; }
      else { break; }
      d.setDate(d.getDate() - 1);
    }
    return streak;
  }

  function getLongest(habit) {
    const set = new Set(habit.completions || []);
    if (!set.size) return 0;
    const earliest = [...set].sort()[0];
    const d = new Date(today + "T12:00:00");
    let best = 0, cur = 0, gapUsed = false; // FIXED C3: grace day option added
    while (localISO(d) >= earliest) {
      if (set.has(localISO(d))) { cur++; best = Math.max(best, cur); }
      else if (habit.graceDay && !gapUsed) { gapUsed = true; }
      else { cur = 0; gapUsed = false; }
      d.setDate(d.getDate() - 1);
    }
    return best;
  }

  function getDays30(habit) {
    const set = new Set(habit.completions || []);
    const base = new Date(today + "T12:00:00");
    base.setDate(base.getDate() - 29);
    let done = 0;
    for (let i = 0; i < 30; i++) {
      const d = new Date(base); d.setDate(d.getDate() + i);
      if (localISO(d) > today) break;
      if (set.has(localISO(d))) done++;
    }
    return done;
  }

  const todayDone = habits.filter(h => isCompleted(h, today)).length;
  const maxStreak = habits.length > 0 ? Math.max(...habits.map(getStreak)) : 0;
  const maxLongest = habits.length > 0 ? Math.max(...habits.map(getLongest)) : 0;
  const totalDays30 = habits.length > 0
    ? Math.round(habits.reduce((s, h) => s + getDays30(h), 0) / habits.length)
    : 0;

  return (
    <div>
      <div style={{display:"flex",justifyContent:"space-between",alignItems:"flex-end",marginBottom:20,paddingBottom:12,borderBottom:"1px solid var(--col-border-soft)"}}>
        <div>
          <div style={{fontSize:13,color:"var(--col-text-sec)",marginTop:4}}>
            {habits.length === 0 ? t("habit.noneYet") :
             t("habit.doneToday",{done:todayDone,total:habits.length}) + (maxStreak > 0 ? t("habit.streakSuffix",{n:maxStreak}) : "")}
          </div>
        </div>
        <div style={{display:"flex",gap:8,alignItems:"center"}}>
          <div style={{display:"flex",border:"1px solid var(--col-border)",borderRadius:20,overflow:"hidden"}}>
            {[["week",t("habit.week")],["month",t("habit.month")]].map(([id,label])=>(
              <button key={id} type="button" onClick={()=>{setViewMode(id);if(id==="week")setMonthOffset(0);}}
                style={{padding:"6px 14px",fontSize:12,border:"none",cursor:"pointer",fontFamily:"var(--sans)",fontWeight:viewMode===id?600:400,
                  background:viewMode===id?"var(--col-accent)":"transparent",color:viewMode===id?"var(--col-bg)":"var(--col-text-sec)"}}>
                {label}
              </button>
            ))}
          </div>
          <button type="button" onClick={() => setShowForm(s => !s)}
            style={{padding:"7px 16px",borderRadius:20,background:"var(--col-accent)",color:"var(--col-bg)",fontSize:12,border:"none",cursor:"pointer",fontFamily:"var(--sans)",fontWeight:500}}>
            {showForm ? t("habit.close") : t("habit.new")}
          </button>
        </div>
      </div>

      {viewMode==="month"&&(
        <div style={{display:"flex",alignItems:"center",justifyContent:"center",gap:14,marginBottom:16}}>
          <button type="button" onClick={()=>setMonthOffset(o=>o-1)} style={{background:"none",border:"1px solid var(--col-border)",borderRadius:"50%",width:28,height:28,cursor:"pointer",color:"var(--col-text-sec)",fontSize:13}}>‹</button>
          <div className="serif" style={{fontSize:15,fontStyle:"italic",color:"var(--col-text)",minWidth:140,textAlign:"center",textTransform:"capitalize"}}>{monthLabel}</div>
          <button type="button" onClick={()=>setMonthOffset(o=>Math.min(0,o+1))} disabled={monthOffset>=0} style={{background:"none",border:"1px solid var(--col-border)",borderRadius:"50%",width:28,height:28,cursor:monthOffset>=0?"default":"pointer",color:monthOffset>=0?"var(--col-text-3)":"var(--col-text-sec)",fontSize:13,opacity:monthOffset>=0?0.4:1}}>›</button>
        </div>
      )}

      {showForm && (
        <HabitForm onSave={h => { onAdd(h); setShowForm(false); }} onCancel={() => setShowForm(false)}/>
      )}

      {habits.length === 0 && !showForm && (
        <p className="serif" style={{fontSize:14,color:"var(--col-text-sec)",fontStyle:"italic",padding:"24px 0"}}>
          {t("habit.createFirst")}
        </p>
      )}

      {habits.length > 0 && viewMode==="week" && (
        <>
          {/* Tages-Header */}
          <div style={{display:"grid",gridTemplateColumns:"1fr repeat(7,38px)",gap:6,marginBottom:8,alignItems:"center",paddingBottom:8,borderBottom:"1px solid var(--col-border-soft)"}}>
            <div/>
            {days.map(d => (
              <div key={d.iso} style={{textAlign:"center"}}>
                <div className="mono" style={{fontSize:10,color:d.isToday?"var(--col-accent)":"var(--col-text-3)",letterSpacing:".04em",fontWeight:d.isToday?600:400}}>{d.label.slice(0,2)}</div>
                <div className="mono" style={{fontSize:9,color:d.isToday?"var(--col-accent)":"var(--col-text-3)"}}>{d.date}</div>
              </div>
            ))}
          </div>

          {/* Gewohnheits-Zeilen */}
          {habits.map(h => {
            const streak = getStreak(h);
            return (
              <div key={h.id} style={{background:"var(--col-bg)",border:"1px solid var(--col-border-soft)",borderRadius:10,padding:"12px 14px",marginBottom:8}}>
                <div style={{display:"grid",gridTemplateColumns:"1fr repeat(7,38px)",gap:6,alignItems:"center"}}>
                  <div style={{display:"flex",alignItems:"center",gap:8,minWidth:0}}>
                    <span style={{flexShrink:0,display:"flex",alignItems:"center"}}>
                      <SportIcon iconKey={h.icon || h.emoji} size={22} color="var(--col-accent)"/>
                    </span>
                    <div style={{minWidth:0,flex:1}}>
                      <div style={{fontSize:13,fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}}>{h.name}</div>
                      <div style={{fontSize:11,marginTop:1,color:"var(--col-text-3)"}}>
                        {(()=>{
                          const ws=weekOf(today);
                          const we=new Date(ws+"T12:00:00");we.setDate(we.getDate()+6);const wEnd=localISO(we);
                          const doneDays=(h.completions||[]).filter(iso=>iso>=ws&&iso<=wEnd&&iso<=today)
                            .map(iso=>t(DAY_KEYS[new Date(iso+"T12:00:00").getDay()]));
                          if(doneDays.length===0)return<span style={{color:"var(--col-text-3)"}}>{t("habit.nothingThisWeek")}</span>;
                          const td=isCompleted(h,today);
                          return<span style={{color:td?"#166534":"var(--col-accent)",fontWeight:500}}>{doneDays.join(", ")}{td?" ✓":""}</span>;
                        })()}
                      </div>
                    </div>
                    <button type="button" onClick={() => onDelete(h.id)}
                      style={{background:"none",border:"none",color:"var(--col-text-3)",fontSize:16,cursor:"pointer",padding:0,flexShrink:0,opacity:0.4}}
                      title={t("habit.delete")}>×</button>
                  </div>
                  {days.map(d => {
                    const done = isCompleted(h, d.iso);
                    const future = d.iso > today;
                    return (
                      <div key={d.iso}
                        onClick={() => !future && toggleCompletion(h, d.iso)}
                        style={{
                          width:34,height:34,borderRadius:"50%",
                          display:"flex",alignItems:"center",justifyContent:"center",
                          margin:"0 auto",cursor:future?"default":"pointer",
                          fontSize:done?14:12,
                          background: done ? (d.isToday?"var(--col-accent)":"#166534") : "transparent",
                          border: done ? "none" : d.isToday ? "2px solid var(--col-accent)" : future ? "1.5px dashed var(--col-border)" : "1.5px solid var(--col-border)",
                          color: done ? "white" : d.isToday ? "var(--col-accent)" : "var(--col-text-3)",
                          boxShadow: done && d.isToday ? "0 0 0 3px var(--col-accent-wash)" : "none",
                          transition:"all .12s"
                        }}>
                        {done ? "✓" : future ? "" : "○"}
                      </div>
                    );
                  })}
                </div>
              </div>
            );
          })}
        </>
      )}

      {habits.length > 0 && viewMode==="month" && (
        <>
          {habits.map(h => {
            const monthDone = monthDays.filter(d=>isCompleted(h,d.iso)&&d.iso<=today).length;
            return (
              <div key={h.id} style={{background:"var(--col-bg)",border:"1px solid var(--col-border-soft)",borderRadius:10,padding:"12px 14px",marginBottom:8}}>
                <div style={{display:"flex",alignItems:"center",gap:8,marginBottom:10}}>
                  <span style={{flexShrink:0,display:"flex",alignItems:"center"}}>
                    <SportIcon iconKey={h.icon || h.emoji} size={22} color="var(--col-accent)"/>
                  </span>
                  <div style={{flex:1,minWidth:0}}>
                    <div style={{fontSize:13,fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}}>{h.name}</div>
                  </div>
                  <span className="mono" style={{fontSize:11,color:"var(--col-text-3)",flexShrink:0}}>{monthDone}/{monthDays.filter(d=>d.iso<=today).length}</span>
                  <button type="button" onClick={() => onDelete(h.id)}
                    style={{background:"none",border:"none",color:"var(--col-text-3)",fontSize:16,cursor:"pointer",padding:0,flexShrink:0,opacity:0.4}}
                    title="Löschen">×</button>
                </div>
                <div style={{display:"flex",flexWrap:"wrap",gap:5}}>
                  {monthDays.map(d => {
                    const done = isCompleted(h, d.iso);
                    const future = d.iso > today;
                    return (
                      <div key={d.iso}
                        onClick={() => !future && toggleCompletion(h, d.iso)}
                        title={d.iso}
                        style={{
                          width:24,height:24,borderRadius:6,
                          display:"flex",alignItems:"center",justifyContent:"center",
                          cursor:future?"default":"pointer",
                          fontSize:10,
                          background: done ? (d.isToday?"var(--col-accent)":"#166534") : "transparent",
                          border: done ? "none" : d.isToday ? "2px solid var(--col-accent)" : future ? "1px dashed var(--col-border)" : "1px solid var(--col-border)",
                          color: done ? "white" : d.isToday ? "var(--col-accent)" : "var(--col-text-3)",
                          transition:"all .12s"
                        }}>
                        {d.date}
                      </div>
                    );
                  })}
                </div>
              </div>
            );
          })}
        </>
      )}

      {/* Statistiken */}
      {habits.length > 0 && (
        <div style={{display:"grid",gridTemplateColumns:"repeat(3,1fr)",gap:10,marginTop:20}}>
          {[
            {n: maxStreak + (window.currentLang==="en"?"d":"T"),  l: t("habit.streakCurrent"),     col: maxStreak > 0 ? "var(--col-accent)" : "var(--col-text)"},
            {n: maxLongest + (window.currentLang==="en"?"d":"T"), l: t("habit.streakLongest"),  col: "var(--col-text)"},
            {n: totalDays30 + (window.currentLang==="en"?"d":"T"),l: t("habit.avgDays30"),     col: "var(--col-text)"}
          ].map((s, i) => (
            <div key={i} style={{background:"var(--col-bg)",border:"1px solid var(--col-border-soft)",borderRadius:10,padding:"14px",textAlign:"center"}}>
              <div className="serif" style={{fontSize:32,fontStyle:"italic",fontWeight:400,color:s.col,lineHeight:1}}>{s.n}</div>
              <div className="mono" style={{fontSize:9,color:"var(--col-text-3)",letterSpacing:".06em",textTransform:"uppercase",marginTop:5}}>{s.l}</div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

function HabitForm({ onSave, onCancel, habit }) {
  const [name, setName] = useState("");
  const [selectedIcon, setSelectedIcon] = useState("runner");
  const [graceDay, setGraceDay] = useState(habit?.graceDay||false); // FIXED C3: grace day option added

  function save() {
    if (!name.trim()) return;
    onSave({
      id: Date.now() + Math.random(),
      name: name.trim(),
      icon: selectedIcon,
      emoji: null,
      freq: "simple",
      days: [],
      timesPerWeek: null,
      completions: [],
      graceDay,
      createdAt: Date.now(),
      updatedAt: Date.now()
    });
  }

  return (
    <div style={{background:"var(--col-bg-sec)",border:"1px solid var(--col-border)",borderRadius:10,padding:"14px 16px",marginBottom:14}}>
      {/* Icon-Auswahl */}
      <div style={{display:"flex",gap:8,marginBottom:12,flexWrap:"wrap"}}>
        {HABIT_ICONS.map(ic => (
          <button type="button" key={ic.key}
            onClick={() => setSelectedIcon(ic.key)}
            title={ic.label}
            style={{
              width:40,height:40,borderRadius:8,display:"flex",alignItems:"center",justifyContent:"center",
              border: selectedIcon === ic.key ? "2px solid var(--col-accent)" : "1px solid var(--col-border)",
              background: selectedIcon === ic.key ? "var(--col-accent-wash)" : "var(--col-bg)",
              cursor:"pointer",transition:"all .12s",flexShrink:0,padding:0
            }}>
            <img
              src={"./habit-icons/" + ic.key + ".svg"}
              width={22} height={22}
              alt={ic.label}
              style={{opacity: selectedIcon === ic.key ? 1 : 0.4, display:"block"}}
              draggable={false}
            />
          </button>
        ))}
      </div>
      {/* Name */}
      <div style={{marginBottom:12}}>
        <input value={name} onChange={e=>setName(e.target.value)} placeholder={t("habit.namePlaceholder")}
          onKeyDown={e=>e.key==="Enter"&&save()} autoFocus
          style={{width:"100%",boxSizing:"border-box",fontSize:13,borderRadius:8,border:"1px solid var(--col-border)",padding:"7px 10px",background:"var(--col-bg)",color:"var(--col-text)"}}/>
        <div style={{fontSize:11,color:"var(--col-text-3)",marginTop:5}}>{t("habit.tip")}</div>
        <label style={{display:"flex",alignItems:"center",gap:8,fontSize:13,marginTop:8,cursor:"pointer"}}>
          <input type="checkbox" checked={graceDay} onChange={e=>setGraceDay(e.target.checked)}/>
          {t("habit.graceDay")}
        </label>
      </div>
      <div style={{display:"flex",gap:6}}>
        <button type="button" onClick={save}
          disabled={!name.trim()}
          style={{padding:"5px 14px",borderRadius:20,background:"var(--col-accent)",color:"var(--col-bg)",fontSize:12,border:"none",cursor:"pointer",fontWeight:500,fontFamily:"var(--sans)"}}>
          {t("habit.save")}
        </button>
        <button type="button" onClick={onCancel}
          style={{padding:"5px 12px",borderRadius:20,border:"1px solid var(--col-border)",color:"var(--col-text-sec)",fontSize:12,background:"transparent",cursor:"pointer",fontFamily:"var(--sans)"}}>
          {t("habit.cancel")}
        </button>
      </div>
    </div>
  );
}

function HabitEveningPopup({ habits, onUpdate, onClose }) {
  const today = todayISO();
  habits = (habits || []).filter(h => !h.deletedAt);

  function toggle(habit) {
    const c = habit.completions || [];
    onUpdate({...habit,
      completions: c.includes(today) ? c.filter(d => d !== today) : [...c, today],
      updatedAt: Date.now()
    });
  }

  return (
    <div style={{position:"fixed",inset:0,background:"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:2500,padding:16}} onClick={onClose}>
      <div style={{background:"var(--col-bg)",borderRadius:16,padding:"1.5rem",width:340,maxWidth:"100%",boxShadow:"0 20px 60px rgba(0,0,0,0.3)",animation:"fadeSlideIn 0.3s ease"}} onClick={e=>e.stopPropagation()}>
        <div style={{fontSize:15,fontWeight:700,color:"var(--col-text)",marginBottom:4}}>{t("habit.eveningTitle")}</div>
        <div style={{fontSize:12,color:"var(--col-text-sec)",marginBottom:16}}>{t("habit.eveningSubtitle")}</div>
        {habits.length===0&&(
          <p className="serif" style={{fontSize:13,color:"var(--col-text-sec)",fontStyle:"italic"}}>{t("habit.none")}</p>
        )}
        {habits.map(h=>{
          const done=(h.completions||[]).includes(today);
          return (
            <label key={h.id} style={{display:"flex",alignItems:"center",gap:10,padding:"8px 0",fontSize:13,color:"var(--col-text)",cursor:"pointer"}}>
              <input type="checkbox" checked={done} onChange={()=>toggle(h)}/>
              <SportIcon iconKey={h.icon||h.emoji} size={20} color="var(--col-accent)"/>
              <span>{h.name}</span>
            </label>
          );
        })}
        <button type="button" onClick={onClose}
          style={{marginTop:16,width:"100%",padding:"9px 0",borderRadius:20,background:"var(--col-accent)",color:"var(--col-bg)",fontSize:13,border:"none",cursor:"pointer",fontFamily:"var(--sans)",fontWeight:500}}>
          {t("habit.done")}
        </button>
      </div>
    </div>
  );
}

Object.assign(window, { HabitView, SportIcon, HabitEveningPopup });

})();
