(function(){
// ============================================================
// stats.jsx — StatsView ("Reflektieren"-Tab)
// Depends on window: localISO, todayISO, getCatColor, prioCol
// ============================================================

function StatsView({
  nonDeletedTodos, isMobile, data, settings,
  streakDays, longestStreak, avgCycle, moved, weekDone, weekCreated, weekStart,
  dayPlanArchive, last7Stats, maxStat, next7,
  setShowReview
}){
  const {localISO, todayISO, getCatColor, prioCol} = window;
  const t = window.t;
  const [statsSendSt, setStatsSendSt] = React.useState("");
  const modules = settings.statsModules || {};
  const show = (key) => modules[key] !== false;
  const WD = window.currentLang==="en" ? ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"] : ["So","Mo","Di","Mi","Do","Fr","Sa"];
  const WD_MON = window.currentLang==="en" ? ["Mon","Tue","Wed","Thu","Fri","Sat","Sun"] : ["Mo","Di","Mi","Do","Fr","Sa","So"];
  const locale = window.currentLang==="en" ? "en-GB" : "de-CH";

  return(
    <div>
      {React.createElement(window.__SH,{kicker:t("stats.kicker"), title:t("stats.title"), subtitle:t("stats.subtitle")})}

      {/* Eigene Wochennotiz */}
      {show("notiz")&&(
      <div style={{marginBottom:28}}>
        <div className="cap" style={{color:"var(--col-text-3)",marginBottom:10}}>{t("stats.ownNote")}</div>
        <textarea
          key={"wnote-"+weekStart}
          defaultValue={localStorage.getItem("planer_wnote_"+(settings.profile||'')+weekStart)||""}
          onBlur={e=>localStorage.setItem("planer_wnote_"+(settings.profile||'')+weekStart,e.target.value)}
          placeholder={t("stats.ownNotePlaceholder")}
          rows={4}
          style={{width:"100%",boxSizing:"border-box",fontSize:isMobile?14:15,fontFamily:"var(--serif)",fontStyle:"italic",lineHeight:1.65,
            border:"1px solid var(--col-border-soft)",borderRadius:8,padding:"12px 16px",
            background:"var(--col-bg-sec)",color:"var(--col-text)",resize:"vertical"}}
        />
      </div>
      )}

      {/* Aktivitäts-Heatmap */}
      {show("heatmap")&&(()=>{
        const WEEKS=16;
        const byDay={};
        nonDeletedTodos.forEach(t=>{if(t.done&&t.doneAt){const iso=localISO(new Date(t.doneAt));byDay[iso]=(byDay[iso]||0)+1;}});
        const maxCount=Math.max(1,...Object.values(byDay));
        const t0=new Date(todayISO()+"T12:00:00");
        const dow0=(t0.getDay()+6)%7;
        const start=new Date(t0);start.setDate(start.getDate()-dow0-(WEEKS-1)*7);
        const weeks=Array.from({length:WEEKS},(_,w)=>Array.from({length:7},(_,d)=>{
          const day=new Date(start);day.setDate(day.getDate()+w*7+d);
          const iso=localISO(day);
          return{iso,count:byDay[iso]||0,future:iso>todayISO(),monthFirst:day.getDate()<=7};
        }));
        const getAlpha=n=>n===0?null:Math.max(0.18,Math.min(1,n/Math.max(4,maxCount)));
        const monthName=iso=>new Date(iso+"T12:00:00").toLocaleDateString(locale,{month:"short"});
        const totalTracked=Object.values(byDay).reduce((a,b)=>a+b,0);
        const activeDays=Object.keys(byDay).length;
        return(
          <div style={{marginBottom:28}}>
            <div style={{display:"flex",justifyContent:"space-between",alignItems:"baseline",marginBottom:14}}>
              <div className="cap" style={{color:"var(--col-text-3)"}}>{t("stats.activityHeatmap",{n:WEEKS})}</div>
              <div className="mono" style={{fontSize:9,color:"var(--col-text-3)",letterSpacing:"0.04em"}}>{t("stats.activeDays",{active:activeDays,total:totalTracked})}</div>
            </div>
            <div style={{display:"flex",gap:4}}>
              <div style={{display:"flex",flexDirection:"column",gap:2,paddingTop:18,width:18}}>
                {[WD_MON[0],"",WD_MON[2],"",WD_MON[4],"",WD_MON[6]].map((l,i)=>(
                  <div key={i} style={{height:12,lineHeight:"12px",fontSize:8,color:"var(--col-text-3)",fontFamily:"var(--mono)",textAlign:"right"}}>{l}</div>
                ))}
              </div>
              <div style={{flex:1,overflowX:"auto"}}>
                <div style={{display:"flex",gap:2,marginBottom:3,minWidth:weeks.length*14}}>
                  {weeks.map((week,wi)=>{
                    const d=new Date(week[0].iso+"T12:00:00");
                    const show=wi===0||(d.getDate()<=7);
                    return <div key={wi} style={{width:12,fontSize:8,color:"var(--col-text-3)",fontFamily:"var(--mono)",letterSpacing:"0.02em",overflow:"visible",whiteSpace:"nowrap"}}>{show?monthName(week[0].iso):""}</div>;
                  })}
                </div>
                <div style={{display:"flex",gap:2,minWidth:weeks.length*14}}>
                  {weeks.map((week,wi)=>(
                    <div key={wi} style={{display:"flex",flexDirection:"column",gap:2}}>
                      {week.map((day,di)=>{
                        const alpha=getAlpha(day.count);
                        const isToday=day.iso===todayISO();
                        return(
                          <div key={di} title={`${day.iso}: ${day.count} erledigt`}
                            style={{width:12,height:12,borderRadius:2,cursor:"default",
                              background:alpha!==null?"var(--col-accent)":"var(--col-border-soft)",
                              opacity:day.future?0.12:alpha!==null?alpha:1,
                              outline:isToday?"1.5px solid var(--col-accent)":"none",outlineOffset:"1px"}}/>
                        );
                      })}
                    </div>
                  ))}
                </div>
              </div>
            </div>
            <div style={{display:"flex",alignItems:"center",gap:5,marginTop:8,justifyContent:"flex-end"}}>
              <span style={{fontSize:9,color:"var(--col-text-3)",fontFamily:"var(--mono)"}}>{t("stats.less")}</span>
              {[null,0.18,0.4,0.65,1].map((o,i)=>(
                <div key={i} style={{width:10,height:10,borderRadius:2,background:o===null?"var(--col-border-soft)":"var(--col-accent)",opacity:o===null?1:o}}/>
              ))}
              <span style={{fontSize:9,color:"var(--col-text-3)",fontFamily:"var(--mono)"}}>{t("stats.more")}</span>
            </div>
          </div>
        );
      })()}

      {/* Verhaltensmuster */}
      {show("muster")&&(()=>{
        const done30=nonDeletedTodos.filter(t=>t.done&&t.doneAt&&Date.now()-new Date(t.doneAt).getTime()<30*86400000);
        if(done30.length<5)return null;
        const byHour=[0,0,0,0];
        done30.forEach(t=>{const h=new Date(t.doneAt).getHours();if(h<6)byHour[0]++;else if(h<12)byHour[1]++;else if(h<17)byHour[2]++;else byHour[3]++;});
        const timeKeys=["Nacht","Morgen","Nachm","Abend"];
        const timeLabels=timeKeys.map(k=>t("stats.timeLabel."+k));
        const maxH=Math.max(1,...byHour);
        const bestT=byHour.indexOf(Math.max(...byHour));
        const byDow=[0,0,0,0,0,0,0];
        done30.forEach(t=>{byDow[(new Date(t.doneAt).getDay()+6)%7]++;});
        const dowLabels=WD_MON;
        const maxD=Math.max(1,...byDow);
        const bestD=byDow.indexOf(Math.max(...byDow));
        return(
          <div style={{display:"grid",gridTemplateColumns:isMobile?"1fr":"1fr 1fr",gap:isMobile?24:32,marginBottom:28}}>
            <div>
              <div className="cap" style={{color:"var(--col-text-3)",marginBottom:12}}>{t("stats.timeOfDayTitle")}</div>
              <div style={{display:"flex",gap:4,alignItems:"flex-end",height:56}}>
                {byHour.map((v,i)=>{
                  const pct=Math.max(8,Math.round(v/maxH*100));
                  const best=i===bestT;
                  return(
                    <div key={i} style={{flex:1,display:"flex",flexDirection:"column",alignItems:"center",gap:4}}>
                      <div style={{width:"100%",flex:1,display:"flex",alignItems:"flex-end"}}>
                        <div style={{width:"100%",height:`${pct}%`,background:best?"var(--col-accent)":"var(--col-border)",borderRadius:"2px 2px 0 0",opacity:best?1:0.45,transition:"height .3s"}}/>
                      </div>
                      <div className="mono" style={{fontSize:8,color:best?"var(--col-accent)":"var(--col-text-3)"}}>{timeLabels[i]}</div>
                    </div>
                  );
                })}
              </div>
              <div className="serif" style={{fontSize:12,fontStyle:"italic",color:"var(--col-text-sec)",marginTop:8}}>
                {t("stats.mostProductiveTime",{time:bestT===2?t("stats.inAfternoon"):t("stats.inTime",{time:timeLabels[bestT]})})}
              </div>
            </div>
            <div>
              <div className="cap" style={{color:"var(--col-text-3)",marginBottom:12}}>{t("stats.weekdayTitle")}</div>
              <div style={{display:"flex",gap:4,alignItems:"flex-end",height:56}}>
                {byDow.map((v,i)=>{
                  const pct=Math.max(8,Math.round(v/maxD*100));
                  const best=i===bestD;
                  return(
                    <div key={i} style={{flex:1,display:"flex",flexDirection:"column",alignItems:"center",gap:4}}>
                      <div style={{width:"100%",flex:1,display:"flex",alignItems:"flex-end"}}>
                        <div style={{width:"100%",height:`${pct}%`,background:best?"var(--col-accent)":"var(--col-border)",borderRadius:"2px 2px 0 0",opacity:best?1:0.45,transition:"height .3s"}}/>
                      </div>
                      <div className="mono" style={{fontSize:8,color:best?"var(--col-accent)":"var(--col-text-3)"}}>{dowLabels[i]}</div>
                    </div>
                  );
                })}
              </div>
              <div className="serif" style={{fontSize:12,fontStyle:"italic",color:"var(--col-text-sec)",marginTop:8}}>
                {t("stats.mostProductiveDay",{day:dowLabels[bestD]})}
              </div>
            </div>
          </div>
        );
      })()}

      {/* Streak + KPI-Trio */}
      {show("kpi")&&<>
      <div style={{display:"grid",gridTemplateColumns:isMobile?"1fr 1fr":"repeat(4,1fr)",gap:isMobile?14:18,marginBottom:show("emailReport")?14:28,padding:"18px 0",borderTop:"1px solid var(--col-border-soft)",borderBottom:"1px solid var(--col-border-soft)"}}>
        <div>
          <div className="cap" style={{color:"var(--col-text-3)",marginBottom:6}}>{t("stats.streak")}</div>
          <div style={{display:"flex",alignItems:"baseline",gap:4}}>
            <span className="serif" style={{fontSize:isMobile?32:38,fontStyle:"italic",fontWeight:400,color:streakDays>0?"var(--col-accent)":"var(--col-text-3)",letterSpacing:"-0.03em",lineHeight:1}}>{streakDays}</span>
            <span className="serif" style={{fontSize:13,color:"var(--col-text-sec)",fontStyle:"italic"}}>{streakDays===1?t("stats.day"):t("stats.days")}</span>
          </div>
          <div className="mono" style={{fontSize:9.5,color:"var(--col-text-3)",letterSpacing:"0.05em",marginTop:5}}>{t("stats.best",{n:longestStreak})}</div>
        </div>
        <div>
          <div className="cap" style={{color:"var(--col-text-3)",marginBottom:6}}>{t("stats.thisWeek")}</div>
          <div style={{display:"flex",alignItems:"baseline",gap:4}}>
            <span className="serif" style={{fontSize:isMobile?32:38,fontStyle:"italic",fontWeight:400,color:"var(--col-text)",letterSpacing:"-0.03em",lineHeight:1}}>{weekDone}</span>
            <span className="serif" style={{fontSize:13,color:"var(--col-text-sec)",fontStyle:"italic"}}>{t("stats.completed")}</span>
          </div>
          <div className="mono" style={{fontSize:9.5,color:"var(--col-text-3)",letterSpacing:"0.05em",marginTop:5}}>{t("stats.newCreated",{n:weekCreated})}</div>
        </div>
        <div>
          <div className="cap" style={{color:"var(--col-text-3)",marginBottom:6}}>{t("stats.avgCycle")}</div>
          {avgCycle===null?(
            <div className="serif" style={{fontSize:isMobile?22:26,fontStyle:"italic",color:"var(--col-text-3)",letterSpacing:"-0.02em",lineHeight:1.1}}>—</div>
          ):(
            <div style={{display:"flex",alignItems:"baseline",gap:4}}>
              <span className="serif" style={{fontSize:isMobile?32:38,fontStyle:"italic",fontWeight:400,color:"var(--col-text)",letterSpacing:"-0.03em",lineHeight:1}}>{avgCycle<1?"<1":Math.round(avgCycle)}</span>
              <span className="serif" style={{fontSize:13,color:"var(--col-text-sec)",fontStyle:"italic"}}>{avgCycle<1?t("stats.day"):(Math.round(avgCycle)===1?t("stats.day"):t("stats.days"))}</span>
            </div>
          )}
          <div className="mono" style={{fontSize:9.5,color:"var(--col-text-3)",letterSpacing:"0.05em",marginTop:5}}>{t("stats.cycleDesc")}</div>
        </div>
        <div>
          <div className="cap" style={{color:"var(--col-text-3)",marginBottom:6}}>{t("stats.moved")}</div>
          <div style={{display:"flex",alignItems:"baseline",gap:4}}>
            <span className="serif" style={{fontSize:isMobile?32:38,fontStyle:"italic",fontWeight:400,color:moved.length>0?"var(--col-text)":"var(--col-text-3)",letterSpacing:"-0.03em",lineHeight:1}}>{moved.length}</span>
            <span className="serif" style={{fontSize:13,color:"var(--col-text-sec)",fontStyle:"italic"}}>{moved.length===1?t("stats.task"):t("stats.tasks")}</span>
          </div>
          <div className="mono" style={{fontSize:9.5,color:"var(--col-text-3)",letterSpacing:"0.05em",marginTop:5}}>{t("stats.movedLong")}</div>
        </div>
      </div>
      {show("emailReport")&&(()=>{
        const habitsThisWeek=(data.habits||[]).filter(h=>(h.completions||[]).some(c=>c>=weekStart)).length;
        const byDay={};
        nonDeletedTodos.filter(t=>t.done&&t.doneAt&&localISO(new Date(t.doneAt))>=weekStart).forEach(t=>{
          const d=WD[new Date(t.doneAt).getDay()];
          byDay[d]=(byDay[d]||0)+1;
        });
        const mostActiveDay=Object.keys(byDay).sort((a,b)=>byDay[b]-byDay[a])[0]||"—";
        const _subj="Planer Wochenbericht "+new Date().toLocaleDateString(locale);
        const _body="Wochenbericht Planer\n====================\nErledigte Aufgaben: "+weekDone+"\nGewohnheiten eingehalten: "+habitsThisWeek+"\nLängster Streak: "+longestStreak+" Tage\nAktivster Tag: "+mostActiveDay+"\n\nErstellt: "+new Date().toLocaleString(locale);
        async function _send(){
          setStatsSendSt("sending");
          try{
            const r=await fetch('/api/send-stats-email',{method:'POST',headers:{'Content-Type':'application/json',...window.authHeaders()},body:JSON.stringify({subject:_subj,text:_body})});
            const d=await r.json();
            setStatsSendSt(r.ok?"ok":"err:"+(d.error||"Fehler"));
          }catch{setStatsSendSt("err:"+t("stats.networkError"));}
        }
        return(
          <div style={{marginBottom:28,display:"flex",alignItems:"center",gap:10}}>
            <button type="button" onClick={_send} disabled={statsSendSt==="sending"} style={{fontSize:12,padding:"5px 12px",border:"1px solid var(--col-border)",borderRadius:6,background:"transparent",cursor:"pointer",color:"var(--col-text-2)"}}>{statsSendSt==="sending"?"…":t("stats.sendWeeklyReport")}</button>
            {statsSendSt.startsWith("err:")&&<span style={{fontSize:11,color:"#b91c1c"}}>{statsSendSt.slice(4)}</span>}
            {statsSendSt==="ok"&&<span style={{fontSize:11,color:"#166534"}}>{t("stats.emailSent")}</span>}
          </div>
        );
      })()}
      </>}

      {/* Highlights dieser Woche */}
      {show("highlights")&&weekDone>0&&(
        <div style={{marginBottom:28}}>
          <div className="cap" style={{color:"var(--col-text-3)",marginBottom:14}}>{t("stats.highlightsThisWeek")}</div>
          <div style={{display:"flex",flexDirection:"column",gap:0}}>
            {nonDeletedTodos
              .filter(t=>t.done&&t.doneAt&&localISO(new Date(t.doneAt))>=weekStart)
              .sort((a,b)=>new Date(b.doneAt)-new Date(a.doneAt))
              .slice(0,8)
              .map((t,i)=>{
                const cc=t.category?getCatColor(data.categories,t.category):null;
                const d=new Date(t.doneAt);
                const wd=WD[d.getDay()];
                const hm=`${String(d.getHours()).padStart(2,"0")}:${String(d.getMinutes()).padStart(2,"0")}`;
                return(
                  <div key={t.id} style={{display:"grid",gridTemplateColumns:"auto 1fr auto",gap:10,padding:"10px 0",borderBottom:"1px solid var(--col-border-soft)",alignItems:"center"}}>
                    <span style={{fontSize:11,color:"#166534",fontWeight:600}}>✓</span>
                    <div style={{minWidth:0}}>
                      <span className="serif" style={{fontSize:14,fontWeight:400,color:"var(--col-text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",display:"block",letterSpacing:"-0.005em"}}>{t.text}</span>
                      {cc&&<span style={{fontSize:10,color:cc.col,fontFamily:"var(--mono)",letterSpacing:"0.04em"}}>{t.category}{t.subcategory?` › ${t.subcategory}`:""}</span>}
                    </div>
                    <span className="mono" style={{fontSize:10,color:"var(--col-text-3)",flexShrink:0,textAlign:"right"}}>{wd} {hm}</span>
                  </div>
                );
              })}
          </div>
        </div>
      )}

      {/* Verschoben-Liste */}
      {show("verschoben")&&moved.length>0&&(
        <div style={{marginBottom:28}}>
          <div className="cap" style={{color:"var(--col-text-3)",marginBottom:14}}>{t("stats.whatLiesLong")}</div>
          <div style={{display:"flex",flexDirection:"column",gap:0}}>
            {moved.map((t,i)=>{
              const cc=t.category?getCatColor(data.categories,t.category):null;
              return(
                <div key={t.id} style={{display:"grid",gridTemplateColumns:"auto 1fr auto",gap:12,padding:"11px 0",borderTop:i===0?"1px solid var(--col-border-soft)":"none",borderBottom:"1px solid var(--col-border-soft)",alignItems:"baseline"}}>
                  {cc?<span style={{width:7,height:7,borderRadius:"50%",background:cc.col,display:"inline-block",transform:"translateY(2px)"}}/>:<span style={{width:7,height:7,borderRadius:"50%",background:"var(--col-text-3)",display:"inline-block",transform:"translateY(2px)"}}/>}
                  <span className="serif" style={{fontSize:14.5,fontWeight:400,color:"var(--col-text)",letterSpacing:"-0.005em",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}}>{t.text}</span>
                  <span className="mono" style={{fontSize:10.5,color:"var(--col-text-3)",letterSpacing:"0.04em"}}>{t._ageDays} {t._ageDays===1?window.t("stats.day"):window.t("stats.days")}</span>
                </div>
              );
            })}
          </div>
          <p className="serif" style={{fontSize:12,color:"var(--col-text-3)",fontStyle:"italic",marginTop:10}}>{window.t("stats.letGoNote")}</p>
        </div>
      )}

      {/* Nach Kategorie */}
      {show("kategorien")&&<div style={{marginBottom:28}}>
        <div className="cap" style={{color:"var(--col-text-3)",marginBottom:14}}>{t("stats.byCategory")}</div>
        {(()=>{
          const cats=[...data.categories];
          const rows=cats.map(cat=>{
            const all=nonDeletedTodos.filter(t=>t.category===cat&&!t.recurring);
            const done=all.filter(t=>t.done).length;
            const total=all.length;
            return{cat,total,done,open:total-done};
          }).filter(r=>r.total>0);
          const noCat=nonDeletedTodos.filter(t=>!t.category&&!t.recurring);
          if(noCat.length>0)rows.push({cat:null,total:noCat.length,done:noCat.filter(t=>t.done).length,open:noCat.filter(t=>!t.done).length});
          if(!rows.length)return <p className="serif" style={{fontSize:14,color:"var(--col-text-sec)",fontStyle:"italic"}}>{t("stats.noTodosWithCategory")}</p>;
          const maxTotal=Math.max(...rows.map(r=>r.total),1);
          return rows.sort((a,b)=>b.total-a.total).map((r,i)=>{
            const cc=r.cat?getCatColor(data.categories,r.cat):null;
            const pct=r.total?Math.round(r.done/r.total*100):0;
            const widthPct=Math.round(r.total/maxTotal*100);
            return(
              <div key={i} style={{padding:"14px 0",borderBottom:"1px solid var(--col-border-soft)"}}>
                <div style={{display:"grid",gridTemplateColumns:isMobile?"1fr auto":"minmax(0,2.2fr) minmax(0,3fr) auto",gap:isMobile?8:18,alignItems:"baseline",marginBottom:8}}>
                  <div style={{display:"flex",alignItems:"baseline",gap:8,minWidth:0}}>
                    {cc?<span style={{width:7,height:7,borderRadius:"50%",background:cc.col,flexShrink:0,display:"inline-block",transform:"translateY(-1px)"}}/>:<span style={{width:7,height:7,borderRadius:"50%",background:"var(--col-text-3)",flexShrink:0,display:"inline-block",transform:"translateY(-1px)"}}/>}
                    <span className="serif" style={{fontSize:16,fontWeight:500,color:"var(--col-text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",letterSpacing:"-0.01em"}}>{r.cat||t("stats.noCategory")}</span>
                  </div>
                  {!isMobile&&(
                    <div style={{display:"flex",alignItems:"baseline",gap:14}}>
                      <span className="mono" style={{fontSize:11,color:"var(--col-text-3)",letterSpacing:"0.04em"}}>{r.total} {r.total===1?t("stats.todo"):t("stats.todos")}</span>
                      <span className="mono" style={{fontSize:11,color:"var(--col-text-sec)",letterSpacing:"0.04em"}}>{t("stats.doneOpen",{done:r.done,open:r.open})}</span>
                    </div>
                  )}
                  <span className="serif" style={{fontSize:18,fontStyle:"italic",fontWeight:400,color:pct===100?"#166534":"var(--col-text)",letterSpacing:"-0.02em",lineHeight:1}}>{pct}%</span>
                </div>
                {isMobile&&<div className="mono" style={{fontSize:10.5,color:"var(--col-text-3)",letterSpacing:"0.04em",marginBottom:8}}>{r.total} {t("stats.todos")} · {t("stats.doneOpen",{done:r.done,open:r.open})}</div>}
                <div style={{position:"relative",height:3,background:"var(--col-border-soft)",borderRadius:0,overflow:"hidden"}}>
                  <div style={{position:"absolute",left:0,top:0,height:"100%",width:`${widthPct}%`,background:"var(--col-border)"}}/>
                  <div style={{position:"absolute",left:0,top:0,height:"100%",width:`${Math.round(widthPct*pct/100)}%`,background:cc?cc.col:"var(--col-accent)",transition:"width 0.4s"}}/>
                </div>
              </div>
            );
          });
        })()}
      </div>}

      {/* Tagesplan-Archiv */}
      {show("tagesplan")&&dayPlanArchive.length>0&&(
        <div style={{marginBottom:28}}>
          <div className="cap" style={{color:"var(--col-text-3)",marginBottom:14}}>{t("stats.pastDays")}</div>
          <div style={{display:"flex",flexDirection:"column",gap:0}}>
            {dayPlanArchive.slice(0,7).map((entry,ei)=>{
              const d=new Date(entry.date+"T12:00:00");
              const wd=WD[d.getDay()];
              const dateLabel=d.toLocaleDateString(locale,{day:"numeric",month:"short"});
              const doneCount=entry.slots.filter(s=>s.done).length;
              const totalCount=entry.slots.length;
              return(
                <div key={entry.date} style={{display:"grid",gridTemplateColumns:isMobile?"80px 1fr":"110px 1fr",gap:14,padding:"14px 0",borderTop:ei===0?"1px solid var(--col-border-soft)":"none",borderBottom:"1px solid var(--col-border-soft)"}}>
                  <div>
                    <div className="cap" style={{color:"var(--col-text-3)",marginBottom:2}}>{wd}</div>
                    <div className="serif" style={{fontSize:22,fontStyle:"italic",lineHeight:1,color:"var(--col-text)",letterSpacing:"-0.02em"}}>{dateLabel}</div>
                    <div className="mono" style={{fontSize:10,color:doneCount===totalCount&&totalCount>0?"#166534":"var(--col-text-3)",marginTop:5,letterSpacing:"0.04em"}}>{t("stats.doneCount",{done:doneCount,total:totalCount})}</div>
                  </div>
                  <div style={{display:"flex",flexDirection:"column",gap:3}}>
                    {entry.slots.length===0&&<span className="serif" style={{fontSize:13,fontStyle:"italic",color:"var(--col-text-3)"}}>{t("stats.noPlanDocumented")}</span>}
                    {entry.slots.map((s,i)=>(
                      <div key={i} style={{display:"flex",gap:10,alignItems:"baseline",minWidth:0,opacity:s.done?1:0.55}}>
                        <span className="mono" style={{fontSize:10.5,color:s.done?"var(--col-accent)":"var(--col-text-3)",letterSpacing:"0.02em",flexShrink:0,minWidth:50}}>{s.time||"—"}</span>
                        <span className="serif" style={{fontSize:13,fontStyle:s.done?"normal":"italic",color:s.done?"var(--col-text)":"var(--col-text-sec)",textDecoration:s.done?"none":"line-through",textDecorationColor:"var(--col-text-3)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0}}>
                          {s.done?"✓ ":""}{s.task}
                        </span>
                      </div>
                    ))}
                  </div>
                </div>
              );
            })}
            {dayPlanArchive.length>7&&(
              <div className="mono" style={{fontSize:10,color:"var(--col-text-3)",letterSpacing:"0.04em",padding:"10px 0",textAlign:"center"}}>{t("stats.moreDaysInArchive",{n:dayPlanArchive.length-7})}</div>
            )}
          </div>
        </div>
      )}

      {/* Zeiterfassung */}
      {show("zeit")&&(()=>{
        const weekMs=nonDeletedTodos.reduce((sum,t)=>sum+(t.timeLog||[]).filter(e=>e.start>=new Date(weekStart+"T00:00:00").getTime()).reduce((s,e)=>s+((e.end||e.start)-e.start),0),0);
        const taskTimes=nonDeletedTodos.map(t=>({text:t.text,ms:(t.timeLog||[]).reduce((s,e)=>s+((e.end||e.start)-e.start),0)})).filter(t=>t.ms>0).sort((a,b)=>b.ms-a.ms).slice(0,5);
        if(taskTimes.length===0)return null;
        const fmtMs=ms=>{const h=Math.floor(ms/3600000),m=Math.floor((ms%3600000)/60000);return h>0?`${h}h${m>0?" "+m+"m":""}`:m+"m";};
        const maxMs=taskTimes[0]?.ms||1;
        return(
          <div style={{marginBottom:28}}>
            <div className="cap" style={{color:"var(--col-text-3)",marginBottom:14}}>{t("stats.timeTracking")}</div>
            <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10,marginBottom:16}}>
              {[{n:fmtMs(weekMs),l:t("stats.thisWeek")},{n:taskTimes.length,l:taskTimes.length===1?t("stats.taskTracked"):t("stats.tasksTracked")}].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:28,fontStyle:"italic",fontWeight:400,color:i===0?"var(--col-accent)":"var(--col-text)",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>
              {taskTimes.map((t,i)=>(
                <div key={i} style={{padding:"8px 0",borderBottom:"1px solid var(--col-border-soft)"}}>
                  <div style={{display:"flex",justifyContent:"space-between",alignItems:"baseline",marginBottom:4,gap:10}}>
                    <span className="serif" style={{fontSize:13,color:"var(--col-text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0}}>{t.text}</span>
                    <span className="mono" style={{fontSize:11,color:"var(--col-accent)",flexShrink:0}}>{fmtMs(t.ms)}</span>
                  </div>
                  <div style={{height:2,background:"var(--col-border-soft)",borderRadius:1}}>
                    <div style={{height:"100%",width:`${Math.round(t.ms/maxMs*100)}%`,background:"var(--col-accent)",borderRadius:1,transition:"width .4s"}}/>
                  </div>
                </div>
              ))}
            </div>
          </div>
        );
      })()}

      {/* Gewohnheiten-Übersicht */}
      {show("gewohnheiten")&&(data.habits||[]).length>0&&(()=>{
        function hStreak(h){
          if(h.freq==="xweekly"){const tgt=h.timesPerWeek||1;let n=0;const cur=new Date(todayISO()+"T12:00:00");for(let w=0;w<52;w++){const dow=(cur.getDay()+6)%7;const ws=localISO(new Date(+cur-dow*86400000));const we=localISO(new Date(+cur-dow*86400000+6*86400000));const cnt=(h.completions||[]).filter(iso=>iso>=ws&&iso<=we&&iso<=todayISO()).length;if(cnt>=tgt){n++;}else if(w>0)break;cur.setDate(cur.getDate()-7);}return n;}
          const set=new Set(h.completions||[]);let n=0;const d=new Date(todayISO()+"T12:00:00");for(let i=0;i<365;i++){const iso=localISO(d);if(h.freq==="weekly"&&Array.isArray(h.days)){const dow=d.getDay()||7;if(!h.days.includes(dow)){d.setDate(d.getDate()-1);continue;}}if(!set.has(iso))break;n++;d.setDate(d.getDate()-1);}return n;
        }
        function hRate(h){
          if(h.freq==="xweekly"){const tgt=h.timesPerWeek||1;let total=0,met=0;const cur=new Date(todayISO()+"T12:00:00");for(let w=0;w<5;w++){const dow=(cur.getDay()+6)%7;const ws=localISO(new Date(+cur-dow*86400000));const we=localISO(new Date(+cur-dow*86400000+6*86400000));const cutWe=we<todayISO()?we:todayISO();const cnt=(h.completions||[]).filter(iso=>iso>=ws&&iso<=cutWe).length;total++;if(cnt>=tgt)met++;cur.setDate(cur.getDate()-7);}return total>0?Math.round(met/total*100):0;}
          const base=new Date(todayISO()+"T12:00:00");base.setDate(base.getDate()-29);let sc=0,dn=0;for(let i=0;i<30;i++){const d=new Date(base);d.setDate(d.getDate()+i);const iso=localISO(d);if(iso>todayISO())break;if(h.freq==="daily")sc++;else if(h.freq==="weekly"&&(h.days||[]).includes(d.getDay()||7))sc++;else continue;if((h.completions||[]).includes(iso))dn++;}return sc>0?Math.round(dn/sc*100):0;
        }
        const habits=data.habits||[];
        const td=habits.filter(h=>(h.completions||[]).includes(todayISO())).length;
        const bestStreak=Math.max(0,...habits.map(hStreak));
        const avgR=habits.length?Math.round(habits.reduce((s,h)=>s+hRate(h),0)/habits.length):0;
        return(
          <div style={{marginBottom:28}}>
            <div className="cap" style={{color:"var(--col-text-3)",marginBottom:14}}>{t("stats.habits")}</div>
            <div style={{display:"grid",gridTemplateColumns:"repeat(3,1fr)",gap:isMobile?6:10,marginBottom:16}}>
              {[{n:`${td}/${habits.length}`,l:t("stats.today")},{n:`${bestStreak}${window.currentLang==="en"?"d":"T"}`,l:t("stats.bestStreak")},{n:`${avgR}%`,l:t("stats.successRate30d")}].map((s,i)=>(
                <div key={i} style={{background:"var(--col-bg)",border:"1px solid var(--col-border-soft)",borderRadius:10,padding:isMobile?"10px 6px":"14px",textAlign:"center",minWidth:0}}>
                  <div className="serif" style={{fontSize:isMobile?22:26,fontStyle:"italic",fontWeight:400,color:i===0&&td===habits.length&&habits.length>0?"#166534":"var(--col-text)",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 style={{display:"flex",flexDirection:"column",gap:4}}>
              {habits.map(h=>{
                const done=(h.completions||[]).includes(todayISO());
                const streak=hStreak(h);
                const rate=hRate(h);
                return(
                  <div key={h.id} style={{display:"flex",alignItems:"center",gap:10,padding:"8px 12px",background:"var(--col-bg)",border:"1px solid var(--col-border-soft)",borderRadius:8}}>
                    <span style={{color:"var(--col-accent)",flexShrink:0,display:"flex",alignItems:"center"}}>
                      {h.icon&&window.SportIcon?React.createElement(window.SportIcon,{iconKey:h.icon,size:16,color:"var(--col-accent)"}):
                        <span style={{fontSize:14}}>{h.emoji||"●"}</span>}
                    </span>
                    <span className="serif" style={{flex:1,fontSize:13,color:"var(--col-text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}}>{h.name}</span>
                    {streak>0&&<span className="mono" style={{fontSize:10,color:"#166534",flexShrink:0,letterSpacing:"0.04em",display:"inline-flex",alignItems:"center",gap:3}}>{/* FIXED: emoji replaced with SVG */}<svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10 10-4.5 10-10c0-2-1-5-3-7-1 2.5-2.5 3-2.5 3C16.5 6 15 3 12 2z"/></svg>{streak}{window.currentLang==="en"?"d":"T"}</span>}
                    {streak===0&&<span className="mono" style={{fontSize:10,color:"var(--col-text-3)",flexShrink:0,letterSpacing:"0.04em"}}>{rate}%</span>}
                    <span style={{width:20,height:20,borderRadius:"50%",flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",fontSize:11,
                      background:done?"var(--col-accent)":"transparent",
                      border:done?"none":"1.5px solid var(--col-border)",
                      color:done?"var(--col-bg)":"var(--col-text-3)"}}>
                      {done?"✓":""}
                    </span>
                  </div>
                );
              })}
            </div>
          </div>
        );
      })()}

      {/* Deadlines nächste 7 Tage */}
      {show("deadlines")&&<div>
        <div className="cap" style={{color:"var(--col-text-3)",marginBottom:14}}>{t("stats.deadlines7d")}</div>
        <div style={{display:"grid",gridTemplateColumns:isMobile?"repeat(4,1fr)":"repeat(7,1fr)",gap:0}}>
          {next7.map((d,i)=>{
            const dl=nonDeletedTodos.filter(t=>!t.done&&t.deadline===d.iso);
            const isToday=d.iso===todayISO();
            return(
              <div key={d.iso} style={{padding:"10px 10px 10px 12px",borderTop:isToday?"2px solid var(--col-accent)":"1px solid var(--col-border-soft)",borderRight:!isMobile&&i<6?"1px solid var(--col-border-soft)":"none",minHeight:dl.length>0?100:70}}>
                <div className="cap" style={{color:isToday?"var(--col-accent)":"var(--col-text-3)",marginBottom:4}}>{d.label}</div>
                <div className="serif" style={{fontSize:24,fontStyle:isToday?"italic":"normal",fontWeight:isToday?500:400,color:isToday?"var(--col-accent)":"var(--col-text)",lineHeight:1,marginBottom:dl.length>0?10:0,letterSpacing:"-0.02em"}}>{d.day}</div>
                {dl.map(t=>(
                  <div key={t.id} className="serif" style={{fontSize:11.5,color:"var(--col-text)",lineHeight:1.35,marginBottom:5,paddingLeft:7,borderLeft:`2px solid ${prioCol[t.priority||"mittel"]}`,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontStyle:"italic"}}>{t.text}</div>
                ))}
                {dl.length===0&&<div className="mono" style={{fontSize:9.5,color:"var(--col-text-3)",letterSpacing:"0.04em",opacity:0.5}}>—</div>}
              </div>
            );
          })}
        </div>
      </div>}
    </div>
  );
}

Object.assign(window, { StatsView });
})();
