﻿(function(){
// ============================================================
// start.jsx — StartTab (Heute / Dashboard)
// Depends on window: parseDuration, cleanTitle, localISO, todayISO,
//                    hexToRgba, prioCol, Spinner
// ============================================================
const {useState, useEffect} = React;

function StartTab({
  nonDeletedTodos, activeTodos, data, isMobile, today, clock, aiGreeting, settings,
  dashQuick, setDashQuick, setData, setTab,
  freeCalEvents, nonDeletedExams, upcomingExams, todayStudyBlocks,
  studyTimer, setStudyTimer, startStudyTimer, pauseStudyTimer, resumeStudyTimer, stopStudyTimer,
  examColor, fmtMs,
  toggleRefresh, activeTimerId, activeTimerElapsed, startTimer, stopTimer, studyBlockIds,
  updateHabit, setPlanMode, setPlanFocusDate,
  focusMode, setFocusMode, onOpenPip
}){
  const {parseDuration, cleanTitle, localISO, todayISO, hexToRgba, prioCol, t, tList, GREETINGS_TR} = window;
  const dateLocale = window.currentLang==="en" ? "en-GB" : "de-CH";
  const hour=new Date().getHours();
  const openCount=nonDeletedTodos.filter(t=>!t.done&&!t.recurring).length;
  const todayCount=activeTodos.length;
  const next7days=Array.from({length:7},(_,i)=>{const d=new Date();d.setDate(d.getDate()+i);return localISO(d);});
  const deadlineCount=nonDeletedTodos.filter(t=>!t.done&&!t.recurring&&t.deadline&&next7days.includes(t.deadline)).length;
  const upcomingDeadlines=nonDeletedTodos.filter(t=>!t.done&&t.deadline&&t.deadline>=todayISO()).sort((a,b)=>a.deadline>b.deadline?1:-1).slice(0,6);
  const weekDays=Array.from({length:7},(_,i)=>{
    const d=new Date();const dow=d.getDay()||7;d.setDate(d.getDate()-dow+1+i);const iso=localISO(d);
    const deadlines=nonDeletedTodos.filter(t=>!t.done&&t.deadline===iso).length;
    const tasks=nonDeletedTodos.filter(t=>!t.done&&!t.recurring&&t.plannedDay===iso&&t.deadline!==iso).length;
    const events=freeCalEvents.filter(e=>e.start?.dateTime?.slice(0,10)===iso).length;
    return{iso,label:[t("week.mon"),t("week.tue"),t("week.wed"),t("week.thu"),t("week.fri"),t("week.sat"),t("week.sun")][i],day:d.getDate(),isToday:iso===todayISO(),deadlines,tasks,events,count:deadlines+tasks+events};
  });

  const noteKey="planer_daynote_"+(getAuthUsername()||"")+"_"+todayISO(); // FIXED L2: daynote key user-scoped
  const[dayNote,setDayNote]=useState(()=>{try{return localStorage.getItem("planer_daynote_"+(getAuthUsername()||"")+"_"+todayISO())||"";}catch{return "";}});
  useEffect(()=>{try{setDayNote(localStorage.getItem(noteKey)||"");}catch{}},[noteKey]);

  function dashAddTodo(){
    if(!dashQuick.trim())return;
    const dur=parseDuration(dashQuick);
    const txt=dur?cleanTitle(dashQuick):dashQuick.trim();
    const todo={id:Date.now(),createdAt:Date.now(),updatedAt:Date.now(),text:txt,done:false,priority:"mittel",plannedDay:todayISO(),deadline:null,category:null,subcategory:null,subtasks:[],comments:[],duration:dur,recurring:null};
    setData(d=>({...d,todos:[...d.todos,todo]}));
    setDashQuick("");
  }
  return(
    <div>
      {/* Editorial hero */}
      <div style={{background:"var(--col-bg)",border:"1px solid var(--col-border-soft)",borderRadius:8,padding:isMobile?"22px 20px":"30px 34px",marginBottom:18}}>
        <div style={{display:"flex",justifyContent:"space-between",alignItems:"baseline",marginBottom:18,flexWrap:"wrap",gap:10,paddingBottom:14,borderBottom:"1px solid var(--col-border-soft)"}}>
          <div className="cap" style={{color:"var(--col-text-sec)"}}>{clock.toLocaleDateString(dateLocale,{weekday:"long",day:"numeric",month:"long",year:"numeric"})}</div>
          <div className="mono" style={{fontSize:13,color:"var(--col-text-sec)",letterSpacing:"0.06em"}}>{clock.toLocaleTimeString(dateLocale,{hour:"2-digit",minute:"2-digit"})}</div>
        </div>
        <div style={{marginBottom:24,maxWidth:680}}>
          <div className="cap" style={{color:"var(--col-text-3)",marginBottom:8}}>
            {hour<5?t("hero.night"):hour<12?t("hero.morning"):hour<13?t("hero.noon"):hour<17?t("hero.afternoon"):t("hero.evening")}{settings.name?` · ${settings.name}`:""}
          </div>
          <div className="serif" style={{fontSize:isMobile?26:34,fontWeight:400,lineHeight:1.18,letterSpacing:"-0.015em",color:"var(--col-text)",textWrap:"pretty"}}>
            {aiGreeting?tList(GREETINGS_TR,aiGreeting.period,aiGreeting.idx):(hour<5?t("hero.fallback.night"):hour<12?t("hero.fallback.morning"):hour<17?t("hero.fallback.afternoon"):t("hero.fallback.evening"))}
          </div>
        </div>
        <div style={{display:"flex",gap:isMobile?24:52,flexWrap:"wrap"}}>
          {[{n:openCount,l:t("hero.open")},{n:todayCount,l:t("hero.dueToday")},{n:deadlineCount,l:t("hero.deadlines7d")}].map((s,i)=>(
            <div key={i}>
              <div className="serif" style={{fontSize:34,fontWeight:400,fontStyle:"italic",lineHeight:1,color:"var(--col-text)",letterSpacing:"-0.02em"}}>{s.n}</div>
              <div className="cap" style={{color:"var(--col-text-3)",marginTop:6}}>{s.l}</div>
            </div>
          ))}
        </div>
      </div>

      {/* Quick Add */}
      <div style={{marginBottom:18,background:"var(--col-bg)",border:"1px solid var(--col-border)",borderRadius:8}}>
        <div style={{display:"flex",gap:10,padding:"10px 14px",alignItems:"center"}}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="var(--col-text-3)" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" style={{flexShrink:0}}><path d="M12 5v14M5 12h14"/></svg>
          <input placeholder={t("quickadd.placeholder")} value={dashQuick} onChange={e=>setDashQuick(e.target.value)} onKeyDown={e=>e.key==="Enter"&&dashAddTodo()} style={{flex:1,fontSize:14,border:"none",background:"transparent",outline:"none",color:"var(--col-text)",fontFamily:"var(--serif)",fontStyle:"italic",padding:0,overflowX:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}}/>{/* FIXED E4: quick-add input overflow handled */}
          <button onClick={dashAddTodo} className="mono" style={{padding:"6px 14px",fontSize:11,borderRadius:20,background:"var(--col-accent)",color:"var(--col-bg)",letterSpacing:"0.06em",flexShrink:0,textTransform:"uppercase"}}>{t("quickadd.add")}</button>
          <button onClick={()=>setTab("todos")} className="mono" style={{padding:"6px 12px",fontSize:11,borderRadius:20,border:"1px solid var(--col-border)",background:"transparent",color:"var(--col-text-sec)",letterSpacing:"0.06em",flexShrink:0,textTransform:"uppercase"}}>{t("quickadd.more")}</button>
        </div>
      </div>

      {/* 2-Column Grid */}
      <div style={{display:"grid",gridTemplateColumns:isMobile?"1fr":"1fr 1fr",gap:14,marginBottom:18}}>
        {/* Heute Todos */}
        <div style={{background:"var(--col-bg)",border:"1px solid var(--col-border-soft)",borderRadius:8,padding:"14px 16px",display:"flex",flexDirection:"column"}}>
          <div style={{display:"flex",justifyContent:"space-between",alignItems:"baseline",marginBottom:10,paddingBottom:8,borderBottom:"1px solid var(--col-border-soft)"}}>
            <span className="serif" style={{fontSize:18,fontStyle:"italic",fontWeight:500,letterSpacing:"-0.01em"}}>{t("today.title")}</span>
            <button onClick={()=>setTab("todos")} className="mono" style={{fontSize:10,color:"var(--col-text-3)",background:"none",border:"none",cursor:"pointer",letterSpacing:"0.08em",textTransform:"uppercase"}}>{t("common.allArrow")}</button>
          </div>
          {activeTodos.length===0&&<p className="serif" style={{fontSize:13,color:"var(--col-text-sec)",fontStyle:"italic"}}>{t("today.empty")}</p>}
          {activeTodos.slice(0,6).map(t=>{
            const isTA=String(activeTimerId)===String(t.id);
            const tMs=isTA?activeTimerElapsed:(t.timeLog||[]).reduce((sum,e)=>{const end=e.end||e.start;return sum+(end-e.start);},0);
            const fmtT=ms=>{const s=Math.floor(ms/1000),h=Math.floor(s/3600),m=Math.floor((s%3600)/60),sc=s%60;return h>0?`${h}:${String(m).padStart(2,'0')}:${String(sc).padStart(2,'0')}`:`${m}:${String(sc).padStart(2,'0')}`;};
            return(
              <div key={t.id} style={{display:"flex",alignItems:"center",gap:9,padding:"7px 0",borderBottom:"1px solid var(--col-border-soft)"}}>
                <button onClick={()=>toggleRefresh(t)} style={{width:14,height:14,borderRadius:3,border:`1.5px solid ${prioCol[t.priority||"mittel"]}`,background:"transparent",cursor:"pointer",flexShrink:0,padding:0}}/>
                <span className="serif" style={{flex:1,fontSize:13,color:"var(--col-text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0,fontWeight:400}}>{t.text}</span>
                {(isTA||tMs>0)&&<span className="mono" style={{fontSize:10,color:isTA?"var(--col-accent)":"var(--col-text-3)",flexShrink:0,letterSpacing:"0.04em",display:"inline-flex",alignItems:"center",gap:3}}>
                  {isTA&&<span style={{width:4,height:4,borderRadius:"50%",background:"var(--col-accent)",flexShrink:0,animation:"pulse .8s infinite"}}/>}
                  {fmtT(tMs)}
                </span>}
                {t.duration&&!isTA&&tMs===0&&<span className="mono" style={{fontSize:10,color:"var(--col-text-3)",flexShrink:0,letterSpacing:"0.04em"}}>{t.duration>=60?`${Math.floor(t.duration/60)}h`:`${t.duration}m`}</span>}
                {!studyBlockIds?.has(t.id)&&<button onClick={e=>{e.stopPropagation();isTA?stopTimer():startTimer(t.id);}}
                  title={isTA?"Timer stoppen":"Timer starten"}
                  style={{background:"none",border:"none",cursor:"pointer",padding:"2px",flexShrink:0,color:isTA?"var(--col-accent)":"var(--col-text-3)",opacity:isTA?1:0.4,lineHeight:1,fontSize:12}}>
                  {isTA?"⏹":"▶"}
                </button>}
              </div>
            );
          })}
          {activeTodos.length>6&&<div onClick={()=>setTab("todos")} className="mono" style={{fontSize:10,color:"var(--col-text-3)",cursor:"pointer",letterSpacing:"0.06em",marginTop:8}}>+{activeTodos.length-6} {t("common.more")}</div>}
          {openCount>activeTodos.length&&<div onClick={()=>setTab("todos")} className="mono" style={{fontSize:10,color:"var(--col-text-3)",marginTop:8,letterSpacing:"0.04em",cursor:"pointer"}}>{t("today.laterDays",{n:openCount-activeTodos.length})}</div>}
        </div>

        {/* Upcoming Deadlines */}
        <div style={{background:"var(--col-bg)",border:"1px solid var(--col-border-soft)",borderRadius:8,padding:"14px 16px",display:"flex",flexDirection:"column"}}>
          <div style={{display:"flex",justifyContent:"space-between",alignItems:"baseline",marginBottom:10,paddingBottom:8,borderBottom:"1px solid var(--col-border-soft)"}}>
            <span className="serif" style={{fontSize:18,fontStyle:"italic",fontWeight:500,letterSpacing:"-0.01em"}}>{t("deadlines.title")}</span>
            <button onClick={()=>setTab("stats")} className="mono" style={{fontSize:10,color:"var(--col-text-3)",background:"none",border:"none",cursor:"pointer",letterSpacing:"0.08em",textTransform:"uppercase"}}>{t("common.allArrow")}</button>
          </div>
          {upcomingDeadlines.length===0&&<p className="serif" style={{fontSize:13,color:"var(--col-text-sec)",fontStyle:"italic"}}>{t("deadlines.empty")}</p>}
          {upcomingDeadlines.map(td=>{
            const daysLeft=Math.round((new Date(td.deadline+"T12:00:00")-new Date(todayISO()+"T12:00:00"))/86400000);
            const urgent=daysLeft<=2;
            return(
              <div key={td.id} style={{display:"flex",alignItems:"center",gap:9,padding:"7px 0",borderBottom:"1px solid var(--col-border-soft)"}}>
                <span style={{width:5,height:5,borderRadius:"50%",background:prioCol[td.priority||"mittel"],flexShrink:0}}/>
                <span className="serif" style={{flex:1,fontSize:13,color:"var(--col-text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0,fontWeight:400}}>{td.text}</span>
                <span className="mono" style={{fontSize:10,fontWeight:500,color:urgent?"#b91c1c":"var(--col-text-3)",flexShrink:0,letterSpacing:"0.04em"}}>{daysLeft===0?t("deadlines.today"):daysLeft===1?t("deadlines.tomorrow"):t("deadlines.daysShort",{n:daysLeft})}</span>
              </div>
            );
          })}
        </div>
      </div>

      {/* Prüfungs-Erinnerungen */}
      {upcomingExams.length>0&&(
        <div style={{marginBottom:12}}>
          {upcomingExams.map(e=>{
            const urgent=e.daysLeft<=2;
            const ec=examColor(e);
            return(
              <div key={e.id} onClick={()=>setTab("pruefung")} style={{display:"flex",alignItems:"center",gap:12,padding:"10px 14px",borderRadius:8,background:urgent?hexToRgba(ec,0.08):"var(--col-bg)",border:`1px solid ${urgent?ec:"var(--col-border-soft)"}`,borderLeft:`4px solid ${ec}`,marginBottom:6,cursor:"pointer"}}>
                <div style={{flex:1,minWidth:0}}>
                  <div style={{fontSize:13,fontWeight:600,color:"var(--col-text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}}>{e.name}</div>
                  {e.openBlocks.length>0&&<div style={{fontSize:10,color:"var(--col-text-3)",marginTop:1}}>{e.openBlocks.length===1?t("exam.blocksOpen",{n:e.openBlocks.length}):t("exam.blocksOpenPlural",{n:e.openBlocks.length})}</div>}
                </div>
                <div style={{textAlign:"right",flexShrink:0}}>
                  <div className="mono" style={{fontSize:13,fontWeight:700,color:urgent?"#b91c1c":ec}}>{e.daysLeft===0?t("exam.today"):e.daysLeft===1?t("exam.tomorrow"):t("exam.daysLeft",{n:e.daysLeft})}</div>
                  <div className="mono" style={{fontSize:9,color:"var(--col-text-3)",letterSpacing:"0.04em",marginTop:1}}>{t("exam.label")}</div>
                </div>
              </div>
            );
          })}
        </div>
      )}

      {/* Lernblock-Timer */}
      {(nonDeletedExams.length>0||studyTimer)&&(
        <div style={{background:"var(--col-bg)",border:"1px solid var(--col-border-soft)",borderRadius:8,padding:"14px 16px",marginBottom:18}}>
          <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:10,paddingBottom:8,borderBottom:"1px solid var(--col-border-soft)"}}>
            <span className="serif" style={{fontSize:18,fontStyle:"italic",fontWeight:500,letterSpacing:"-0.01em"}}>{t("study.title")}</span>
            <div style={{display:"flex",alignItems:"center",gap:8}}>
              {studyTimer&&<button onClick={()=>setFocusMode(true)} className="mono" style={{fontSize:10,padding:"3px 10px",borderRadius:20,border:"1px solid var(--col-border)",color:"var(--col-text-sec)",background:"transparent",cursor:"pointer",letterSpacing:"0.04em"}}>{t("study.focus")}</button>}
              {!studyTimer&&<button onClick={()=>{if(typeof Notification!=='undefined'&&Notification.permission==='default')Notification.requestPermission();setStudyTimer({blockId:Date.now(),examId:0,todoId:null,hours:30/3600,elapsed:0,running:true,startTs:Date.now(),examName:'Test-Prüfung',subject:'Test'});}} style={{fontSize:12,padding:"4px 12px",borderRadius:10,background:"var(--col-accent)",color:"#fff",border:"none",cursor:"pointer",fontWeight:600}}>🧪 30s Test</button>}
              <span className="mono" style={{fontSize:10,color:"var(--col-text-3)",letterSpacing:"0.06em"}}>{t("study.todayCount",{n:todayStudyBlocks.length})}</span>
            </div>
          </div>
          {studyTimer?._interrupted&&(
            <div style={{padding:"8px 12px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,marginBottom:10,fontSize:12,color:"#854d0e",display:"flex",justifyContent:"space-between",alignItems:"center",gap:8}}>
              <span>{t("study.restored",{x:fmtMs(studyTimer.elapsed)})}</span>
              <button onClick={()=>setStudyTimer(t=>t?{...t,_interrupted:false}:null)} style={{background:"none",border:"none",color:"#854d0e",fontSize:16,cursor:"pointer",padding:0,lineHeight:1}}>×</button>
            </div>
          )}
          {studyTimer?(()=>{
            const elapsed=studyTimer.elapsed+(studyTimer.running?Date.now()-studyTimer.startTs:0);
            const total=studyTimer.hours*3600000;
            const remaining=total-elapsed;
            const prog=total>0?Math.min(1,Math.max(0,elapsed/total)):0;
            const eColor=examColor({id:studyTimer.examId});
            const overdue=remaining<0;
            return(
              <div style={{margin:"0 -16px -14px",padding:"0 16px 14px",background:studyTimer.running?hexToRgba(eColor,0.04):"transparent",borderRadius:"0 0 8px 8px",transition:"background 0.4s"}}>
                {/* Full-width progress bar at top */}
                <div style={{height:6,background:"var(--col-bg-sec)",margin:"0 -16px 14px",overflow:"hidden"}}>
                  <div style={{height:"100%",width:`${prog*100}%`,background:overdue?"#b91c1c":eColor,transition:"width 0.8s linear",opacity:overdue?0.8:1}}/>
                </div>
                {/* Exam name + running indicator */}
                <div style={{display:"flex",alignItems:"center",gap:8,marginBottom:12}}>
                  {studyTimer.running&&<span style={{width:7,height:7,borderRadius:"50%",background:eColor,flexShrink:0,animation:"pulse 1.8s ease-in-out infinite"}}/>}
                  {!studyTimer.running&&<span style={{width:7,height:7,borderRadius:"50%",background:"var(--col-border)",flexShrink:0}}/>}
                  <span style={{fontSize:13,fontWeight:600,color:"var(--col-text)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}}>{studyTimer.examName}</span>
                  {studyTimer.subject!==studyTimer.examName&&<span style={{fontSize:11,color:eColor,fontWeight:600,flexShrink:0}}>{studyTimer.subject}</span>}
                  <span className="mono" style={{fontSize:9,color:studyTimer.running?"#166534":"var(--col-text-3)",letterSpacing:"0.06em",flexShrink:0}}>{studyTimer.running?t("study.running"):t("study.paused")}</span>
                </div>
                {/* Time display */}
                <div style={{display:"flex",alignItems:"flex-end",gap:isMobile?16:28,marginBottom:14,flexWrap:"wrap"}}>
                  <div>
                    <div className="serif" style={{fontSize:isMobile?36:44,fontWeight:400,fontStyle:"italic",color:eColor,lineHeight:1,letterSpacing:"-0.03em"}}>{fmtMs(elapsed)}</div>
                    <div className="mono" style={{fontSize:9,color:"var(--col-text-3)",textTransform:"uppercase",letterSpacing:"0.08em",marginTop:4}}>{t("study.elapsed")}</div>
                  </div>
                  <div style={{paddingBottom:4}}>
                    <div className="serif" style={{fontSize:isMobile?22:28,fontWeight:400,fontStyle:"italic",color:overdue?"#b91c1c":"var(--col-text-sec)",lineHeight:1,letterSpacing:"-0.02em"}}>{fmtMs(remaining)}</div>
                    <div className="mono" style={{fontSize:9,color:overdue?"#b91c1c":"var(--col-text-3)",textTransform:"uppercase",letterSpacing:"0.08em",marginTop:4}}>{overdue?t("study.overdue"):t("study.remaining")}</div>
                  </div>
                  <div style={{marginLeft:"auto",paddingBottom:4}}>
                    <label style={{fontSize:9,color:"var(--col-text-3)",display:"block",marginBottom:3,textTransform:"uppercase",letterSpacing:"0.06em"}}>{t("study.target")}</label>
                    <input type="number" min="0.25" max="12" step="0.25" value={studyTimer.hours}
                      onChange={e=>{const h=parseFloat(e.target.value)||studyTimer.hours;setStudyTimer(t=>t?{...t,hours:h}:null);}}
                      disabled={studyTimer.running}
                      style={{width:60,fontSize:13,fontWeight:600,opacity:studyTimer.running?0.4:1,cursor:studyTimer.running?"not-allowed":"auto"}}/>
                  </div>
                </div>
                {/* Block switcher */}
                {todayStudyBlocks.length>1&&(
                  <div style={{display:"flex",gap:4,flexWrap:"wrap",marginBottom:10}}>
                    {todayStudyBlocks.map(b=>{const bc=examColor(b.exam);const isCur=studyTimer.blockId===b.id;return(
                      <button key={b.id} onClick={()=>startStudyTimer(b,b.exam)} style={{padding:"3px 10px",borderRadius:20,fontSize:10,border:isCur?`2px solid ${bc}`:"1px solid var(--col-border)",background:isCur?hexToRgba(bc,0.12):"transparent",color:isCur?bc:"var(--col-text-sec)",cursor:"pointer",fontWeight:isCur?600:400,letterSpacing:"0.01em"}}>
                        {b._timedOut?"✓ ":""}{b.exam.subject||b.exam.name} · {b.hours}h
                      </button>
                    );})}
                  </div>
                )}
                {/* Controls */}
                <div style={{display:"flex",gap:6}}>
                  <button onClick={studyTimer.running?pauseStudyTimer:resumeStudyTimer}
                    style={{flex:1,padding:"10px",fontSize:13,borderRadius:8,background:studyTimer.running?hexToRgba(eColor,0.12):eColor,color:studyTimer.running?eColor:"#fff",border:`1.5px solid ${eColor}`,fontWeight:700,cursor:"pointer",letterSpacing:"0.02em",transition:"background 0.2s"}}>
                    {studyTimer.running?t("study.pause"):t("study.resume")}
                  </button>
                  <button onClick={stopStudyTimer} style={{padding:"10px 16px",fontSize:13,borderRadius:8,border:"1px solid var(--col-border)",color:"var(--col-text-sec)",background:"transparent",cursor:"pointer",fontWeight:500}}>{t("study.stop")}</button>
                  {onOpenPip&&<button onClick={onOpenPip} title="Mini-Fenster" style={{padding:"10px 12px",fontSize:13,borderRadius:8,border:"1px solid var(--col-border)",color:"var(--col-text-sec)",background:"transparent",cursor:"pointer"}}>⧉</button>}
                </div>
              </div>
            );
          })():(
            <div style={{display:"flex",flexDirection:"column",gap:6}}>
              {todayStudyBlocks.length===0&&<p className="serif" style={{fontSize:13,color:"var(--col-text-sec)",fontStyle:"italic",margin:0}}>{t("study.empty")}</p>}
              {todayStudyBlocks.map(b=>{
                const bc=examColor(b.exam);
                const done=b._timedOut;
                return(
                  <div key={b.id} style={{display:"flex",alignItems:"center",gap:10,padding:"9px 12px",borderRadius:6,background:"var(--col-bg-sec)",border:"1px solid var(--col-border-soft)",borderLeft:done?"4px solid #22c55e":`4px solid ${bc}`,opacity:done?0.8:1}}>
                    <div style={{flex:1,minWidth:0}}>
                      <div style={{fontSize:13,fontWeight:500,color:done?"#22c55e":"var(--col-text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}}>{done?"✓ ":""}{b.exam.name}</div>
                      {b.exam.subject&&<div style={{fontSize:10,color:done?"#22c55e":bc,fontWeight:600,marginTop:1}}>{b.exam.subject}</div>}
                    </div>
                    <span className="mono" style={{fontSize:11,color:"var(--col-text-3)",flexShrink:0}}>{b.hours}h</span>
                    <button onClick={()=>startStudyTimer(b,b.exam)}
                      style={{padding:"6px 14px",fontSize:11,borderRadius:20,background:done?"transparent":bc,color:done?"#22c55e":"#fff",fontWeight:500,cursor:"pointer",border:done?"1.5px solid #22c55e":"none",flexShrink:0}}>{done?t("study.resume"):t("study.start")}</button>
                  </div>
                );
              })}
            </div>
          )}
        </div>
      )}

      {/* Gewohnheiten Heute */}
      {(data.habits||[]).filter(h=>!h.deletedAt).length>0&&(
        <div style={{background:"var(--col-bg)",border:"1px solid var(--col-border-soft)",borderRadius:8,padding:"14px 16px",marginBottom:18}}>
          <div style={{display:"flex",justifyContent:"space-between",alignItems:"baseline",marginBottom:10,paddingBottom:8,borderBottom:"1px solid var(--col-border-soft)"}}>
            <span className="serif" style={{fontSize:18,fontStyle:"italic",fontWeight:500,letterSpacing:"-0.01em"}}>{t("habits.title")}</span>
            <button onClick={()=>setTab("habits")} className="mono" style={{fontSize:10,color:"var(--col-text-3)",background:"none",border:"none",cursor:"pointer",letterSpacing:"0.08em",textTransform:"uppercase"}}>{t("common.allArrow")}</button>
          </div>
          <div style={{display:"grid",gridTemplateColumns:isMobile?"1fr 1fr":"repeat(auto-fill,minmax(160px,1fr))",gap:8}}>
            {(data.habits||[]).filter(h=>!h.deletedAt).map(h=>{
              let wc=null,wTarget=null,weekDone2=false;
              if(h.freq==="xweekly"){
                const d2=new Date(today+"T12:00:00");
                const dow2=(d2.getDay()+6)%7;
                d2.setDate(d2.getDate()-dow2);
                const ws=localISO(d2);
                const we=new Date(d2);we.setDate(we.getDate()+6);
                wc=(h.completions||[]).filter(iso=>iso>=ws&&iso<=localISO(we)&&iso<=today).length;
                wTarget=h.timesPerWeek||1;
                weekDone2=wc>=wTarget;
              }
              const todayChecked=(h.completions||[]).includes(today);
              const done=h.freq==="xweekly"?weekDone2:todayChecked;
              function habitToggle(){
                const c=h.completions||[];
                updateHabit({...h,completions:todayChecked?c.filter(x=>x!==today):[...c,today],updatedAt:Date.now()});
              }
              return(
                <div key={h.id} onClick={habitToggle}
                  style={{display:"flex",alignItems:"center",gap:9,padding:"10px 12px",borderRadius:8,cursor:"pointer",
                    background:done?"var(--col-accent-wash)":"var(--col-bg-sec)",
                    border:`1px solid ${done?"var(--col-accent)":"var(--col-border-soft)"}`,
                    transition:"all .15s",userSelect:"none"}}>
                  <div style={{width:22,height:22,borderRadius:"50%",flexShrink:0,
                    background:done?"var(--col-accent)":"transparent",
                    border:done?"none":"1.5px solid var(--col-border)",
                    display:"flex",alignItems:"center",justifyContent:"center",
                    color:done?"var(--col-bg)":"var(--col-text-3)",fontSize:11,fontWeight:600}}>
                    {done?"✓":""}
                  </div>
                  <div style={{flex:1,minWidth:0}}>
                    <div style={{fontSize:12,fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",
                      color:done?"var(--col-accent)":"var(--col-text)"}}>{h.name}</div>
                    {h.freq==="xweekly"&&<div className="mono" style={{fontSize:10,color:weekDone2?"#166534":"var(--col-text-3)",marginTop:1}}>{wc}/{wTarget} {t("habits.thisWeek")}</div>}
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* Mini Week Calendar */}
      <div style={{background:"var(--col-bg)",border:"1px solid var(--col-border-soft)",borderRadius:8,padding:"14px 16px"}}>
        <div style={{display:"flex",justifyContent:"space-between",alignItems:"baseline",marginBottom:14,paddingBottom:8,borderBottom:"1px solid var(--col-border-soft)"}}>
          <span className="serif" style={{fontSize:18,fontStyle:"italic",fontWeight:500,letterSpacing:"-0.01em"}}>{t("week.title")}</span>
          <button onClick={()=>{setPlanMode("agenda");setPlanFocusDate(null);setTab("plan");}} className="mono" style={{fontSize:10,color:"var(--col-text-3)",background:"none",border:"none",cursor:"pointer",letterSpacing:"0.08em",textTransform:"uppercase"}}>{t("common.planArrow")}</button>
        </div>
        <div style={{display:"grid",gridTemplateColumns:isMobile?"repeat(4,1fr)":"repeat(7,1fr)",gap:0}}>
          {weekDays.map((d,i)=>(
            <div key={d.iso} onClick={()=>{setPlanMode("agenda");setPlanFocusDate(d.iso);setTab("plan");}} style={{padding:"10px 10px 8px",cursor:"pointer",borderTop:d.isToday?"2px solid var(--col-accent)":"1px solid var(--col-border-soft)",borderRight:!isMobile&&i<6?"1px solid var(--col-border-soft)":"none"}}>
              <div className="cap" style={{color:d.isToday?"var(--col-accent)":"var(--col-text-3)",marginBottom:4}}>{d.label}</div>
              <div className="serif" style={{fontSize:24,fontStyle:d.isToday?"italic":"normal",fontWeight:d.isToday?500:400,color:d.isToday?"var(--col-accent)":"var(--col-text)",lineHeight:1,marginBottom:6,letterSpacing:"-0.02em"}}>{d.day}</div>
              {(()=>{
                const parts=[];
                if(d.deadlines>0)parts.push({n:d.deadlines,l:d.deadlines===1?t("week.deadline"):t("week.deadlines"),col:"#b91c1c"});
                if(d.tasks>0)parts.push({n:d.tasks,l:d.tasks===1?t("week.task"):t("week.tasks"),col:"var(--col-text-sec)"});
                if(d.events>0)parts.push({n:d.events,l:d.events===1?t("week.event"):t("week.events"),col:"var(--col-text-sec)"});
                if(parts.length===0)return <div className="mono" style={{fontSize:10,color:"var(--col-text-3)",letterSpacing:"0.04em",opacity:0.5}}>—</div>;
                return parts.map((p,k)=>(
                  <div key={k} className="mono" style={{fontSize:10,color:p.col,letterSpacing:"0.04em",lineHeight:1.5}}>{p.n} {p.l}</div>
                ));
              })()}
            </div>
          ))}
        </div>
      </div>

      {/* Tages-Notiz */}
      <div style={{background:"var(--col-bg)",border:"1px solid var(--col-border-soft)",borderRadius:8,padding:"14px 16px",marginTop:14}}>
        <div className="cap" style={{color:"var(--col-text-3)",marginBottom:8}}>{t("note.title")}</div>
        <textarea value={dayNote} onChange={e=>{setDayNote(e.target.value);try{localStorage.setItem(noteKey,e.target.value);}catch{}}} placeholder={t("note.placeholder")} style={{width:"100%",boxSizing:"border-box",fontSize:13,fontFamily:"var(--serif)",fontStyle:"italic",border:"none",background:"transparent",outline:"none",resize:"vertical",minHeight:64,color:"var(--col-text)",lineHeight:1.55,padding:0}}/>
      </div>
    </div>
  );
}

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