(function(){
// ============================================================
// forms.jsx — NewTodoForm + TodoItem + SlotAdder
// Depends on (window): DatePicker, CatPicker, RecurringPicker,
//   parseDuration, cleanTitle, todayISO, fmtDate, getCatColor
// ============================================================

const { useState, useEffect } = React;

// ── NewTodoForm ──────────────────────────────────────────────────────
function NewTodoForm({ onAdd, categories, subcategories, onManageCats, initialText="", hideDate=false }){
  const [text, setText] = useState("");
  const [expanded, setExpanded] = useState(false);
  const [plannedDay, setPlannedDay] = useState(null);
  const [deadline, setDeadline] = useState(null);
  const [category, setCategory] = useState(null);
  const [subcategory, setSubcategory] = useState(null);
  const [priority, setPriority] = useState("mittel");
  const [recurring, setRecurring] = useState(null);
  const [subInput, setSubInput] = useState("");
  const [subtasks, setSubtasks] = useState([]);
  const [comInput, setComInput] = useState("");
  const [comments, setComments] = useState([]);
  // FIXED: Vorlagen chips above form, prefill on click
  useEffect(() => { if (initialText) { setText(initialText); setExpanded(true); } }, [initialText]);

  const addSub = () => {
    if (!subInput.trim()) return;
    setSubtasks(s => [...s, { id: Date.now(), text: subInput.trim(), done: false }]);
    setSubInput("");
  };

  function submit(){
    if (!text.trim()) return;
    const dur = parseDuration(text);
    const t = dur ? cleanTitle(text) : text.trim();
    onAdd({
      id: Date.now(), createdAt: Date.now(), updatedAt: Date.now(),
      text: t, done: false, priority,
      plannedDay: hideDate ? null : plannedDay, deadline, category, subcategory, // FIXED: Inbox hides date field, sets plannedDay null
      subtasks, comments, duration: dur, recurring
    });
    setText(""); setPlannedDay(null); setDeadline(null);
    setCategory(null); setSubcategory(null); setPriority("mittel");
    setRecurring(null); setSubtasks([]); setComments([]);
    setSubInput(""); setComInput(""); setExpanded(false);
  }

  return (
    <div style={{background:"var(--col-bg)",border:"1px solid var(--col-border)",borderRadius:10,marginBottom:12,overflow:"hidden"}}>
      <div style={{display:"flex",gap:8,padding:"9px 12px",alignItems:"center"}}>
        <input placeholder={hideDate?window.t("form.inboxPlaceholder"):window.t("form.taskPlaceholder")}
          value={text}
          onChange={e => { setText(e.target.value); setExpanded(!!e.target.value); }}
          onKeyDown={e => e.key === "Enter" && submit()}
          style={{flex:1,fontSize:14,border:"none",background:"transparent",outline:"none",color:"var(--col-text)"}}/>
        {text.trim() && (
          <button onClick={() => setExpanded(x => !x)} title={expanded?window.t("form.collapseOptions"):window.t("form.expandOptions")}
            style={{background:"none",border:"none",color:expanded?"var(--col-accent)":"var(--col-text-sec)",fontSize:17,padding:"0 2px"}}>⊕</button>
        )}
        <button onClick={submit}
          style={{padding:"4px 12px",fontSize:12,borderRadius:20,background:"var(--col-accent)",color:"var(--col-bg)",fontWeight:500}}>{window.t("form.add")}</button>
      </div>
      {expanded && text.trim() && (
        <div style={{borderTop:"1px solid var(--col-border)",background:"var(--col-bg-sec)"}}>
          <div style={{padding:"8px 12px",borderBottom:"1px solid var(--col-border)"}}>
            <div style={{fontSize:11,fontWeight:500,color:"var(--col-text-sec)",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:5}}>{window.t("form.priority")}</div>
            <div style={{display:"flex",gap:4}}>
              {["hoch","mittel","niedrig"].map(p => (
                <button key={p} onClick={() => setPriority(p)}
                  style={{
                    padding:"3px 10px", borderRadius:20, fontSize:12,
                    border: priority === p ? "2px solid var(--col-accent)" : "1px solid var(--col-border)",
                    background: priority === p ? "var(--col-accent)" : "transparent",
                    color: priority === p ? "var(--col-bg)" : "var(--col-text-sec)"
                  }}>{window.t("prio."+p)}</button>
              ))}
            </div>
          </div>
          <div style={{padding:"8px 12px",borderBottom:"1px solid var(--col-border)"}}>
            <CatPicker value={category} subcategory={subcategory}
              onChange={setCategory} onSubChange={setSubcategory}
              categories={categories} subcategories={subcategories || {}}
              onManage={onManageCats}/>
          </div>
          {!hideDate&&(
          <div style={{padding:"8px 12px",borderBottom:"1px solid var(--col-border)",display:"flex",gap:12,flexWrap:"wrap"}}>
            <div style={{flex:1,minWidth:180}}><DatePicker value={plannedDay} onChange={setPlannedDay} label={window.t("form.plannedFor")}/></div>
            <div style={{flex:1,minWidth:180}}><DatePicker value={deadline}   onChange={setDeadline}   label={window.t("form.deadline")}/></div>
          </div>
          )}
          <div style={{padding:"8px 12px",borderBottom:"1px solid var(--col-border)"}}>
            <RecurringPicker value={recurring} onChange={setRecurring}/>
          </div>
          <div style={{padding:"8px 12px",borderBottom:"1px solid var(--col-border)"}}>
            <div style={{fontSize:11,fontWeight:500,color:"var(--col-text-sec)",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:6}}>{window.t("form.subtasks")}</div>
            {subtasks.map((s, i) => (
              <div key={s.id} style={{display:"flex",alignItems:"center",gap:6,padding:"2px 0"}}>
                <span style={{width:5,height:5,borderRadius:"50%",background:"var(--col-border)",flexShrink:0}}/>
                <span style={{flex:1,fontSize:12}}>{s.text}</span>
                <button onClick={() => setSubtasks(st => st.filter((_, j) => j !== i))}
                  style={{background:"none",border:"none",color:"var(--col-text-sec)",fontSize:13}}>×</button>
              </div>
            ))}
            <div style={{display:"flex",gap:5,marginTop:5}}>
              <input placeholder={window.t("form.subtaskPlaceholder")} value={subInput}
                onChange={e => setSubInput(e.target.value)}
                onKeyDown={e => e.key === "Enter" && addSub()}
                style={{flex:1,fontSize:12}}/>
              <button onClick={addSub}
                style={{padding:"4px 9px",fontSize:12,borderRadius:6,border:"1px solid var(--col-border)",color:"var(--col-text)"}}>{window.t("form.add")}</button>
            </div>
          </div>
          <div style={{padding:"8px 12px"}}>
            <div style={{fontSize:11,fontWeight:500,color:"var(--col-text-sec)",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:6}}>{window.t("form.comment")}</div>
            <div style={{display:"flex",gap:5}}>
              <input placeholder={window.t("form.commentPlaceholder")} value={comInput}
                onChange={e => setComInput(e.target.value)}
                onKeyDown={e => {
                  if (e.key === "Enter" && comInput.trim()) {
                    setComments(cs => [...cs, { id: Date.now(), text: comInput.trim() }]);
                    setComInput("");
                  }
                }}
                style={{flex:1,fontSize:12}}/>
              <button onClick={() => {
                  if (comInput.trim()) {
                    setComments(cs => [...cs, { id: Date.now(), text: comInput.trim() }]);
                    setComInput("");
                  }
                }}
                style={{padding:"4px 9px",fontSize:12,borderRadius:6,border:"1px solid var(--col-border)",color:"var(--col-text)"}}>{window.t("form.add")}</button>
            </div>
            {comments.map((c, i) => (
              <div key={c.id} style={{display:"flex",gap:6,marginTop:4}}>
                <span style={{flex:1,fontSize:12,color:"var(--col-text-sec)",background:"var(--col-bg)",borderRadius:6,padding:"3px 8px",border:"1px solid var(--col-border)"}}>{c.text}</span>
                <button onClick={() => setComments(cs => cs.filter((_, j) => j !== i))}
                  style={{background:"none",border:"none",color:"var(--col-text-sec)",fontSize:13}}>×</button>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

// ── TodoItem ─────────────────────────────────────────────────────────
function TodoItem({ t, onToggle, onDelete, onUpdate, onDeleteTemplate, categories, subcategories, onSync, isDragging, isDragOver, onDragStart, onDragOver, onDrop, onDragEnd, activeTimerId, timerRunning=false, liveElapsed=0, onStartTimer, onStopTimer, onDuplicate, onSaveTemplate, snoozeBadge=false }){
  const [expanded, setExpanded] = useState(false);
  const [editing, setEditing] = useState(false);
  const [completing, setCompleting] = useState(false);

  function handleToggle(){
    if (t.done) { onToggle(); return; }
    setCompleting(true);
    setTimeout(() => { setCompleting(false); onToggle(); }, 380);
  }

  const [editText, setEditText] = useState(t.text);
  const [editDeadline, setEditDeadline] = useState(t.deadline || null);
  const [editPlanned, setEditPlanned] = useState(t.plannedDay || null);
  const [editPrio, setEditPrio] = useState(t.priority || "mittel");
  const [editRecurring, setEditRecurring] = useState(t.recurring || null);
  const [editSubs, setEditSubs] = useState(t.subtasks || []);
  const [editSubInput, setEditSubInput] = useState("");
  const [editComments, setEditComments] = useState(t.comments || []);
  const [editComInput, setEditComInput] = useState("");
  const [editCategory, setEditCategory] = useState(t.category || null);
  const [editSubcategory, setEditSubcategory] = useState(t.subcategory || null);
  const [editSnooze, setEditSnooze] = useState(t.snoozedUntil || null);

  const today = todayISO();
  const isOverdue = t.deadline && t.deadline < today;
  // Timer
  const isTimerActive = activeTimerId === t.id;
  const totalMs = isTimerActive ? liveElapsed : (t.timeLog||[]).reduce((sum,e)=>{
    const end=e.end||e.start;
    return sum+(end-e.start);
  },0);
  function fmtMs(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')}`;
  }
  const durLabel = t.duration
    ? (t.duration >= 60 ? `${Math.floor(t.duration/60)}h${t.duration%60 ? t.duration%60 + "m" : ""}` : `${t.duration}m`)
    : null;
  const doneSubs = t.subtasks?.filter(s => s.done).length || 0;
  const totalSubs = t.subtasks?.length || 0;

  function startEdit(){
    setEditText(t.text);
    setEditDeadline(t.deadline || null);
    setEditPlanned(t.plannedDay || null);
    setEditPrio(t.priority || "mittel");
    setEditSubs(t.subtasks || []);
    setEditSubInput("");
    setEditComments(t.comments || []);
    setEditComInput("");
    setEditCategory(t.category || null);
    setEditSubcategory(t.subcategory || null);
    setEditRecurring(t.recurring || null);
    setEditSnooze(t.snoozedUntil || null);
    setEditing(true);
  }
  function saveEdit(){
    const rawText = editText.trim() || t.text;
    const newDur = parseDuration(rawText);
    const newText = newDur ? cleanTitle(rawText) : rawText;
    onUpdate({
      ...t,
      text: newText,
      duration: newDur !== null ? newDur : t.duration,
      deadline: editDeadline,
      plannedDay: editPlanned,
      priority: editPrio,
      subtasks: editSubs,
      comments: editComments,
      category: editCategory,
      subcategory: editSubcategory,
      recurring: editRecurring,
      snoozedUntil: editSnooze || null
    });
    setEditing(false);
  }
  function addEditSub(){
    if (!editSubInput.trim()) return;
    setEditSubs(s => [...s, { id: Date.now(), text: editSubInput.trim(), done: false }]);
    setEditSubInput("");
  }
  function addEditCom(){
    if (!editComInput.trim()) return;
    setEditComments(cs => [...cs, { id: Date.now(), text: editComInput.trim() }]);
    setEditComInput("");
  }
  function toggleSub(sid){
    onUpdate({ ...t, subtasks: t.subtasks.map(s => s.id === sid ? { ...s, done: !s.done } : s) });
  }

  return (
    <div draggable
      onDragStart={e => {
        e.dataTransfer.effectAllowed = 'move';
        try { e.dataTransfer.setData('text/todo-id', String(t.id)); } catch {}
        try { e.dataTransfer.setData('text/plain', t.text || ''); } catch {}
        onDragStart && onDragStart();
      }}
      onDragOver={e => { e.preventDefault(); onDragOver && onDragOver(); }}
      onDrop={e => { e.preventDefault(); onDrop && onDrop(); }}
      onDragEnd={onDragEnd}
      className={completing ? "todo-complete" : ""}
      style={{
        background:"var(--col-bg)",
        borderBottom: isDragOver ? "2px solid var(--col-accent)" : "1px solid var(--col-border-soft)",
        borderTop:"none", borderLeft:"none", borderRight:"none", borderRadius:0,
        marginBottom:0, overflow:"hidden",
        opacity: isDragging ? 0.4 : 1,
        transition:"opacity 0.15s, background 0.15s",
        position:"relative"
      }}>
      {isOverdue && <span style={{position:"absolute",left:0,top:0,bottom:0,width:2,background:"#b91c1c"}}/>}
      <div style={{display:"flex",alignItems:"flex-start",gap:12,padding:"11px 12px 11px 14px",cursor:"pointer"}}
           onClick={() => !editing && setExpanded(x => !x)}>
        <button onClick={e => { e.stopPropagation(); handleToggle(); }}
          aria-label={t.done ? window.t("todoitem.toggleUndone") : window.t("todoitem.toggleDone")}
          style={{
            width:16, height:16, borderRadius:4,
            border: `1.25px solid ${t.done ? "var(--col-accent)" : "var(--col-text-3)"}`,
            background: t.done || completing ? "var(--col-accent)" : "transparent",
            cursor:"pointer", flexShrink:0, marginTop:2,
            transition:"background 0.2s, border-color 0.2s",
            display:"flex", alignItems:"center", justifyContent:"center", padding:0
          }}>
          {t.done && (
            <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="var(--col-bg)" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
              <path d="M5 12l4 4 10-10"/>
            </svg>
          )}
        </button>
        <div style={{flex:1,minWidth:0}}>
          <div style={{
            fontSize:13.5, fontWeight:400,
            color: t.done ? "var(--col-text-3)" : "var(--col-text)",
            textDecoration: t.done ? "line-through" : "none",
            lineHeight:1.4, overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap"
          }}>{t.text}</div>
          {(durLabel || t.recurring || totalSubs > 0 || t.category || t.subcategory || t.deadline || (t.plannedDay && t.plannedDay !== today) || (snoozeBadge && t.snoozedUntil)) && (
            <div style={{display:"flex",alignItems:"center",gap:10,marginTop:4,flexWrap:"wrap"}}>
              {durLabel && (
                <span style={{display:"inline-flex",alignItems:"center",gap:4,color:"var(--col-text-sec)"}}>
                  <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="var(--col-text-3)" strokeWidth="1.5" strokeLinecap="round">
                    <circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>
                  </svg>
                  <span className="mono" style={{fontSize:10.5}}>{durLabel}</span>
                </span>
              )}
              {t.deadline && (
                <span style={{display:"inline-flex",alignItems:"center",gap:4,color:isOverdue?"#b91c1c":"var(--col-text-sec)"}}>
                  <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke={isOverdue?"#b91c1c":"var(--col-text-3)"} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
                    <path d="M4 4v16M4 4l13 1.5-3 4 3 4L4 14"/>
                  </svg>
                  <span className="mono" style={{fontSize:10.5}}>{fmtDate(t.deadline)}</span>
                </span>
              )}
              {t.plannedDay === "someday" && (
                <span className="mono" style={{fontSize:10.5,color:"var(--col-text-3)"}}>{window.t("todoitem.someday")}</span>
              )}
              {t.plannedDay && t.plannedDay !== today && t.plannedDay !== "someday" && (
                <span style={{display:"inline-flex",alignItems:"center",gap:4,color:"var(--col-text-sec)"}}>
                  <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="var(--col-text-3)" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
                    <rect x="3" y="5" width="18" height="16" rx="1"/><path d="M3 9h18M8 3v4M16 3v4"/>
                  </svg>
                  <span className="mono" style={{fontSize:10.5}}>{fmtDate(t.plannedDay)}</span>
                </span>
              )}
              {t.category && (() => {
                const cc = getCatColor(categories, t.category);
                return (
                  <span style={{display:"inline-flex",alignItems:"center",gap:5,padding:"1px 7px",borderRadius:10,background:cc.bg,color:cc.col,fontSize:10.5,fontWeight:500}}>
                    {t.category}{t.subcategory ? <span style={{opacity:0.6}}>· {t.subcategory}</span> : null}
                  </span>
                );
              })()}
              {(t.recurring || t._fromTemplate) && (
                <span style={{display:"inline-flex",alignItems:"center",gap:4,color:"var(--col-text-3)"}}>
                  <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
                    <path d="M3 12a9 9 0 0 1 15-6.7L21 8M21 4v4h-4M21 12a9 9 0 0 1-15 6.7L3 16M3 20v-4h4"/>
                  </svg>
                  <span className="mono" style={{fontSize:10.5}}>
                    {window.t("todoitem.recurring")}{(()=>{
                      const r=t.recurring;
                      if(!r||!(r.deadlineDays>0))return"";
                      const base=t.plannedDay&&t.plannedDay!=="someday"?t.plannedDay:null;
                      if(!base)return` · DL +${r.deadlineDays}T`;
                      const d=new Date(base+"T12:00:00");d.setDate(d.getDate()+r.deadlineDays);
                      return` · DL ${fmtDate(localISO(d))}`;
                    })()}
                  </span>
                </span>
              )}
              {totalSubs > 0 && (
                <span className="mono" style={{fontSize:10.5,color:doneSubs===totalSubs?"#166534":"var(--col-text-3)"}}>
                  {doneSubs}/{totalSubs} {window.t("todoitem.steps")}
                </span>
              )}
              {(isTimerActive||totalMs>0)&&(
                <span style={{display:"inline-flex",alignItems:"center",gap:4,padding:"1px 7px",borderRadius:10,fontFamily:"var(--mono)",fontSize:10.5,background:isTimerActive?"var(--col-accent)":"transparent",color:isTimerActive?"var(--col-bg)":"var(--col-text-3)"}}>
                  {isTimerActive&&<span style={{width:5,height:5,borderRadius:"50%",background:"var(--col-bg)",flexShrink:0,animation:"pulse .8s infinite"}}/>}
                  {fmtMs(totalMs)}
                </span>
              )}
              {t._calMissing && (
                <span title={window.t("todoitem.calMissingTitle")} style={{display:"inline-flex",alignItems:"center",gap:4,padding:"1px 7px",borderRadius:10,background:"#fef3c7",color:"#92400e",fontSize:10.5,fontWeight:500}}>
                  <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M12 9v4M12 17h.01"/><path d="M10.3 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/></svg>
                  {window.t("todoitem.calMissing")}
                </span>
              )}
              {t._calDrift && !t._calMissing && (
                <span title={window.t("todoitem.calDriftTitle",{fields:Object.keys(t._calDrift).join(", ")})} style={{display:"inline-flex",alignItems:"center",gap:4,padding:"1px 7px",borderRadius:10,background:"#fef3c7",color:"#92400e",fontSize:10.5,fontWeight:500}}>
                  <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M21 12a9 9 0 1 1-3-6.7L21 8"/><path d="M21 3v5h-5"/></svg>
                  {window.t("todoitem.calDrift")}
                </span>
              )}
              {snoozeBadge && t.snoozedUntil && (
                <span className="mono" style={{fontSize:10,color:"var(--col-text-3)",marginLeft:6}}>{window.t("todoitem.wakeAt",{date:t.snoozedUntil})}</span>
              )}
            </div>
          )}
        </div>
        {t.priority && t.priority !== "mittel" && (
          <span style={{
            width:6, height:6, borderRadius:"50%",
            background: t.priority === "hoch" ? "#b91c1c" : "#166534",
            flexShrink:0, marginTop:7
          }}/>
        )}
        {onStartTimer && !t.done && (
          <button onClick={e=>{e.stopPropagation();(isTimerActive&&timerRunning)?onStopTimer():onStartTimer(t.id);}}
            title={!isTimerActive?window.t("todoitem.timerStart"):timerRunning?window.t("todoitem.timerStop"):window.t("todoitem.timerResume")}
            style={{background:"none",border:"none",cursor:"pointer",padding:"2px 4px",flexShrink:0,marginTop:3,
              color:isTimerActive?"var(--col-accent)":"var(--col-text-3)",
              fontSize:isTimerActive?15:13,opacity:isTimerActive?1:0.45,lineHeight:1}}>
            {(isTimerActive&&timerRunning)?"⏹":"▶"}
          </button>
        )}
      </div>
      {expanded && !editing && (
        <div style={{background:"var(--col-bg-sec)",padding:"8px 12px 10px",borderTop:"1px solid var(--col-border)"}}>
          {totalSubs > 0 && (
            <div style={{marginBottom:8}}>
              {t.subtasks.map(s => (
                <div key={s.id} style={{display:"flex",gap:7,alignItems:"center",padding:"3px 0",borderBottom:"0.5px solid var(--col-border)"}}>
                  <button onClick={() => toggleSub(s.id)}
                    style={{
                      width:15, height:15, borderRadius:3,
                      border: `2px solid ${s.done ? "var(--col-accent)" : "var(--col-border)"}`,
                      background: s.done ? "var(--col-accent)" : "transparent",
                      cursor:"pointer", flexShrink:0,
                      display:"flex", alignItems:"center", justifyContent:"center", padding:0
                    }}>
                    {s.done && <span style={{color:"var(--col-bg)",fontSize:9,lineHeight:1}}>✓</span>}
                  </button>
                  <span style={{
                    fontSize:12,
                    color: s.done ? "var(--col-text-sec)" : "var(--col-text)",
                    textDecoration: s.done ? "line-through" : "none",
                    flex:1
                  }}>{s.text}</span>
                </div>
              ))}
            </div>
          )}
          {t.comments?.length > 0 && (
            <div style={{marginBottom:6,maxHeight:120,overflowY:"auto"}}>{/* FIXED E7: comment block max-height added */}
              {t.comments.map(c => <div key={c.id} style={{fontSize:12,color:"var(--col-text-sec)",padding:"2px 0"}}>{c.text}</div>)}
            </div>
          )}
          <div style={{display:"flex",gap:6,marginTop:6,flexWrap:"wrap"}}>
            <button onClick={startEdit}
              style={{padding:"5px 12px",fontSize:11,borderRadius:20,border:"1px solid var(--col-border)",color:"var(--col-text-sec)",fontFamily:"var(--mono)",letterSpacing:"0.04em"}}>{window.t("todoitem.edit")}</button>
            {onDuplicate&&(
              <button onClick={onDuplicate}
                style={{padding:"5px 12px",fontSize:11,borderRadius:20,border:"1px solid var(--col-border)",color:"var(--col-text-sec)",fontFamily:"var(--mono)",letterSpacing:"0.04em"}}>{window.t("todoitem.duplicate")}</button>
            )}
            {onSaveTemplate&&(
              <button onClick={()=>onSaveTemplate(t)}
                style={{padding:"5px 12px",fontSize:11,borderRadius:20,border:"1px solid var(--col-border)",color:"var(--col-text-sec)",fontFamily:"var(--mono)",letterSpacing:"0.04em",display:"inline-flex",alignItems:"center",gap:5}}>
                {/* FIXED: star emoji replaced with SVG */}
                <svg width="13" height="13" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinejoin="round"><polygon points="7,1 8.8,5.2 13.5,5.6 10,8.7 11.1,13.3 7,10.8 2.9,13.3 4,8.7 0.5,5.6 5.2,5.2"/></svg>
                {window.t("todoitem.template")}</button>
            )}
            {onSync && (
              <button onClick={onSync}
                style={{padding:"5px 12px",fontSize:11,borderRadius:20,border:"1px solid var(--col-border)",color:"var(--col-text-sec)",fontFamily:"var(--mono)",letterSpacing:"0.04em",display:"inline-flex",alignItems:"center",gap:5}}>
                <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
                  <rect x="3" y="5" width="18" height="16" rx="1"/><path d="M3 9h18M8 3v4M16 3v4"/>
                </svg>
                {window.t("todoitem.calendar")}
              </button>
            )}
            <button onClick={onDelete}
              style={{padding:"5px 12px",fontSize:11,borderRadius:20,border:"1px solid #fca5a5",color:"#b91c1c",fontFamily:"var(--mono)",letterSpacing:"0.04em"}}>{window.t("todoitem.delete")}</button>
            {t._fromTemplate && onDeleteTemplate && (
              <button onClick={onDeleteTemplate}
                style={{padding:"5px 12px",fontSize:11,borderRadius:20,border:"1px solid #fca5a5",color:"#b91c1c",fontFamily:"var(--mono)",letterSpacing:"0.04em"}}>{window.t("todoitem.stopRecurring")}</button>
            )}
          </div>
        </div>
      )}
      {editing && (
        <div style={{background:"var(--col-bg-sec)",padding:"10px 12px",borderTop:"1px solid var(--col-border)"}}
          onKeyDown={e=>{if(e.key==="Escape"){const changed=editText!==t.text||editDeadline!==(t.deadline||null)||editPlanned!==(t.plannedDay||null)||editPrio!==(t.priority||"mittel")||editCategory!==(t.category||null);if(changed&&!confirm(window.t("form.discardConfirm")))return;setEditing(false);}}}>
          <input value={editText}
            onChange={e => setEditText(e.target.value)}
            onKeyDown={e => e.key === "Enter" && saveEdit()}
            style={{width:"100%",boxSizing:"border-box",fontSize:13,marginBottom:8}}/>
          <div style={{display:"flex",gap:4,marginBottom:8}}>
            {["hoch","mittel","niedrig"].map(p => (
              <button key={p} onClick={() => setEditPrio(p)}
                style={{
                  padding:"3px 9px", fontSize:11, borderRadius:20,
                  border: editPrio === p ? "2px solid var(--col-accent)" : "1px solid var(--col-border)",
                  background: editPrio === p ? "var(--col-accent)" : "transparent",
                  color: editPrio === p ? "var(--col-bg)" : "var(--col-text-sec)"
                }}>{window.t("prio."+p)}</button>
            ))}
          </div>
          <div style={{display:"flex",gap:12,marginBottom:8,flexWrap:"wrap"}}>
            <div style={{flex:1,minWidth:160}}><DatePicker value={editPlanned}  onChange={setEditPlanned}  label={window.t("form.plannedFor")}/></div>
            <div style={{flex:1,minWidth:160}}><DatePicker value={editDeadline} onChange={setEditDeadline} label={window.t("form.deadline")}/></div>
            <div style={{flex:1,minWidth:160}}>
              <DatePicker value={editSnooze} onChange={setEditSnooze} label={window.t("form.snooze")}/>
              {/* FIXED: Wiedervorlage hint text added */}
              <div style={{fontSize:10,color:"var(--col-text-3)",marginTop:3}}>{window.t("form.snoozeHint")}</div>
            </div>
          </div>
          <div style={{marginBottom:8}}>
            <CatPicker value={editCategory} subcategory={editSubcategory}
              onChange={v => { setEditCategory(v); setEditSubcategory(null); }}
              onSubChange={setEditSubcategory}
              categories={categories} subcategories={subcategories || {}}
              onManage={() => {}}/>
          </div>
          {!t._fromTemplate&&(
            <div style={{marginBottom:8}}>
              <RecurringPicker value={editRecurring} onChange={setEditRecurring} plannedDay={editPlanned}/>
            </div>
          )}
          {/* Unteraufgaben bearbeiten */}
          <div style={{marginBottom:8}}>
            <div style={{fontSize:11,fontWeight:500,color:"var(--col-text-sec)",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:5}}>{window.t("form.subtasks")}</div>
            {editSubs.map((s, i) => (
              <div key={s.id} style={{display:"flex",gap:6,alignItems:"center",padding:"3px 0",borderBottom:"0.5px solid var(--col-border)"}}>
                <span style={{width:5,height:5,borderRadius:"50%",background:"var(--col-accent)",flexShrink:0}}/>
                <span style={{flex:1,fontSize:12,color:"var(--col-text)"}}>{s.text}</span>
                <button onClick={() => setEditSubs(ss => ss.filter((_, j) => j !== i))}
                  style={{background:"none",border:"none",color:"var(--col-text-sec)",cursor:"pointer",fontSize:13,padding:0}}>×</button>
              </div>
            ))}
            <div style={{display:"flex",gap:5,marginTop:5}}>
              <input placeholder={window.t("form.newSubtaskPlaceholder")} value={editSubInput}
                onChange={e => setEditSubInput(e.target.value)}
                onKeyDown={e => e.key === "Enter" && addEditSub()}
                style={{flex:1,fontSize:12}}/>
              <button onClick={addEditSub}
                style={{padding:"4px 9px",fontSize:12,borderRadius:6,border:"1px solid var(--col-border)",color:"var(--col-text)"}}>{window.t("form.add")}</button>
            </div>
          </div>
          {/* Kommentare bearbeiten */}
          <div style={{marginBottom:8}}>
            <div style={{fontSize:11,fontWeight:500,color:"var(--col-text-sec)",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:5}}>{window.t("form.comments")}</div>
            {editComments.map((c, i) => (
              <div key={c.id} style={{display:"flex",gap:6,alignItems:"center",padding:"3px 0",borderBottom:"0.5px solid var(--col-border)"}}>
                <span style={{flex:1,fontSize:12,color:"var(--col-text-sec)"}}>{c.text}</span>
                <button onClick={() => setEditComments(cs => cs.filter((_, j) => j !== i))}
                  style={{background:"none",border:"none",color:"var(--col-text-sec)",cursor:"pointer",fontSize:13,padding:0}}>×</button>
              </div>
            ))}
            <div style={{display:"flex",gap:5,marginTop:5}}>
              <input placeholder={window.t("form.newCommentPlaceholder")} value={editComInput}
                onChange={e => setEditComInput(e.target.value)}
                onKeyDown={e => e.key === "Enter" && addEditCom()}
                style={{flex:1,fontSize:12}}/>
              <button onClick={addEditCom}
                style={{padding:"4px 9px",fontSize:12,borderRadius:6,border:"1px solid var(--col-border)",color:"var(--col-text)"}}>{window.t("form.add")}</button>
            </div>
          </div>
          <div style={{display:"flex",gap:6}}>
            <button onClick={saveEdit}
              style={{padding:"5px 14px",fontSize:12,borderRadius:20,background:"var(--col-accent)",color:"var(--col-bg)",fontWeight:500}}>{window.t("todoitem.save")}</button>
            <button onClick={() => { // FIXED: warn before discarding unsaved changes
              const changed=editText!==t.text||editDeadline!==(t.deadline||null)||editPlanned!==(t.plannedDay||null)||editPrio!==(t.priority||"mittel")||editCategory!==(t.category||null)||editSubcategory!==(t.subcategory||null);
              if(changed&&!confirm(window.t("form.discardConfirm")))return;
              setEditing(false);
            }}
              style={{padding:"5px 14px",fontSize:12,borderRadius:20,border:"1px solid var(--col-border)",color:"var(--col-text-sec)"}}>{window.t("todoitem.cancel")}</button>
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { NewTodoForm, TodoItem });

})();
