/* ============================================================
   screen_tasks.jsx — Задачи и автоплан (M17)
   Виды: список / канбан · фильтры · drawer-деталка
   ============================================================ */
function Tasks({ ctx }) {
  const [view, setView] = React.useState("list");
  const [fSite, setFSite] = React.useState(ctx.activeSite === "all" ? "all" : ctx.site);
  const [fPrio, setFPrio] = React.useState("all");
  const [fType, setFType] = React.useState("all");
  const [tasks, setTasks] = React.useState(() => DATA.tasks.map(t => ({ ...t })));
  const [openTask, setOpenTask] = React.useState(null);

  const types = ["all", "Техническое", "Контент", "AI SEO"];
  const filtered = tasks.filter(t =>
    (fSite === "all" || t.site === fSite) &&
    (fPrio === "all" || t.sev === fPrio) &&
    (fType === "all" || t.type === fType)
  );

  function updateTask(id, patch) {
    setTasks(ts => ts.map(t => t.id === id ? { ...t, ...patch } : t));
    setOpenTask(ot => ot && ot.id === id ? { ...ot, ...patch } : ot);
  }

  const active = filtered.filter(t => t.status !== "done").length;
  const crit = filtered.filter(t => t.sev === "critical" && t.status !== "done").length;

  return (
    <div className="grid" style={{ gap: 16 }}>
      {/* weekly plan banner */}
      <div className="card" style={{ background: "linear-gradient(100deg, var(--accent-softer), var(--surface) 60%)", borderColor: "#DCEAF7" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 16, padding: "16px 20px" }}>
          <span style={{ width: 42, height: 42, borderRadius: 12, background: "var(--accent)", color: "#fff", display: "flex", alignItems: "center", justifyContent: "center", flex: "0 0 42px" }}><Icon name="calendar" size={21} /></span>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 14.5, fontWeight: 800 }}>План на эту неделю готов</div>
            <div style={{ fontSize: 13, color: "var(--ink-2)", marginTop: 2, fontWeight: 500 }}>{crit} критичных фикса, 2 статьи и 1 настройка Schema. Оценка времени — <b>~3 часа</b>.</div>
          </div>
          <button className="btn btn-ghost btn-sm">Изменить</button>
          <button className="btn btn-primary btn-sm"><Icon name="check_circle" size={14} />Принять план</button>
        </div>
      </div>

      {/* toolbar */}
      <div style={{ display: "flex", alignItems: "center", gap: 12, flexWrap: "wrap" }}>
        <div className="seg">
          <button className={view === "list" ? "on" : ""} onClick={() => setView("list")}><Icon name="list" size={14} style={{ marginRight: 5, verticalAlign: "-2px" }} />Список</button>
          <button className={view === "kanban" ? "on" : ""} onClick={() => setView("kanban")}><Icon name="columns" size={14} style={{ marginRight: 5, verticalAlign: "-2px" }} />Канбан</button>
        </div>
        <div style={{ width: 1, height: 24, background: "var(--border)" }} />
        <FilterSelect value={fSite} onChange={setFSite} options={[["all", "Все сайты"], ...DATA.sites.map(s => [s.id, s.title])]} icon="globe" />
        <FilterSelect value={fPrio} onChange={setFPrio} options={[["all", "Все приоритеты"], ["critical", "Критично"], ["important", "Важно"], ["minor", "Желательно"], ["content", "Контент"]]} icon="filter" />
        <div className="chips">
          {types.map(t => <button key={t} className={"chip" + (fType === t ? " on" : "")} onClick={() => setFType(t)}>{t === "all" ? "Все типы" : t}</button>)}
        </div>
        <div style={{ flex: 1 }} />
        <span style={{ fontSize: 13, color: "var(--ink-3)", fontWeight: 700 }}>{active} активных</span>
      </div>

      {view === "list"
        ? <TaskList tasks={filtered} onOpen={setOpenTask} updateTask={updateTask} />
        : <Kanban tasks={filtered} onOpen={setOpenTask} updateTask={updateTask} />}

      {openTask && <TaskDrawer task={openTask} onClose={() => setOpenTask(null)} updateTask={updateTask} />}
    </div>
  );
}

function FilterSelect({ value, onChange, options, icon }) {
  return (
    <div style={{ position: "relative", display: "inline-flex", alignItems: "center" }}>
      <Icon name={icon} size={15} style={{ position: "absolute", left: 11, color: "var(--ink-4)", pointerEvents: "none" }} />
      <select className="select" value={value} onChange={e => onChange(e.target.value)} style={{ height: 36, width: "auto", paddingLeft: 32, paddingRight: 30, fontWeight: 600, fontSize: 13, cursor: "pointer", appearance: "none" }}>
        {options.map(([v, l]) => <option key={v} value={v}>{l}</option>)}
      </select>
      <Icon name="chevron_down" size={15} style={{ position: "absolute", right: 9, color: "var(--ink-4)", pointerEvents: "none" }} />
    </div>
  );
}

function TaskList({ tasks, onOpen, updateTask }) {
  const siteOf = id => DATA.sites.find(s => s.id === id);
  return (
    <div className="card">
      {tasks.map((t, i) => {
        const m = severityMeta[t.sev]; const done = t.status === "done";
        return (
          <div key={t.id} className="clickable" style={{ display: "flex", alignItems: "center", gap: 13, padding: "13px 18px", borderBottom: i === tasks.length - 1 ? "none" : "1px solid var(--border)", cursor: "pointer", opacity: done ? .55 : 1 }} onClick={() => onOpen(t)}>
            <div className="prio-bar" style={{ background: m.color, height: 32 }} />
            <Cbx on={done} onClick={(e) => { e.stopPropagation(); updateTask(t.id, { status: done ? "new" : "done" }); }} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 13.5, fontWeight: 700, textDecoration: done ? "line-through" : "none", color: "var(--ink)" }}>{t.title}</div>
              <div style={{ display: "flex", alignItems: "center", gap: 9, marginTop: 4 }}>
                <span style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: 11.5, fontWeight: 700, color: "var(--ink-3)" }}><Favicon site={siteOf(t.site)} size={15} radius={4} />{siteOf(t.site).title}</span>
                <span className="badge b-gray">{t.type}</span>
              </div>
            </div>
            <div style={{ display: "flex", alignItems: "center", gap: 16 }}>
              <span style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: 12, color: "var(--ink-3)", fontWeight: 600 }}><Icon name="clock" size={13} />{t.est}</span>
              <span style={{ display: "inline-flex", alignItems: "center", gap: 4, fontSize: 12, color: "var(--green-ink)", fontWeight: 700, minWidth: 86 }}><Icon name="trending" size={13} />{t.impact}</span>
              <span style={{ color: "var(--ink-4)" }}><Icon name="chevron_right" size={17} /></span>
            </div>
          </div>
        );
      })}
      {tasks.length === 0 && <div style={{ padding: 40, textAlign: "center", color: "var(--ink-3)" }}>Нет задач под выбранные фильтры</div>}
    </div>
  );
}

function Kanban({ tasks, onOpen, updateTask }) {
  const cols = [
    { id: "new", label: "Новые", color: "var(--ink-4)" },
    { id: "progress", label: "В работе", color: "var(--blue)" },
    { id: "done", label: "Готово", color: "var(--green)" },
  ];
  const siteOf = id => DATA.sites.find(s => s.id === id);
  const [dragId, setDragId] = React.useState(null);
  return (
    <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 16, alignItems: "start" }}>
      {cols.map(col => {
        const items = tasks.filter(t => t.status === col.id);
        return (
          <div key={col.id} style={{ background: "var(--bg-sunken)", borderRadius: 14, padding: 10, minHeight: 140 }}
            onDragOver={e => e.preventDefault()}
            onDrop={() => { if (dragId) updateTask(dragId, { status: col.id }); setDragId(null); }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8, padding: "6px 8px 10px" }}>
              <span className="dot" style={{ background: col.color }} />
              <span style={{ fontSize: 13, fontWeight: 800 }}>{col.label}</span>
              <span className="tnum" style={{ fontSize: 12, color: "var(--ink-4)", fontWeight: 700 }}>{items.length}</span>
            </div>
            <div style={{ display: "flex", flexDirection: "column", gap: 9 }}>
              {items.map(t => {
                const m = severityMeta[t.sev];
                return (
                  <div key={t.id} className="card card-pad" draggable
                    onDragStart={() => setDragId(t.id)} onClick={() => onOpen(t)}
                    style={{ padding: 13, cursor: "grab", borderLeft: `3px solid ${m.color}` }}>
                    <div style={{ fontSize: 13, fontWeight: 700, lineHeight: 1.35, marginBottom: 9 }}>{t.title}</div>
                    <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                      <span style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: 11, fontWeight: 700, color: "var(--ink-3)" }}><Favicon site={siteOf(t.site)} size={14} radius={4} />{siteOf(t.site).title}</span>
                      <span style={{ flex: 1 }} />
                      <span style={{ fontSize: 11, color: "var(--ink-4)", fontWeight: 600 }}>{t.est}</span>
                    </div>
                  </div>
                );
              })}
              {items.length === 0 && <div style={{ padding: "16px 8px", textAlign: "center", fontSize: 12, color: "var(--ink-4)" }}>Перетащите задачу сюда</div>}
            </div>
          </div>
        );
      })}
    </div>
  );
}

function TaskDrawer({ task, onClose, updateTask }) {
  const m = severityMeta[task.sev];
  const site = DATA.sites.find(s => s.id === task.site);
  const [timer, setTimer] = React.useState(false);
  const [secs, setSecs] = React.useState(0);
  React.useEffect(() => {
    if (!timer) return;
    const iv = setInterval(() => setSecs(s => s + 1), 1000);
    return () => clearInterval(iv);
  }, [timer]);
  const fmt = s => `${String(Math.floor(s / 60)).padStart(2, "0")}:${String(s % 60).padStart(2, "0")}`;

  function toggleStep(i) {
    const cl = task.checklist.map((c, idx) => idx === i ? { ...c, done: !c.done } : c);
    updateTask(task.id, { checklist: cl });
  }
  const doneSteps = task.checklist.filter(c => c.done).length;
  const pct = Math.round((doneSteps / task.checklist.length) * 100);

  return (
    <>
      <div className="scrim" onClick={onClose} />
      <aside className="drawer">
        <div className="drawer-head">
          <span className={"badge b-" + m.cls}>{m.label}</span>
          <span className="badge b-gray">{task.type}</span>
          <div style={{ flex: 1 }} />
          <button className="icon-btn" onClick={onClose}><Icon name="x" size={16} /></button>
        </div>
        <div className="drawer-body">
          <h2 style={{ margin: "0 0 12px", fontSize: 18, fontWeight: 800, letterSpacing: "-.01em", lineHeight: 1.3 }}>{task.title}</h2>
          <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginBottom: 16 }}>
            <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 12.5, fontWeight: 700, color: "var(--ink-2)", background: "var(--bg-sunken)", padding: "5px 10px", borderRadius: 8 }}><Favicon site={site} size={15} radius={4} />{site.title}</span>
            <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 12.5, fontWeight: 700, color: "var(--ink-2)", background: "var(--bg-sunken)", padding: "5px 10px", borderRadius: 8 }}><Icon name="clock" size={14} />{task.est}</span>
            <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 12.5, fontWeight: 700, color: "var(--green-ink)", background: "var(--green-soft)", padding: "5px 10px", borderRadius: 8 }}><Icon name="trending" size={14} />Влияние {task.impact}</span>
          </div>
          <p style={{ fontSize: 13.5, color: "var(--ink-2)", lineHeight: 1.55, margin: "0 0 20px" }}>{task.desc}</p>

          <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 10 }}>
            <h3 style={{ margin: 0, fontSize: 13.5, fontWeight: 800 }}>Пошаговый чек-лист</h3>
            <div style={{ flex: 1 }} />
            <span className="tnum" style={{ fontSize: 12, color: "var(--ink-4)", fontWeight: 700 }}>{doneSteps}/{task.checklist.length}</span>
          </div>
          <div className="bar" style={{ marginBottom: 14 }}><i style={{ width: pct + "%", background: pct === 100 ? "var(--green)" : "var(--accent)" }} /></div>
          <div style={{ display: "flex", flexDirection: "column", gap: 4, marginBottom: 20 }}>
            {task.checklist.map((c, i) => (
              <div key={i} style={{ display: "flex", alignItems: "flex-start", gap: 11, padding: "9px 11px", borderRadius: 10, background: c.done ? "var(--green-soft)" : "var(--surface)", border: "1px solid " + (c.done ? "transparent" : "var(--border)"), cursor: "pointer" }} onClick={() => toggleStep(i)}>
                <Cbx on={c.done} onClick={(e) => { e.stopPropagation(); toggleStep(i); }} />
                <span style={{ fontSize: 13, fontWeight: 500, color: c.done ? "var(--green-ink)" : "var(--ink)", textDecoration: c.done ? "line-through" : "none", lineHeight: 1.4 }}>{c.t}</span>
              </div>
            ))}
          </div>

          {task.code && <div style={{ marginBottom: 20 }}>
            <div style={{ fontSize: 12, fontWeight: 700, color: "var(--ink-4)", textTransform: "uppercase", letterSpacing: ".04em", marginBottom: 8 }}>Пример кода</div>
            <CodeBlock code={task.code} />
          </div>}
        </div>

        <div style={{ borderTop: "1px solid var(--border)", padding: "14px 20px", background: "var(--surface)", display: "flex", alignItems: "center", gap: 10 }}>
          <button className={"btn btn-sm " + (timer ? "btn-soft" : "btn-ghost")} onClick={() => setTimer(t => !t)}>
            <Icon name="clock" size={14} />{timer ? fmt(secs) : "Таймер"}
          </button>
          <div style={{ flex: 1 }} />
          {task.status !== "progress" && task.status !== "done" && <button className="btn btn-ghost btn-sm" onClick={() => updateTask(task.id, { status: "progress" })}>В работу</button>}
          <button className="btn btn-primary btn-sm" onClick={() => { updateTask(task.id, { status: "done" }); onClose(); }}><Icon name="check_circle" size={15} />Готово</button>
        </div>
      </aside>
    </>
  );
}

window.Tasks = Tasks;
window.FilterSelect = FilterSelect;
