// ─────────────────────────────────────────────────────────────
// PROJECTS — grid, create/edit modal (admin), project workspace
// ─────────────────────────────────────────────────────────────
function Projects({ profile, projects, clients, profiles, tasks, projectEditors, refresh, onOpenProject }) {
  const { Card, Btn, Modal, Field, Input, Select, Empty, SectionTitle } = window.PUI;
  const P = window.PORTAL;
  const isAdmin = profile.role === "admin";
  const [modal, setModal] = React.useState(null); // null | {} | project

  const editorsOf = (pid) => projectEditors.filter(pe => pe.project_id === pid).map(pe => profiles.find(p => p.id === pe.editor_id)).filter(Boolean);
  const clientOf = (cid) => clients.find(c => c.id === cid);
  const progressOf = (pid) => {
    const pt = tasks.filter(t => t.project_id === pid);
    if (!pt.length) return 0;
    return Math.round(pt.filter(t => t.status === "completed").length / pt.length * 100);
  };

  const STATUS_LABEL = { active: "Active", on_hold: "On Hold", completed: "Completed", archived: "Archived" };
  const STATUS_COLOR = { active: "#3FB57A", on_hold: "#E5A13A", completed: "var(--gold-500)", archived: "var(--ink-400)" };

  return (
    <div>
      <SectionTitle right={isAdmin && <Btn onClick={() => setModal({})}>+ New Project</Btn>}>Projects</SectionTitle>

      {projects.length === 0
        ? <Card><Empty icon="▦" title="No projects yet" sub={isAdmin ? "Create your first project to get started." : "You'll see projects here once they're assigned to you."} /></Card>
        : (
          <div className="pgrid-3" style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 14 }}>
            {projects.map(p => {
              const prog = progressOf(p.id);
              const eds = editorsOf(p.id);
              const openCount = tasks.filter(t => t.project_id === p.id && t.status !== "completed").length;
              return (
                <Card key={p.id} hover onClick={() => onOpenProject(p.id)} padding={22}>
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 10 }}>
                    <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 17, letterSpacing: "-0.01em", color: "var(--text-primary)" }}>{p.name}</div>
                    {isAdmin && (
                      <button onClick={(e) => { e.stopPropagation(); setModal(p); }} style={{ background: "none", border: "none", color: "var(--text-tertiary)", cursor: "pointer", fontSize: 15, padding: 2 }}>✎</button>
                    )}
                  </div>
                  <div style={{ fontSize: 13, color: "var(--text-tertiary)", marginTop: 4 }}>{clientOf(p.client_id)?.name || "No client"}</div>

                  <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 14 }}>
                    <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 11, fontWeight: 700, color: STATUS_COLOR[p.status] }}>
                      <span style={{ width: 6, height: 6, borderRadius: "50%", background: STATUS_COLOR[p.status] }} />{STATUS_LABEL[p.status]}
                    </span>
                    <span style={{ fontSize: 11, color: "var(--text-tertiary)" }}>· {openCount} open task{openCount !== 1 ? "s" : ""}</span>
                    {p.due_date && <span style={{ fontSize: 11, color: "var(--text-tertiary)", marginLeft: "auto" }}>Due {P.fmtDate(p.due_date)}</span>}
                  </div>

                  {/* Progress */}
                  <div style={{ marginTop: 14 }}>
                    <div style={{ display: "flex", justifyContent: "space-between", fontSize: 11, color: "var(--text-tertiary)", marginBottom: 6 }}>
                      <span>Progress</span><span style={{ color: "var(--gold-400)", fontWeight: 700 }}>{prog}%</span>
                    </div>
                    <div style={{ height: 5, borderRadius: 99, background: "var(--surface-inset)", overflow: "hidden" }}>
                      <div style={{ width: prog + "%", height: "100%", borderRadius: 99, background: "linear-gradient(90deg, var(--gold-600), var(--gold-500))", transition: "width .4s ease" }} />
                    </div>
                  </div>

                  {/* Editors */}
                  {eds.length > 0 && (
                    <div style={{ display: "flex", marginTop: 16 }}>
                      {eds.slice(0, 4).map((e, i) => (
                        <span key={e.id} style={{ marginLeft: i ? -8 : 0 }} title={e.full_name}><window.PUI.Avatar name={e.full_name} size={28} /></span>
                      ))}
                      {eds.length > 4 && <span style={{ marginLeft: 6, fontSize: 12, color: "var(--text-tertiary)", alignSelf: "center" }}>+{eds.length - 4}</span>}
                    </div>
                  )}
                </Card>
              );
            })}
          </div>
        )}

      {isAdmin && modal !== null && (
        <ProjectModal project={modal.id ? modal : null} clients={clients} profiles={profiles}
          projectEditors={projectEditors} profile={profile}
          onClose={() => setModal(null)} onSaved={() => { setModal(null); refresh(); }} />
      )}
    </div>
  );
}

function ProjectModal({ project, clients, profiles, projectEditors, profile, onClose, onSaved }) {
  const { Modal, Field, Input, Select, Btn } = window.PUI;
  const editors = profiles.filter(p => p.role === "editor");
  const [name, setName] = React.useState(project?.name || "");
  const [clientId, setClientId] = React.useState(project?.client_id || "");
  const [status, setStatus] = React.useState(project?.status || "active");
  const [due, setDue] = React.useState(project?.due_date || "");
  const [selEds, setSelEds] = React.useState(project ? projectEditors.filter(pe => pe.project_id === project.id).map(pe => pe.editor_id) : []);
  const [busy, setBusy] = React.useState(false);
  const [newClient, setNewClient] = React.useState("");

  const toggleEd = (id) => setSelEds(s => s.includes(id) ? s.filter(x => x !== id) : [...s, id]);

  const save = async () => {
    if (!name.trim()) return alert("Enter a project name.");
    setBusy(true);
    try {
      let cid = clientId || null;
      if (newClient.trim()) {
        const { data: c } = await sb.from("clients").insert({ name: newClient.trim() }).select().single();
        cid = c.id;
      }
      let pid = project?.id;
      if (project) {
        await sb.from("projects").update({ name, client_id: cid, status, due_date: due || null }).eq("id", project.id);
      } else {
        const { data: p, error } = await sb.from("projects").insert({ name, client_id: cid, status, due_date: due || null, created_by: profile.id }).select().single();
        if (error) throw error;
        pid = p.id;
      }
      // Sync editors
      await sb.from("project_editors").delete().eq("project_id", pid);
      if (selEds.length) await sb.from("project_editors").insert(selEds.map(eid => ({ project_id: pid, editor_id: eid })));
      onSaved();
    } catch (e) { alert("Save failed: " + e.message); }
    setBusy(false);
  };

  const del = async () => {
    if (!confirm("Delete this project and ALL its tasks? This cannot be undone.")) return;
    setBusy(true);
    await sb.from("projects").delete().eq("id", project.id);
    onSaved();
  };

  return (
    <Modal open onClose={onClose}>
      <h3 style={{ fontFamily: "var(--font-display)", fontWeight: 900, fontSize: 22, letterSpacing: "-0.02em", marginBottom: 22 }}>
        {project ? "Edit Project" : "New Project"}
      </h3>
      <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
        <Field label="Project Name" required><Input value={name} onChange={e => setName(e.target.value)} placeholder="e.g. Q3 Content Batch" /></Field>
        <Field label="Client">
          <Select value={clientId} onChange={e => setClientId(e.target.value)}>
            <option value="">— Select client —</option>
            {clients.map(c => <option key={c.id} value={c.id}>{c.name}{c.company ? " · " + c.company : ""}</option>)}
          </Select>
        </Field>
        {!clientId && <Field label="Or create a new client"><Input value={newClient} onChange={e => setNewClient(e.target.value)} placeholder="New client name" /></Field>}
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
          <Field label="Status">
            <Select value={status} onChange={e => setStatus(e.target.value)}>
              <option value="active">Active</option><option value="on_hold">On Hold</option>
              <option value="completed">Completed</option><option value="archived">Archived</option>
            </Select>
          </Field>
          <Field label="Due Date"><Input type="date" value={due} onChange={e => setDue(e.target.value)} /></Field>
        </div>
        <Field label={"Assigned Editors (" + selEds.length + ")"}>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
            {editors.length === 0 && <span style={{ fontSize: 13, color: "var(--text-tertiary)" }}>No editors yet — add them in Users.</span>}
            {editors.map(e => (
              <span key={e.id} onClick={() => toggleEd(e.id)} style={{
                padding: "7px 13px", borderRadius: 99, fontSize: 13, fontWeight: 600, cursor: "pointer",
                border: "1.5px solid " + (selEds.includes(e.id) ? "rgba(251,208,40,0.6)" : "var(--border-default)"),
                background: selEds.includes(e.id) ? "rgba(251,208,40,0.08)" : "transparent",
                color: selEds.includes(e.id) ? "var(--gold-400)" : "var(--text-secondary)",
              }}>{e.full_name || e.email}</span>
            ))}
          </div>
        </Field>
        <div style={{ display: "flex", gap: 10, marginTop: 8 }}>
          <Btn onClick={save} disabled={busy}>{busy ? "Saving…" : project ? "Save Changes" : "Create Project"}</Btn>
          <Btn variant="secondary" onClick={onClose}>Cancel</Btn>
          {project && <Btn variant="danger" onClick={del} style={{ marginLeft: "auto" }}>Delete</Btn>}
        </div>
      </div>
    </Modal>
  );
}
window.Projects = Projects;
