// ---------- Projects list — card + table toggle ----------

const ProjectsPage = ({ onOpenProject, onOpenMobileMenu }) => {
  const [view, setView] = React.useState("card");
  const [filter, setFilter] = React.useState("all");
  const [clientFilter, setClientFilter] = React.useState("all");
  const [sort, setSort] = React.useState("updated");

  const SORT_OPTIONS = [
    { id: "updated", label: "Recently updated" },
    { id: "due-asc", label: "Due soonest" },
    { id: "due-desc", label: "Due latest" },
    { id: "progress", label: "Most progressed" },
    { id: "name", label: "Name A → Z" },
  ];

  const filtered = React.useMemo(() => {
    let list = HD.projects.slice();
    if (filter !== "all") list = list.filter(p => p.status === filter);
    if (clientFilter !== "all") list = list.filter(p => p.clientId === clientFilter);

    const dueRank = (d) => {
      if (d === "—") return 999;
      if (d === "Done") return 998;
      const m = d.match(/(\d+)d/); if (m) return parseInt(m[1]);
      const m2 = d.match(/^(\d+)/); if (m2) return parseInt(m2[1]);
      return 500;
    };

    if (sort === "due-asc") list.sort((a, b) => dueRank(a.dueIn) - dueRank(b.dueIn));
    else if (sort === "due-desc") list.sort((a, b) => dueRank(b.dueIn) - dueRank(a.dueIn));
    else if (sort === "progress") list.sort((a, b) => b.progress - a.progress);
    else if (sort === "name") list.sort((a, b) => a.name.localeCompare(b.name));
    // 'updated' = original order
    return list;
  }, [filter, clientFilter, sort]);

  return (
    <div>
      <Topbar
        eyebrow="WORKSPACE"
        title="Projects"
        onOpenMobileMenu={onOpenMobileMenu}
        actions={
          <Button variant="primary" size="md" icon={<window.Icon.Plus size={13} />} onClick={() => window.dispatchEvent(new CustomEvent("hd-open-new-project"))}>
            New project
          </Button>
        }
      />

      <div style={{ padding: "20px 32px 60px", display: "flex", flexDirection: "column", gap: 16 }}>
        {/* Filter bar */}
        <Card style={{ padding: "12px 16px" }}>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, flexWrap: "wrap" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
              <FilterChip active={filter === "all"} onClick={() => setFilter("all")}>All <span style={{ opacity: 0.5, marginLeft: 4 }}>{HD.projects.length}</span></FilterChip>
              <FilterChip active={filter === "review"} onClick={() => setFilter("review")} tone="harbor">In review</FilterChip>
              <FilterChip active={filter === "revision"} onClick={() => setFilter("revision")} tone="amber">Revision</FilterChip>
              <FilterChip active={filter === "uploading"} onClick={() => setFilter("uploading")} tone="teal">Client upload</FilterChip>
              <FilterChip active={filter === "approved"} onClick={() => setFilter("approved")} tone="green">Approved</FilterChip>
              <FilterChip active={filter === "drafting"} onClick={() => setFilter("drafting")} tone="lavender">Drafting</FilterChip>

              <div style={{ width: 1, height: 18, background: "rgba(255,255,255,0.08)", margin: "0 4px" }} />

              <Dropdown
                label="Client"
                value={clientFilter === "all" ? "All clients" : HD.clients.find(c => c.id === clientFilter)?.name?.split(" /")[0] || "All"}
                options={[{ id: "all", label: "All clients" }, ...HD.clients.map(c => ({ id: c.id, label: c.name }))]}
                onSelect={(id) => setClientFilter(id)}
              />
              <Dropdown
                label="Sort"
                value={SORT_OPTIONS.find(s => s.id === sort)?.label || "Updated"}
                options={SORT_OPTIONS}
                onSelect={(id) => setSort(id)}
              />
            </div>

            <div style={{ display: "flex", alignItems: "center", gap: 4, padding: 3, background: "rgba(255,255,255,0.03)", border: "1px solid rgba(255,255,255,0.05)", borderRadius: 8 }}>
              <ViewToggle active={view === "card"} onClick={() => setView("card")} iconName="Grid" label="Cards" />
              <ViewToggle active={view === "table"} onClick={() => setView("table")} iconName="List" label="Table" />
            </div>
          </div>
        </Card>

        {/* Results */}
        {filtered.length === 0 ? (
          <EmptyState
            iconName="Folder"
            title="No projects match this filter"
            body="Try widening the status filter or clearing client / editor selection."
            action={<Button variant="ghost" size="md" onClick={() => { setFilter("all"); setClientFilter("all"); }}>Clear filters</Button>}
          />
        ) : view === "card" ? (
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 16 }}>
            {filtered.map(p => <ProjectCard key={p.id} project={p} onClick={() => onOpenProject(p.id)} />)}
          </div>
        ) : (
          <ProjectTable projects={filtered} onOpenProject={onOpenProject} />
        )}
      </div>
    </div>
  );
};

const FilterChip = ({ children, active, onClick, tone = "neutral" }) => {
  const t = STATUS_TONES[tone];
  return (
    <button onClick={onClick} style={{
      padding: "6px 12px", borderRadius: 99,
      fontSize: 12, fontWeight: 500, fontFamily: "var(--sans)",
      background: active ? (tone !== "neutral" ? t.bg : "rgba(255,255,255,0.06)") : "transparent",
      border: active ? `1px solid ${tone !== "neutral" ? t.bd : "rgba(255,255,255,0.10)"}` : "1px solid rgba(255,255,255,0.06)",
      color: active ? (tone !== "neutral" ? t.fg : "var(--white)") : "var(--warm-gray)",
      cursor: "pointer", transition: "all 120ms ease",
    }}>{children}</button>
  );
};

const FilterSelect = ({ label, value }) => (
  <button style={{
    display: "inline-flex", alignItems: "center", gap: 6,
    padding: "6px 10px", borderRadius: 8,
    background: "transparent", border: "1px solid rgba(255,255,255,0.06)",
    color: "var(--white)", fontSize: 12, fontFamily: "var(--sans)", cursor: "pointer",
  }}>
    <span style={{ color: "var(--warm-gray)" }}>{label}:</span>
    <span>{value}</span>
    <window.Icon.ChevronD size={11} color="var(--warm-gray)" />
  </button>
);

// Real dropdown — controlled
const Dropdown = ({ label, value, options, onSelect }) => {
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (!open) return;
    const handler = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, [open]);
  return (
    <div ref={ref} style={{ position: "relative" }}>
      <button onClick={() => setOpen(o => !o)} style={{
        display: "inline-flex", alignItems: "center", gap: 6,
        padding: "6px 10px", borderRadius: 8,
        background: open ? "rgba(255,255,255,0.04)" : "transparent",
        border: "1px solid rgba(255,255,255,0.06)",
        color: "var(--white)", fontSize: 12, fontFamily: "var(--sans)", cursor: "pointer",
      }}>
        <span style={{ color: "var(--warm-gray)" }}>{label}:</span>
        <span style={{ maxWidth: 140, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{value}</span>
        <window.Icon.ChevronD size={11} color="var(--warm-gray)" style={{ transform: open ? "rotate(180deg)" : "none", transition: "transform 160ms ease" }} />
      </button>
      {open && (
        <div style={{
          position: "absolute", top: "calc(100% + 6px)", left: 0, zIndex: 20,
          minWidth: 220,
          background: "var(--charcoal)",
          border: "1px solid rgba(255,255,255,0.10)",
          borderRadius: 10,
          boxShadow: "0 20px 40px -16px rgba(0,0,0,0.55)",
          overflow: "hidden", padding: 6,
        }}
          className="hd-fadeUp"
        >
          {options.map(o => (
            <button
              key={o.id}
              onClick={() => { onSelect(o.id); setOpen(false); }}
              style={{
                display: "block", width: "100%", textAlign: "left",
                padding: "8px 10px", borderRadius: 6,
                background: "transparent", border: "none",
                color: "var(--white)", fontSize: 12.5, fontFamily: "var(--sans)", cursor: "pointer",
                transition: "background 120ms ease",
              }}
              onMouseEnter={(e) => (e.currentTarget.style.background = "rgba(255,255,255,0.04)")}
              onMouseLeave={(e) => (e.currentTarget.style.background = "transparent")}
            >{o.label}</button>
          ))}
        </div>
      )}
    </div>
  );
};

const ViewToggle = ({ active, onClick, iconName, label }) => {
  const IconComp = window.Icon[iconName];
  return (
    <button onClick={onClick} style={{
      display: "inline-flex", alignItems: "center", gap: 6,
      padding: "5px 10px", borderRadius: 6,
      background: active ? "rgba(255,255,255,0.06)" : "transparent",
      border: "none", color: active ? "var(--white)" : "var(--warm-gray)",
      fontSize: 12, fontFamily: "var(--sans)", cursor: "pointer",
    }}>
      <IconComp size={12} />{label}
    </button>
  );
};

const ProjectCard = ({ project, onClick }) => {
  const tone = STATUS_TONES[project.accent];
  return (
    <Card hover onClick={onClick} style={{ padding: 0, overflow: "hidden", display: "flex", flexDirection: "column" }}>
      {/* Thumb */}
      <div style={{ aspectRatio: "16/10", position: "relative", overflow: "hidden", borderBottom: "1px solid rgba(255,255,255,0.04)" }}>
        <div style={{
          position: "absolute", inset: 0,
          background: `linear-gradient(135deg, var(--charcoal), ${tone.bg})`,
        }} />
        <svg width="100%" height="100%" viewBox="0 0 320 200" preserveAspectRatio="none" style={{ position: "absolute", inset: 0, opacity: 0.20 }}>
          {Array.from({ length: 14 }).map((_, i) => {
            const y = 14 + i * 14;
            return <path key={i} d={`M -20 ${y} Q 80 ${y - 6} 160 ${y} T 340 ${y}`} stroke="white" fill="none" strokeWidth="0.5" />;
          })}
        </svg>
        <div style={{ position: "absolute", top: 12, left: 12, right: 12, display: "flex", justifyContent: "space-between" }}>
          <StatusBadge status={project.status} size="sm" />
          <span className="mono" style={{
            background: "rgba(0,0,0,0.4)", border: "1px solid rgba(255,255,255,0.12)",
            color: "var(--white)", padding: "2px 6px", borderRadius: 4, fontSize: 10,
          }}>{project.code}</span>
        </div>
        <div style={{
          position: "absolute", bottom: 14, left: 14,
          width: 36, height: 36, borderRadius: 99,
          background: "rgba(0,0,0,0.4)", backdropFilter: "blur(8px)",
          border: "1px solid rgba(255,255,255,0.16)",
          display: "flex", alignItems: "center", justifyContent: "center", color: "var(--white)",
        }}><window.Icon.Play size={14} /></div>
      </div>

      <div style={{ padding: 18 }}>
        <div className="micro" style={{ color: "var(--warm-gray)", marginBottom: 6, fontSize: 9.5 }}>{project.type.toUpperCase()}</div>
        <div style={{ fontSize: 15, fontWeight: 600, color: "var(--white)", lineHeight: 1.35, letterSpacing: "-0.005em" }}>{project.name}</div>
        <div style={{ fontSize: 12, color: "var(--warm-gray)", marginTop: 6 }}>{project.client}</div>

        <div style={{ margin: "16px 0 12px" }}>
          <div style={{ fontSize: 10.5, color: "var(--warm-gray)", marginBottom: 6, display: "flex", justifyContent: "space-between" }}>
            <span>{project.phase}</span>
            <span style={{ color: tone.fg }}>{project.progress}%</span>
          </div>
          <Progress value={project.progress} tone={project.accent} />
        </div>

        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", paddingTop: 12, borderTop: "1px solid rgba(255,255,255,0.04)" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
            <MetaItem iconName="Message" value={project.comments} unread={project.unread} />
            <MetaItem iconName="File" value={project.assets} />
          </div>
          <div style={{ fontSize: 11, color: "var(--warm-gray)" }}>
            <span style={{ color: "var(--white)" }}>{project.due}</span> · {project.dueIn}
          </div>
        </div>
      </div>
    </Card>
  );
};

const MetaItem = ({ iconName, value, unread = 0 }) => {
  const IconComp = window.Icon[iconName];
  return (
    <div style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: 11.5, color: "var(--warm-gray)" }}>
      <IconComp size={12} />
      <span style={{ color: "var(--white)" }}>{value}</span>
      {unread > 0 && <span style={{
        background: "var(--harbor)", color: "white",
        fontSize: 9, padding: "0 5px", borderRadius: 99, fontWeight: 500,
      }}>{unread}</span>}
    </div>
  );
};

const ProjectTable = ({ projects, onOpenProject }) => (
  <Card style={{ padding: 0, overflow: "hidden" }}>
    <div style={{
      display: "grid",
      gridTemplateColumns: "30px minmax(0,2fr) minmax(0,1.4fr) 110px 130px 90px 90px 110px",
      gap: 12, padding: "10px 20px",
      borderBottom: "1px solid rgba(255,255,255,0.05)",
      fontSize: 10.5, color: "var(--warm-gray)", letterSpacing: "0.10em",
      textTransform: "uppercase", fontWeight: 500,
    }}>
      <span></span>
      <span>Project</span>
      <span>Client</span>
      <span>Status</span>
      <span>Progress</span>
      <span>Comments</span>
      <span>Due</span>
      <span style={{ textAlign: "right" }}>Updated</span>
    </div>
    {projects.map(p => {
      const tone = STATUS_TONES[p.accent];
      return (
        <div
          key={p.id}
          onClick={() => onOpenProject(p.id)}
          className="hd-row"
          style={{
            display: "grid",
            gridTemplateColumns: "30px minmax(0,2fr) minmax(0,1.4fr) 110px 130px 90px 90px 110px",
            gap: 12, padding: "14px 20px",
            borderBottom: "1px solid rgba(255,255,255,0.03)",
            cursor: "pointer", alignItems: "center",
            transition: "background 120ms ease",
          }}
        >
          <div style={{ width: 22, height: 22, borderRadius: 6, background: tone.bg, border: `1px solid ${tone.bd}`, color: tone.fg, display: "flex", alignItems: "center", justifyContent: "center" }}>
            <window.Icon.Film size={11} />
          </div>
          <div style={{ minWidth: 0 }}>
            <div style={{ fontSize: 13, fontWeight: 500, color: "var(--white)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{p.name}</div>
            <div className="mono" style={{ fontSize: 10.5, color: "var(--warm-gray)", marginTop: 2 }}>{p.code}</div>
          </div>
          <div style={{ fontSize: 12.5, color: "rgba(250,250,250,0.78)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{p.client}</div>
          <StatusBadge status={p.status} size="sm" />
          <div>
            <div style={{ fontSize: 10.5, color: "var(--warm-gray)", marginBottom: 4 }}>{p.progress}%</div>
            <Progress value={p.progress} tone={p.accent} height={3} />
          </div>
          <div style={{ fontSize: 12.5, color: "var(--white)" }}>
            {p.comments}
            {p.unread > 0 && <span style={{ marginLeft: 4, fontSize: 10, color: "var(--harbor-2)" }}>· {p.unread} new</span>}
          </div>
          <div style={{ fontSize: 12.5, color: "var(--white)" }}>{p.due}</div>
          <div style={{ fontSize: 11.5, color: "var(--warm-gray)", textAlign: "right" }}>{p.updated}</div>
        </div>
      );
    })}
  </Card>
);

window.ProjectsPage = ProjectsPage;
