// ─────────────────────────────────────────────────────────────
// TASKS — filterable list + create/edit + full task detail
// ─────────────────────────────────────────────────────────────
function Tasks({ profile, tasks, projects, clients, profiles, projectEditors, refresh, openTaskId, setOpenTaskId, projectFilter, onClearProjectFilter }) {
  const { Card, Btn, StatusBadge, PriorityBadge, Select, Input, Empty, SectionTitle, Avatar } = window.PUI;
  const P = window.PORTAL;
  const isAdmin = profile.role === "admin";
  const isClient = profile.role === "client";

  const [fClient, setFClient] = React.useState("");
  const [fEditor, setFEditor] = React.useState("");
  const [fProject, setFProject] = React.useState(projectFilter || "");
  const [fStatus, setFStatus] = React.useState("");
  const [fPriority, setFPriority] = React.useState("");
  const [fDue, setFDue] = React.useState("");
  const [q, setQ] = React.useState("");
  const [createOpen, setCreateOpen] = React.useState(false);

  React.useEffect(() => { setFProject(projectFilter || ""); }, [projectFilter]);

  const editors = profiles.filter(p => p.role === "editor");
  const nameOf = (id) => profiles.find(p => p.id === id)?.full_name || "Unassigned";
  const projectOf = (id) => projects.find(p => p.id === id);

  const today = new Date(); today.setHours(0,0,0,0);
  const filtered = tasks.filter(t => {
    const proj = projectOf(t.project_id);
    if (q && !(t.title.toLowerCase().includes(q.toLowerCase()) || (t.description||"").toLowerCase().includes(q.toLowerCase()))) return false;
    if (fProject && t.project_id !== fProject) return false;
    if (fClient && proj?.client_id !== fClient) return false;
    if (fEditor && t.assigned_editor !== fEditor) return false;
    if (fStatus && t.status !== fStatus) return false;
    if (fPriority && t.priority !== fPriority) return false;
    if (fDue) {
      if (!t.due_date) return false;
      const d = new Date(t.due_date + "T00:00:00");
      if (fDue === "overdue" && !(d < today && t.status !== "completed")) return false;
      if (fDue === "today" && d.getTime() !== today.getTime()) return false;
      if (fDue === "week") { const wk = new Date(today.getTime() + 7 * 86400000); if (d < today || d > wk) return false; }
    }
    return true;
  }).sort((a, b) => new Date(b.updated_at) - new Date(a.updated_at));

  const projName = projectFilter ? projectOf(projectFilter)?.name : null;

  return (
    <div>
      <SectionTitle right={(isAdmin || isClient) && <Btn onClick={() => setCreateOpen(true)}>+ New Task</Btn>}>
        {projName ? <span>Tasks · <span style={{ color: "var(--gold-500)" }}>{projName}</span></span> : "Tasks"}
      </SectionTitle>
      {projName && <div style={{ marginTop: -10, marginBottom: 16 }}><button onClick={onClearProjectFilter} style={{ background: "none", border: "none", color: "var(--text-tertiary)", fontSize: 12, cursor: "pointer" }}>← All tasks</button></div>}

      {/* Filters */}
      <div className="pfilters" style={{ display: "flex", gap: 8, flexWrap: "wrap", marginBottom: 16 }}>
        <Input placeholder="Search tasks…" value={q} onChange={e => setQ(e.target.value)} style={{ maxWidth: 220, flex: "1 1 180px" }} />
        {isAdmin && <Select value={fClient} onChange={e => setFClient(e.target.value)} style={{ width: "auto" }}>
          <option value="">All clients</option>{clients.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
        </Select>}
        <Select value={fProject} onChange={e => setFProject(e.target.value)} style={{ width: "auto" }}>
          <option value="">All projects</option>{projects.map(p => <option key={p.id} value={p.id}>{p.name}</option>)}
        </Select>
        {!isClient && <Select value={fEditor} onChange={e => setFEditor(e.target.value)} style={{ width: "auto" }}>
          <option value="">All editors</option>{editors.map(ed => <option key={ed.id} value={ed.id}>{ed.full_name || ed.email}</option>)}
        </Select>}
        <Select value={fStatus} onChange={e => setFStatus(e.target.value)} style={{ width: "auto" }}>
          <option value="">All statuses</option>{P.STATUSES.map(s => <option key={s.id} value={s.id}>{s.label}</option>)}
        </Select>
        <Select value={fPriority} onChange={e => setFPriority(e.target.value)} style={{ width: "auto" }}>
          <option value="">All priorities</option>{P.PRIORITIES.map(p => <option key={p.id} value={p.id}>{p.label}</option>)}
        </Select>
        <Select value={fDue} onChange={e => setFDue(e.target.value)} style={{ width: "auto" }}>
          <option value="">Any due date</option><option value="overdue">Overdue</option>
          <option value="today">Due today</option><option value="week">Due this week</option>
        </Select>
      </div>

      {/* List */}
      <Card padding={0}>
        {filtered.length === 0
          ? <Empty icon="◈" title="No tasks found" sub="Try adjusting your filters or create a new task." />
          : filtered.map(t => {
            const overdue = t.due_date && new Date(t.due_date + "T23:59:59") < new Date() && t.status !== "completed";
            return (
              <div key={t.id} onClick={() => setOpenTaskId(t.id)} className="ptask-row" style={{
                display: "grid", gridTemplateColumns: "1fr auto auto auto auto", gap: 16, alignItems: "center",
                padding: "15px 22px", borderBottom: "1px solid var(--border-subtle)", cursor: "pointer",
              }}
              onMouseEnter={(e) => e.currentTarget.style.background = "rgba(255,255,255,0.02)"}
              onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}>
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontSize: 14, fontWeight: 600, color: "var(--text-primary)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{t.title}</div>
                  <div style={{ fontSize: 12, color: "var(--text-tertiary)", marginTop: 2 }}>{projectOf(t.project_id)?.name || "—"}</div>
                </div>
                <div className="ptask-editor" style={{ display: "flex", alignItems: "center", gap: 8 }}>
                  <Avatar name={nameOf(t.assigned_editor)} size={24} />
                  <span style={{ fontSize: 12, color: "var(--text-secondary)", whiteSpace: "nowrap" }}>{nameOf(t.assigned_editor)}</span>
                </div>
                <PriorityBadge priority={t.priority} />
                <span style={{ fontSize: 12, fontWeight: 600, color: overdue ? "#E2492E" : "var(--text-tertiary)", whiteSpace: "nowrap" }}>{t.due_date ? P.fmtDate(t.due_date) : "—"}</span>
                <StatusBadge status={t.status} />
              </div>
            );
          })}
      </Card>

      {createOpen && (
        <TaskModal profile={profile} projects={projects} profiles={profiles} projectEditors={projectEditors}
          clients={clients} defaultProject={fProject} onClose={() => setCreateOpen(false)}
          onSaved={() => { setCreateOpen(false); refresh(); }} />
      )}

      {openTaskId && (
        <TaskDetail taskId={openTaskId} profile={profile} projects={projects} profiles={profiles}
          clients={clients} projectEditors={projectEditors} refresh={refresh} onClose={() => setOpenTaskId(null)} />
      )}
    </div>
  );
}

// ── Create / edit task modal ──
function TaskModal({ profile, projects, profiles, projectEditors, clients = [], task, defaultProject, onClose, onSaved }) {
  const { Modal, Field, Input, Select, Textarea, Btn, Avatar } = window.PUI;
  const P = window.PORTAL;
  const isAdmin = profile.role === "admin";
  const isClient = profile.role === "client";

  // Client context: their record + dedicated editor
  const myClient = clients.find(cl => cl.profile_id === profile.id);
  const dedicatedEditor = myClient?.dedicated_editor ? profiles.find(pr => pr.id === myClient.dedicated_editor) : null;

  const [title, setTitle] = React.useState(task?.title || "");
  const [desc, setDesc] = React.useState(task?.description || "");
  const [projectId, setProjectId] = React.useState(task?.project_id || defaultProject || "");
  const [projectName, setProjectName] = React.useState(task ? (projects.find(pr => pr.id === task.project_id)?.name || "") : "");
  const [status, setStatus] = React.useState(task?.status || "todo");
  const [priority, setPriority] = React.useState(task?.priority || "medium");
  const [due, setDue] = React.useState(task?.due_date || "");
  const [editor, setEditor] = React.useState(task?.assigned_editor || "");
  const [drive, setDrive] = React.useState(task?.drive_folder_url || "");
  const [links, setLinks] = React.useState((task?.reference_links || []).join("\n"));
  const [busy, setBusy] = React.useState(false);

  const editorsAll = profiles.filter(pr => pr.role === "editor");

  // Admin convenience: picking a project pre-fills that client's dedicated editor
  const onPickProject = (pid) => {
    setProjectId(pid);
    if (!task && !editor) {
      const proj = projects.find(pr => pr.id === pid);
      const cl = clients.find(x => x.id === proj?.client_id);
      if (cl?.dedicated_editor) setEditor(cl.dedicated_editor);
    }
  };

  const save = async () => {
    if (!title.trim()) return alert("Enter a task title.");
    setBusy(true);
    try {
      let pid = projectId;
      let assignedEditor = editor || null;

      if (isClient) {
        // Project is a required free-text field for clients
        const pname = projectName.trim();
        if (!pname) { setBusy(false); return alert("Enter a project name."); }
        if (!myClient) { setBusy(false); return alert("Your account isn't linked to a client record yet. Please contact Zentro at support@zentrovisuals.com."); }
        if (!dedicatedEditor && !task) { setBusy(false); return alert("No editor has been assigned to your account yet. Zentro will assign your dedicated editor shortly — please try again soon or contact support@zentrovisuals.com."); }

        // Reuse an existing project with the same name, or create it
        const existing = projects.find(pr => pr.client_id === myClient.id && pr.name.toLowerCase() === pname.toLowerCase());
        if (existing) {
          pid = existing.id;
        } else {
          const { data: np, error: pe } = await sb.from("projects")
            .insert({ name: pname, client_id: myClient.id, created_by: profile.id }).select().single();
          if (pe) throw pe;
          pid = np.id;
          if (dedicatedEditor) {
            await sb.from("project_editors").insert({ project_id: pid, editor_id: dedicatedEditor.id });
          }
        }
        // Editor is always their dedicated editor (locked)
        assignedEditor = task ? (task.assigned_editor || dedicatedEditor?.id || null) : dedicatedEditor.id;
      } else {
        if (!pid) { setBusy(false); return alert("Select a project."); }
        if (!assignedEditor) { setBusy(false); return alert("Assign an editor to this task."); }
      }

      const payload = {
        title: title.trim(), description: desc, project_id: pid,
        status, priority, due_date: due || null,
        assigned_editor: assignedEditor, drive_folder_url: drive.trim(),
        reference_links: links.split("\n").map(l => l.trim()).filter(Boolean),
      };
      const proj = projects.find(pr => pr.id === pid) || { name: isClient ? projectName.trim() : "", client_id: myClient?.id };

      if (task) {
        await sb.from("tasks").update(payload).eq("id", task.id);
        await window.logActivity(task.id, profile.id, "updated the task");
        await window.emitEvent("task_updated", { task: { ...task, ...payload }, project: proj, actor: profile, title: (profile.full_name || "Someone") + " updated \u201C" + title + "\u201D" });
      } else {
        const { data: t, error } = await sb.from("tasks").insert({ ...payload, created_by: profile.id }).select().single();
        if (error) throw error;
        await window.logActivity(t.id, profile.id, "created this task");
        if (assignedEditor) await window.emitEvent("task_assigned", { task: t, project: proj, actor: profile, title: "New task assigned: \u201C" + title + "\u201D", body: proj?.name || "" });
        else await window.emitEvent("task_updated", { task: t, project: proj, actor: profile, title: (profile.full_name || "Someone") + " created \u201C" + title + "\u201D", body: proj?.name || "" });
      }
      onSaved();
    } catch (e) { alert("Save failed: " + e.message); }
    setBusy(false);
  };

  return (
    <Modal open onClose={onClose} width={600}>
      <h3 style={{ fontFamily: "var(--font-display)", fontWeight: 900, fontSize: 22, letterSpacing: "-0.02em", marginBottom: 22 }}>{task ? "Edit Task" : "New Task"}</h3>
      <div style={{ display: "flex", flexDirection: "column", gap: 15 }}>
        <Field label="Title" required><Input value={title} onChange={e => setTitle(e.target.value)} placeholder="e.g. Edit June property reel" /></Field>
        <Field label="Description"><Textarea value={desc} onChange={e => setDesc(e.target.value)} placeholder="Brief, goals, references, timestamps…" /></Field>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>

          {isClient ? (
            <React.Fragment>
              <Field label="Project" required>
                <Input value={projectName} onChange={e => setProjectName(e.target.value)} placeholder="e.g. June Content Batch" />
                <span style={{ fontSize: 11, color: "var(--text-tertiary)" }}>Type a new name or an existing project name to add this task to it.</span>
              </Field>
              <Field label="Assigned Editor" required>
                {dedicatedEditor ? (
                  <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "9px 13px", borderRadius: 10, background: "rgba(251,208,40,0.06)", border: "1.5px solid rgba(251,208,40,0.3)" }}>
                    <Avatar name={dedicatedEditor.full_name || dedicatedEditor.email} size={26} />
                    <div>
                      <div style={{ fontSize: 13, fontWeight: 700, color: "var(--text-primary)" }}>{dedicatedEditor.full_name || dedicatedEditor.email}</div>
                      <div style={{ fontSize: 10, color: "var(--gold-400)", fontWeight: 700, letterSpacing: "0.06em", textTransform: "uppercase" }}>Your dedicated editor</div>
                    </div>
                  </div>
                ) : (
                  <div style={{ padding: "11px 13px", borderRadius: 10, background: "var(--surface-inset)", border: "1.5px dashed var(--border-default)", fontSize: 12, color: "var(--text-tertiary)", lineHeight: 1.5 }}>
                    Pending — Zentro is assigning your dedicated editor.
                  </div>
                )}
              </Field>
            </React.Fragment>
          ) : (
            <React.Fragment>
              <Field label="Project" required>
                <Select value={projectId} onChange={e => onPickProject(e.target.value)}>
                  <option value="">— Select —</option>
                  {projects.map(p => <option key={p.id} value={p.id}>{p.name}</option>)}
                </Select>
              </Field>
              <Field label="Assigned Editor" required>
                <Select value={editor} onChange={e => setEditor(e.target.value)}>
                  <option value="">— Select editor —</option>
                  {editorsAll.map(ed => <option key={ed.id} value={ed.id}>{ed.full_name || ed.email}</option>)}
                </Select>
              </Field>
            </React.Fragment>
          )}

          <Field label="Status">
            <Select value={status} onChange={e => setStatus(e.target.value)}>
              {P.STATUSES.map(s => <option key={s.id} value={s.id}>{s.label}</option>)}
            </Select>
          </Field>
          <Field label="Priority">
            <Select value={priority} onChange={e => setPriority(e.target.value)}>
              {P.PRIORITIES.map(pr => <option key={pr.id} value={pr.id}>{pr.label}</option>)}
            </Select>
          </Field>
          <Field label="Due Date"><Input type="date" value={due} onChange={e => setDue(e.target.value)} /></Field>
          <Field label="Google Drive Folder"><Input value={drive} onChange={e => setDrive(e.target.value)} placeholder="https://drive.google.com/…" /></Field>
        </div>
        <Field label="Reference Links (one per line)"><Textarea value={links} onChange={e => setLinks(e.target.value)} style={{ minHeight: 60 }} placeholder={"https://youtube.com/…\nhttps://instagram.com/…"} /></Field>
        <div style={{ display: "flex", gap: 10, marginTop: 6 }}>
          <Btn onClick={save} disabled={busy}>{busy ? "Saving…" : task ? "Save Changes" : "Create Task"}</Btn>
          <Btn variant="secondary" onClick={onClose}>Cancel</Btn>
        </div>
      </div>
    </Modal>
  );
}

window.Tasks = Tasks;
window.TaskModal = TaskModal;
