/* =========================================================================
   Çevik Yaşam — GÖREVLER (ana liste · kategori › proje › todo + checklist)
   Hiyerarşik: Grup (kategori) → Proje → Görevler → Checklist
   ========================================================================= */

function PrioPicker({ value, onChange }) {
  return (
    <div className="cy-seg" style={{ flexWrap: "wrap" }}>
      {CY.prioLevels.map((p) => (
        <button key={p.v} className={"cy-choice" + (value === p.v ? " on" : "")} onClick={() => onChange(p.v)}
          style={value === p.v ? { background: p.color, borderColor: p.color, color: "#fff" } : null}>
          <i style={{ width: 8, height: 8, borderRadius: 999, background: value === p.v ? "#fff" : p.color }} />{p.short}
        </button>
      ))}
    </div>
  );
}

/* checklist editörü (görev kartı içinde) */
function Checklist({ items, onChange }) {
  const [txt, setTxt] = useState("");
  const toggle = (id) => onChange(items.map((c) => (c.id === id ? { ...c, done: !c.done } : c)));
  const add = () => { if (!txt.trim()) return; onChange([...items, { id: uid("c"), t: txt.trim(), done: false }]); setTxt(""); };
  const del = (id) => onChange(items.filter((c) => c.id !== id));
  const done = items.filter((c) => c.done).length;
  return (
    <div className="cy-checklist">
      {!!items.length && (
        <div className="cy-between" style={{ marginBottom: 8 }}>
          <span className="cy-muted" style={{ fontSize: 12 }}>Checklist · {done}/{items.length}</span>
          <div className="cy-prog" style={{ width: 90 }}><i style={{ width: (items.length ? done / items.length * 100 : 0) + "%" }} /></div>
        </div>
      )}
      <div className="cy-stack" style={{ gap: 4 }}>
        {items.map((c) => (
          <div key={c.id} className="cy-cl-row">
            <button className={"cy-check sm" + (c.done ? " on" : "")} onClick={() => toggle(c.id)}><Icon name="check" className="ic" /></button>
            <span style={{ flex: 1, fontSize: 13, textDecoration: c.done ? "line-through" : "none", color: c.done ? "var(--ml-ink-4)" : "var(--ml-ink-2)" }}>{c.t}</span>
            <button className="cy-iconbtn-sm" onClick={() => del(c.id)}><Icon name="x" style={{ width: 13 }} /></button>
          </div>
        ))}
      </div>
      <div style={{ display: "flex", gap: 7, marginTop: 8 }}>
        <input className="cy-input" style={{ padding: "7px 11px", fontSize: 13 }} placeholder="Alt adım ekle…" value={txt}
          onChange={(e) => setTxt(e.target.value)} onKeyDown={(e) => e.key === "Enter" && add()} />
        <Btn variant="ghost" size="sm" icon="plus" onClick={add}>Ekle</Btn>
      </div>
    </div>
  );
}

const MONTHS_S = ["Oca", "Şub", "Mar", "Nis", "May", "Haz", "Tem", "Ağu", "Eyl", "Eki", "Kas", "Ara"];
// ADHD önceliklendirme: kritik/öncelikli/çok-ertelenen/esas üstte, bitenler altta
function cyTaskWeight(t) {
  if (t.done) return 1000;
  let w = (t.prio || 3) * 10;
  if (t.due && t.due < CY.today.iso) w -= 40;
  if ((t.deferCount || 0) >= 3) w -= 30;
  if (t.sub && CY.subproj(t.sub) && CY.subproj(t.sub).core) w -= 15;
  if (t.due === CY.today.iso) w -= 8;
  return w;
}
function cyTaskCmp(a, b) { return cyTaskWeight(a) - cyTaskWeight(b); }
function dueInfo(t) {
  if (!t.due) return { label: null, overdue: false };
  const overdue = t.due < CY.today.iso && !t.done;
  const d = new Date(t.due);
  const label = t.due === CY.today.iso ? "Bugün" : d.getDate() + " " + MONTHS_S[d.getMonth()];
  return { label, overdue };
}

function TaskItem({ t, coll, onStart, onDefer, onComplete, onFocus, onEdit, onDelete, onOpen, defaultOpen }) {
  const [open, setOpen] = useState(!!defaultOpen);
  const p = CY.prio(t.prio);
  const cl = t.checklist || [];
  const clDone = cl.filter((c) => c.done).length;
  const di = dueInfo(t);
  return (
    <div className={"cy-titem" + (t.done ? " done" : "")} style={{ borderLeftColor: p.color }}>
      <div className="cy-titem-main">
        <button className={"cy-check" + (t.done ? " on" : "")} onClick={() => { if (!t.done) onComplete(t); else coll.update(t.id, { done: false }); }}><Icon name="check" className="ic" /></button>
        <div style={{ flex: 1, minWidth: 0 }}>
          <span className="cy-titem-title" onClick={onOpen} style={onOpen ? { cursor: "pointer" } : null} title={onOpen ? "Detayı aç" : undefined}>{t.title}</span>
          <div className="cy-titem-meta">
            <span className="cy-pill" style={{ padding: "2px 9px", fontSize: 11, color: p.color, background: p.color + "12", border: "none" }}><i style={{ width: 6, height: 6, borderRadius: 999, background: p.color }} />{p.short}</span>
            {t.sub && CY.subproj(t.sub) && (() => { const sk = CY.subKind(CY.subproj(t.sub).kind); return <span className="cy-tag-mini" style={{ color: sk.color, background: sk.color + "14", fontWeight: 600 }}>{sk.short !== "★ Esas" ? sk.label + " · " : "★ "}{CY.subproj(t.sub).name}</span>; })()}
            {di.label && <span className="cy-tag-mini" style={di.overdue ? { color: "var(--ml-red)", background: "var(--ml-red-050)" } : null}><Icon name="clock" style={{ width: 10, marginRight: 3, verticalAlign: "-1px" }} />{di.label}{di.overdue ? " · geçti" : ""}</span>}
            {t.today && <span className="cy-tag-mini" style={{ color: "var(--ml-info)", background: "var(--ml-info-bg)" }}>Bugün</span>}
            {!!cl.length && <span className="cy-tag-mini">☑ {clDone}/{cl.length}</span>}
            {t.deferCount > 0 && <span className="cy-tag-mini" style={{ color: t.deferCount >= 3 ? "var(--ml-red)" : "var(--ml-warn)", background: t.deferCount >= 3 ? "var(--ml-red-050)" : "var(--ml-warn-bg)" }}>↻ {t.deferCount}× ertelendi</span>}
            {t.emotional && <span className="cy-tag-mini" style={{ color: "var(--ml-red)", background: "var(--ml-red-050)" }}>duygusal</span>}
            {t.notify && <span className="cy-tag-mini"><Icon name="bell" style={{ width: 10, marginRight: 3, verticalAlign: "-1px" }} />{t.notify}</span>}
            {t.spentMin > 0 && <span className="cy-tag-mini" style={{ color: "var(--ml-success)", background: "var(--ml-success-bg)" }}>⏱ {t.spentMin} dk</span>}
          </div>
        </div>
        <div style={{ display: "flex", gap: 2, flex: "none", alignItems: "center" }}>
          {!t.done && <button className="cy-btn ghost sm" onClick={() => onFocus(t)} style={{ padding: "6px 9px" }} title="Odak modu (pomodoro)"><Icon name="timer" className="ic" /></button>}
          {!t.done && <button className="cy-btn ghost sm" onClick={() => onStart(t)} style={{ padding: "6px 9px" }} title="Bugüne çek"><Icon name="arrowUp" className="ic" /></button>}
          {!t.done && <button className="cy-btn ghost sm" onClick={() => onDefer(t)} style={{ padding: "6px 9px" }} title="Ertele"><Icon name="snooze" className="ic" /></button>}
          <button className="cy-iconbtn-sm" onClick={() => setOpen(!open)}><Icon name="chevronDown" style={{ transform: open ? "rotate(180deg)" : "none", transition: "transform .2s" }} /></button>
          <RowMenu onEdit={() => onEdit(t)} onDelete={() => onDelete(t)} />
        </div>
      </div>
      {open && (
        <div className="cy-titem-body">
          {t.hint && <div className="cy-defer-tip" style={{ marginBottom: 12 }}><Icon name="sparkles" className="ic" /><span>{t.hint}</span></div>}
          <Checklist items={cl} onChange={(items) => coll.update(t.id, { checklist: items })} />
          <div style={{ display: "flex", gap: 8, marginTop: 12 }}>
            {!t.today && !t.done && <Btn variant="ghost" size="sm" icon="arrowUp" onClick={() => coll.update(t.id, { today: true })} style={{ color: "var(--ml-info)" }}>Bugüne çek</Btn>}
            {t.today && !t.done && <Btn variant="ghost" size="sm" icon="arrowDown" onClick={() => coll.update(t.id, { today: false })}>Bugünden çıkar</Btn>}
          </div>
        </div>
      )}
    </div>
  );
}

const TASK_FIELDS_FULL = [
  { name: "title", label: "Görev", placeholder: "Ne yapılacak?" },
  { name: "project", label: "Proje", type: "dropdown", optgroups: CY.projectOptgroups, default: "tr-platform" },
  { name: "sub", label: "Alt proje", type: "depdropdown", placeholder: "— alt proje yok —", optional: true,
    optionsFn: (v) => CY.subsOf(v.project).map((s) => ({ value: s.id, label: CY.subKind(s.kind).short + " · " + s.name })) },
  { name: "prio", label: "Öncelik", type: "select", options: CY.prioLevels.map((p) => ({ value: p.v, label: p.short })), default: 3 },
  { name: "block", label: "Çalışma mesafesi", type: "select", options: ["Kuş bakışı", "Normal", "Odaklı yakın"], default: "Normal" },
  { name: "due", label: "Tarih", type: "date", optional: true },
  { name: "est", label: "Tahmini süre", placeholder: "örn. 30 dk", optional: true },
  { name: "hint", label: "Çevik not", placeholder: "İpucu / yaklaşım", optional: true },
];

function Gorevler() {
  const T = useCollection("tasks", CY.todayTasks);
  const [grpF, setGrpF] = useState("all");
  const [prioF, setPrioF] = useState("all");
  const [q, setQ] = useState("");
  const [edit, setEdit] = useState(null);
  const [del, setDel] = useState(null);
  const [defer, setDefer] = useState(null);
  const [complete, setComplete] = useState(null);
  const [focus, setFocus] = useState(null);
  const [collapsed, setCollapsed] = useStore("gorev-collapsed", {});
  const [coreOnly, setCoreOnly] = useState(false);
  const [hideDone, setHideDone] = useStore("gorev-hidedone", false);

  const list = T.active.filter((t) =>
    (grpF === "all" || CY.proj(t.project).group === grpF) &&
    (prioF === "all" || t.prio === prioF) &&
    (!coreOnly || (t.sub && CY.subproj(t.sub) && CY.subproj(t.sub).core)) &&
    (!hideDone || !t.done) &&
    (!q || t.title.toLowerCase().includes(q.toLowerCase()))
  );

  // hiyerarşi: grup → proje → görevler
  const tree = CY.groups
    .filter((g) => grpF === "all" || g.key === grpF)
    .map((g) => {
      const projs = CY.projects.filter((p) => p.group === g.key)
        .map((p) => ({ proj: p, tasks: list.filter((t) => t.project === p.id) }))
        .filter((x) => x.tasks.length);
      const count = projs.reduce((a, x) => a + x.tasks.length, 0);
      return { group: g, projs, count };
    })
    .filter((x) => x.count);

  const total = list.length;
  const doneCount = list.filter((t) => t.done).length;
  const toggleCollapse = (k) => setCollapsed((c) => ({ ...c, [k]: !c[k] }));

  const startTask = (t) => {
    T.update(t.id, { today: true });
    try { localStorage.setItem("cy:active-task", JSON.stringify(t.id)); if (window.CY_STATE) window.CY_STATE["cy:active-task"] = t.id; window.cySaveState && window.cySaveState("cy:active-task", t.id); } catch (e) {}
    window.cyGoto && window.cyGoto("bugun");
  };
  const handleDefer = (patch) => {
    T.update(defer.id, patch);
    setDefer(null);
  };

  return (
    <div className="cy-canvas cy-fade-in">
      <SectionHead eyebrow="Ana liste · tüm yapılacaklar"
        title="Görevler"
        sub="Kategoriye ve projeye göre hiyerarşik. Her görevde öncelik, tarih, checklist; ertele akışı duygusal engelleri yakalar."
        right={<Btn variant="primary" icon="plus" onClick={() => setEdit({})}>Görev ekle</Btn>} />

      <HowTo id="gorevler" when="Backlog · her şey burada"
        summary="Tüm işlerinin <strong>tek doğruluk kaynağı.</strong> Kategori › proje hiyerarşisinde durur; buradan güne çeker, önceliklendirir, ertelersin."
        steps={[
          "Aklına geleni hemen <strong>Görev ekle</strong> ile buraya at — proje ve öncelik seç.",
          "Görevi açıp <strong>checklist</strong> ile alt adımlara böl; karmaşık işi küçült.",
          "<strong>Bugüne çek</strong> ile günlük listene al; <strong>saat ikonu</strong> ile ertele.",
          "Bir işi 3+ kez ertelersen sistem duygusal engeli sorar ve seni Engeller'e yönlendirir.",
        ]} />

      {/* özet + filtreler */}
      <div className="cy-toolbar">
        <div className="cy-search">
          <Icon name="search" className="ic" />
          <input placeholder="Görev ara…" value={q} onChange={(e) => setQ(e.target.value)} />
        </div>
        <div style={{ flex: 1 }} />
        <button className={"cy-fchip" + (hideDone ? " on" : "")} onClick={() => setHideDone(!hideDone)} title="Tamamlananları gizle">
          <Icon name={hideDone ? "eye" : "check"} style={{ width: 13 }} /> {hideDone ? "Tamamlananlar gizli" : "Tamamlananları gizle"}
        </button>
        <button className={"cy-fchip" + (coreOnly ? " on" : "")} onClick={() => setCoreOnly(!coreOnly)} title="Sadece esas alt projeler">
          <Icon name="target" style={{ width: 13 }} /> Sadece esas
        </button>
        <span className="cy-muted cy-mono" style={{ fontSize: 13 }}>{doneCount}/{total}</span>
      </div>

      <div className="cy-filterbar" style={{ marginTop: 12 }}>
        <div className="cy-fgroup">
          <span className="cy-fglabel">Kategori</span>
          <button className={"cy-fchip" + (grpF === "all" ? " on" : "")} onClick={() => setGrpF("all")}>Tümü</button>
          {CY.groups.map((g) => <button key={g.key} className={"cy-fchip" + (grpF === g.key ? " on" : "")} onClick={() => setGrpF(grpF === g.key ? "all" : g.key)}><i className="cy-proj-dot" style={{ background: g.color, width: 8, height: 8 }} />{g.label}</button>)}
        </div>
        <div className="cy-fgroup">
          <span className="cy-fglabel">Öncelik</span>
          <button className={"cy-fchip" + (prioF === "all" ? " on" : "")} onClick={() => setPrioF("all")}>Tümü</button>
          {CY.prioLevels.map((p) => <button key={p.v} className={"cy-fchip" + (prioF === p.v ? " on" : "")} onClick={() => setPrioF(prioF === p.v ? "all" : p.v)}><i style={{ width: 8, height: 8, borderRadius: 999, background: p.color }} />{p.short}</button>)}
        </div>
      </div>

      {/* hiyerarşik liste */}
      <div style={{ marginTop: 22 }}>
        {tree.map(({ group, projs, count }) => (
          <div key={group.key} className="cy-cat-block">
            <button className="cy-cat-head" onClick={() => toggleCollapse(group.key)}>
              <Icon name="chevronDown" style={{ width: 16, transform: collapsed[group.key] ? "rotate(-90deg)" : "none", transition: "transform .2s", color: "var(--ml-ink-4)" }} />
              <i style={{ width: 11, height: 11, borderRadius: 3, background: group.color }} />
              <h3 className="cy-h4" style={{ fontSize: 15 }}>{group.label}</h3>
              <span className="cy-mono cy-muted" style={{ fontSize: 12 }}>{count}</span>
            </button>
            {!collapsed[group.key] && projs.map(({ proj, tasks }) => {
              const subs = CY.subsOf(proj.id);
              const noSub = tasks.filter((t) => !t.sub || !CY.subproj(t.sub)).sort(cyTaskCmp);
              const subGroups = subs
                .map((s) => ({ sub: s, tasks: tasks.filter((t) => t.sub === s.id).sort(cyTaskCmp) }))
                .filter((x) => x.tasks.length)
                .sort((a, b) => ({ esas: 0, ilgi: 1, takip: 2 }[a.sub.kind] ?? 1) - ({ esas: 0, ilgi: 1, takip: 2 }[b.sub.kind] ?? 1));
              return (
              <div key={proj.id} className="cy-proj-block">
                <div className="cy-proj-head">
                  <i className="cy-proj-dot" style={{ background: proj.color }} />
                  <span className="cy-proj-name">{proj.name}</span>
                  <PrioMini v={proj.priority} />
                  <span className="cy-mono cy-muted" style={{ fontSize: 11.5 }}>{tasks.length}</span>
                </div>
                {subGroups.map(({ sub, tasks: stasks }) => (
                  <div key={sub.id} className="cy-sub-block">
                    <div className="cy-sub-head">
                      <span className={"cy-sub-badge " + (sub.kind || "ilgi")}>{CY.subKind(sub.kind).short}</span>
                      <span className="cy-sub-name">{sub.name}</span>
                      <span className="cy-mono cy-muted" style={{ fontSize: 11 }}>{stasks.length}</span>
                    </div>
                    <div className="cy-stack" style={{ gap: 8 }}>
                      {stasks.map((t) => <TaskItem key={t.id} t={t} coll={T} onStart={startTask} onDefer={setDefer} onComplete={setComplete} onFocus={setFocus} onEdit={setEdit} onDelete={setDel} onOpen={() => window.cyGotoTask && window.cyGotoTask(t.id)} />)}
                    </div>
                  </div>
                ))}
                {!!noSub.length && (
                  <div className="cy-stack" style={{ gap: 8, marginTop: subGroups.length ? 8 : 0 }}>
                    {noSub.map((t) => <TaskItem key={t.id} t={t} coll={T} onStart={startTask} onDefer={setDefer} onComplete={setComplete} onFocus={setFocus} onEdit={setEdit} onDelete={setDel} onOpen={() => window.cyGotoTask && window.cyGotoTask(t.id)} />)}
                  </div>
                )}
              </div>
              );
            })}
          </div>
        ))}
        {!tree.length && <div className="cy-empty">Bu filtreye uyan görev yok.</div>}
      </div>

      {edit && <EditSheet eyebrow={edit.id ? "Görevi düzenle" : "Yeni görev"} title={edit.id ? "Görevi düzenle" : "Görev ekle"}
        fields={TASK_FIELDS_FULL} initial={edit.id ? edit : null}
        onClose={() => setEdit(null)}
        onSave={(v) => { const due = v.due && v.due.trim() ? v.due.trim() : null; edit.id ? T.update(edit.id, { ...v, due }) : T.add({ ...v, due, done: false, today: false, checklist: [], deferCount: 0 }); setEdit(null); }} />}
      {del && <ConfirmSheet body={`"${del.title}" silinecek.`} onClose={() => setDel(null)} onConfirm={() => { T.remove(del.id); setDel(null); }} />}
      {defer && <DeferSheet task={defer} onClose={() => setDefer(null)} onDefer={handleDefer} onOpenBlocker={() => { setDefer(null); window.cyGoto && window.cyGoto("engeller"); }} />}
      {complete && <CompleteSheet task={complete}
        onClose={() => setComplete(null)}
        onDone={() => { T.update(complete.id, { done: true }); setComplete(null); }}
        onAddFollowup={(f) => T.add(f)} />}
      {focus && <FocusMode task={focus} onClose={() => setFocus(null)}
        onLog={(t, mins) => T.update(t.id, { spentMin: (t.spentMin || 0) + mins, today: true })}
        onComplete={(t) => setComplete(t)} />}
    </div>
  );
}

function PrioMini({ v }) {
  const p = CY.prio(v);
  return <span style={{ fontSize: 10.5, fontWeight: 600, color: p.color, background: p.color + "14", padding: "1px 7px", borderRadius: 999 }}>{p.short}</span>;
}

Object.assign(window, { Gorevler, Checklist, PrioPicker, TASK_FIELDS_FULL });
