// Roles overview page + roles-specific side panel

const ROLES_SEED = [
  {
    id: "pm", title: "Product Manager", color: "#3b5cf6", avatar: "avatars/product-manager.webp",
    description: "Owns the why and what. Synthesizes user research, market signals, and business goals into a coherent product strategy. Prioritizes the roadmap and defines outcome targets.",
    agents: 4, lastUsed: "2d ago", skills: 7, sources: 4,
  },
  {
    id: "po", title: "Product Owner", color: "#0e7c66", avatar: "avatars/product-owner.webp",
    description: "Owns the backlog. Translates strategy into stories, sequences delivery, and is the day-to-day decision-maker for the development team. Accountable for sprint outcomes.",
    agents: 3, lastUsed: "yesterday", skills: 5, sources: 6,
  },
  {
    id: "ss", title: "Support Specialist", color: "#d97706", avatar: "avatars/support-specialist.webp",
    description: "First line for customer issues. Reproduces problems, triages severity, escalates to engineering, and feeds patterns back to product. Owns ticket-to-resolution time.",
    agents: 6, lastUsed: "today", skills: 9, sources: 3,
  },
  {
    id: "pmm", title: "Product Marketing", color: "#ec4899", avatar: "avatars/product-marketeer.webp",
    description: "Owns positioning, messaging, and go-to-market. Crafts launches, enables sales, and runs the narrative loop between customer feedback and product communication.",
    agents: 2, lastUsed: "1w ago", skills: 4, sources: 5,
  },
  {
    id: "ba", title: "Business Analyst", color: "#8b5cf6", avatar: "avatars/business-analyst.webp",
    description: "Bridges business and engineering. Documents domain logic, models processes, and produces the specs that translate strategy into implementable requirements.",
    agents: 3, lastUsed: "4d ago", skills: 6, sources: 8,
  },
];

function RolesPage({ onOpenRole }) {
  const [roles, setRoles] = useState(ROLES_SEED);
  const [openMenu, setOpenMenu] = useState(null);
  const [query, setQuery] = useState("");

  const filtered = roles.filter(r => r.title.toLowerCase().includes(query.toLowerCase()) || r.description.toLowerCase().includes(query.toLowerCase()));

  const onMenuAction = (role, action) => {
    setOpenMenu(null);
    if (action === "delete") setRoles(rs => rs.filter(r => r.id !== role.id));
    if (action === "edit") onOpenRole?.(role.id);
  };

  const createRole = () => {
    const id = `r${Date.now()}`;
    setRoles(rs => [...rs, { id, title: "New agent", color: "#0e0e10", description: "Describe what this agent is responsible for.", agents: 0, lastUsed: "just now", skills: 0, sources: 0 }]);
  };

  return (
    <div className="flex-1 min-w-0 flex flex-col bg-white">
      {/* Page header */}
      <div className="border-b border-[#e8e3d8] bg-white">
        <div className="max-w-[1180px] mx-auto px-8 pt-8 pb-5">
          <div className="flex items-start gap-4">
            <div className="flex-1">
              <div className="text-[11px] font-semibold tracking-[0.08em] text-[#9aa0a6] uppercase mb-1.5">Workspace</div>
              <h1 className="text-[28px] font-medium tracking-tight text-[#0e0e10] leading-tight">Agent Team</h1>
              <p className="text-[13.5px] text-[#5a5a5a] mt-1.5 max-w-[640px] leading-relaxed">
                Your team of agents. Each agent owns a job — it bundles the skills, sources, and entities needed to do that job, and the assistant adapts to it.
              </p>
            </div>
            <button onClick={createRole}
              className="flex items-center gap-1.5 px-3.5 py-2 rounded-md bg-[var(--accent)] text-white text-[13px] font-medium hover:brightness-110 shadow-[0_1px_0_rgba(0,0,0,0.08)]">
              <Icon name="sparkles" size={15} /> Create agent
            </button>
          </div>
        </div>
      </div>

      {/* Roles grid */}
      <div className="flex-1 overflow-y-auto">
        <div className="max-w-[1180px] mx-auto px-8 py-8">
          <div className="grid grid-cols-[repeat(auto-fill,minmax(280px,1fr))] gap-4">
            {filtered.map(role => (
              <RoleCard key={role.id} role={role}
                menuOpen={openMenu === role.id}
                setMenuOpen={(v) => setOpenMenu(v ? role.id : null)}
                onAction={(a) => onMenuAction(role, a)}
                onOpen={() => onOpenRole?.(role.id)} />
            ))}
            <CreateRoleCard onClick={createRole} />
          </div>
        </div>
      </div>
    </div>
  );
}

function RoleCard({ role, menuOpen, setMenuOpen, onAction, onOpen }) {
  return (
    <div onClick={onOpen}
      className="group relative rounded-xl border border-[#ece7da] bg-white p-5 hover:border-[var(--accent)]/40 hover:shadow-[0_4px_18px_rgba(0,0,0,0.04)] transition-all cursor-pointer flex flex-col">
      <div className="flex items-start gap-5">
        <RoleAvatar role={role} size={88} />
        <div className="flex-1 min-w-0">
          <div className="text-[14.5px] font-semibold text-[#0e0e10] truncate">{role.title}</div>
          <div className="text-[11.5px] text-[#9aa0a6] mt-0.5 flex items-center gap-1.5">
            <span className="w-1.5 h-1.5 rounded-full bg-[#1f8a5b]" />
            <span>Active</span>
            <span className="text-[#cbcbcb]">·</span>
            <span>{role.lastUsed}</span>
          </div>
        </div>
        <div className="relative" onClick={e => e.stopPropagation()}>
          <button onClick={() => setMenuOpen(!menuOpen)}
            className="p-1.5 rounded-md text-[#6b6b6b] hover:bg-black/[0.06] hover:text-[#0e0e10]"
            title="More actions">
            <Icon name="more-v" size={15} />
          </button>
          {menuOpen && <RoleMenu onAction={onAction} onClose={() => setMenuOpen(false)} />}
        </div>
      </div>
      <p className="text-[12.5px] text-[#3a3a3a] leading-relaxed mt-3 line-clamp-4">{role.description}</p>
    </div>
  );
}

function CreateRoleCard({ onClick }) {
  return (
    <button onClick={onClick}
      className="rounded-xl border border-dashed border-[#d4cdba] bg-[#faf8f3] hover:bg-white hover:border-[var(--accent)] hover:text-[var(--accent)] text-[#6b6b6b] p-4 flex flex-col items-center justify-center min-h-[200px] transition-colors">
      <div className="w-11 h-11 rounded-full bg-white border border-[#ece7da] flex items-center justify-center mb-2">
        <Icon name="plus" size={20} />
      </div>
      <div className="text-[13.5px] font-medium">Create new agent</div>
      <div className="text-[11.5px] text-[#9aa0a6] mt-0.5">Add a specialized agent to your team</div>
    </button>
  );
}

function RoleAvatar({ role, size = 44 }) {
  if (role.avatar) {
    return (
      <img src={window.__res ? window.__res(role.avatar) : role.avatar} alt={role.title}
        className="rounded-full object-cover shrink-0 bg-white ring-[3px] ring-white shadow-[0_0_0_5px_var(--accent),0_4px_14px_rgba(31,61,246,0.18)]"
        style={{ width: size, height: size }} />
    );
  }
  const initials = role.title.split(/\s+/).slice(0, 2).map(w => w[0]).join("").toUpperCase();
  return (
    <div className="rounded-full flex items-center justify-center text-white font-semibold shrink-0 ring-[3px] ring-white shadow-[0_0_0_5px_var(--accent),0_4px_14px_rgba(31,61,246,0.18)]"
      style={{ width: size, height: size, background: role.color || "#0e0e10", fontSize: size * 0.36 }}>
      {initials}
    </div>
  );
}

function RoleMenu({ onAction, onClose }) {
  const items = [
    { id: "edit", label: "Edit agent", icon: "edit" },
    { id: "rename", label: "Rename", icon: "edit-line" },
    { id: "avatar", label: "Change avatar", icon: "user" },
    { id: "duplicate", label: "Duplicate", icon: "copy" },
    { id: "delete", label: "Delete", icon: "trash", danger: true },
  ];
  return (
    <>
      <div className="fixed inset-0 z-20" onClick={onClose} />
      <div className="absolute right-0 top-full mt-1 w-[180px] bg-white rounded-lg border border-[#ece7da] shadow-xl z-30 py-1">
        {items.map((it, i) => (
          <React.Fragment key={it.id}>
            {it.danger && <div className="my-1 h-px bg-[#ece7da]" />}
            <button onClick={() => onAction(it.id)}
              className={`w-full flex items-center gap-2.5 px-3 py-1.5 text-[12.5px] text-left hover:bg-black/[0.04] ${it.danger ? "text-[#c2410c] hover:bg-[#fdecea] hover:text-[#a83228]" : "text-[#1a1a1a]"}`}>
              <Icon name={it.icon} size={13} />
              {it.label}
            </button>
          </React.Fragment>
        ))}
      </div>
    </>
  );
}

// ---------- ROLES SIDE PANEL ----------
function RolesSidePanel() {
  const categories = [
    { id: "all", label: "All Agents", icon: "users", count: 5, active: true },
    { id: "product", label: "Product", icon: "story", count: 2 },
    { id: "engineering", label: "Engineering", icon: "code", count: 0 },
    { id: "customer", label: "Customer-facing", icon: "user", count: 2 },
    { id: "ops", label: "Operations", icon: "building", count: 1 },
  ];
  const recents = [
    { id: "pm", title: "Product Manager", color: "#3b5cf6", avatar: "avatars/product-manager.webp" },
    { id: "ss", title: "Support Specialist", color: "#d97706", avatar: "avatars/support-specialist.webp" },
    { id: "po", title: "Product Owner", color: "#0e7c66", avatar: "avatars/product-owner.webp" },
  ];
  return (
    <aside className="w-full h-full bg-[#f4f1ea] flex flex-col border-r border-[#e8e3d8]">
      {/* Logo */}
      <div className="px-4 pt-3 pb-2 flex items-center justify-between">
        <TeklensLogo />
      </div>

      {/* Dashboard */}
      <div className="px-2">
        <button className="w-full flex items-center gap-2.5 px-2.5 py-1.5 rounded-md text-[13.5px] text-[#1f1f1f] hover:bg-black/[0.04]">
          <Icon name="home" size={16} /> Dashboard
        </button>
      </div>

      {/* Section title */}
      <div className="px-4 mt-4 mb-1.5 flex items-center gap-1.5">
        <Icon name="users" size={13} className="text-[#3b5cf6]" />
        <span className="text-[11px] font-semibold tracking-[0.06em] text-[#6b6b6b] uppercase">Agents</span>
      </div>

      {/* New agent */}
      <div className="px-2">
        <button className="w-full flex items-center justify-center gap-2 px-3 py-2 rounded-md text-[13.5px] font-medium text-white bg-[var(--accent)] hover:brightness-110">
          <Icon name="sparkles" size={16} /> Create agent
        </button>
      </div>

      <div className="mx-3 my-3 h-px bg-[#e8e3d8]" />

      <div className="flex-1 min-h-0 overflow-y-auto px-2 pb-2">
        {/* Categories */}
        <div className="px-2 py-1 text-[11px] font-semibold tracking-[0.06em] text-[#6b6b6b] uppercase">Categories</div>
        <div className="flex flex-col">
          {categories.map(c => (
            <button key={c.id}
              className={`flex items-center gap-2 pl-2.5 pr-2 py-1.5 rounded-md text-left text-[12.5px] ${c.active ? "bg-black/[0.06] text-[#0e0e10] font-medium" : "text-[#3a3a3a] hover:bg-black/[0.04]"}`}>
              <Icon name={c.icon} size={13} className={c.active ? "text-[var(--accent)]" : "text-[#9aa0a6]"} />
              <span className="flex-1 truncate">{c.label}</span>
              <span className="text-[10.5px] text-[#9aa0a6] tabular-nums">{c.count}</span>
            </button>
          ))}
        </div>

        {/* Recents */}
        <div className="px-2 py-1 mt-4 text-[11px] font-semibold tracking-[0.06em] text-[#6b6b6b] uppercase">Recently opened</div>
        <div className="flex flex-col">
          {recents.map(r => (
            <button key={r.id}
              className="flex items-center gap-2 pl-2.5 pr-2 py-1.5 rounded-md text-left text-[12.5px] text-[#3a3a3a] hover:bg-black/[0.04]">
              <img src={r.avatar} alt={r.title} className="w-5 h-5 rounded-full object-cover shrink-0 bg-white ring-1 ring-[#d4cdba]" />
              <span className="truncate">{r.title}</span>
            </button>
          ))}
        </div>
      </div>

      {/* Sticky user/settings */}
      <div className="mt-auto border-t border-[#e8e3d8] bg-[#f4f1ea] px-2 py-2 flex items-center gap-2 shrink-0">
        <img src={window.__res ? window.__res("person-simon.webp") : "person-simon.webp"} alt="Simon" className="w-7 h-7 rounded-full object-cover shrink-0" />
        <div className="flex-1 min-w-0">
          <div className="text-[12.5px] font-medium truncate">simon@contem.ch</div>
        </div>
        <button className="p-1.5 rounded hover:bg-black/[0.05] text-[#5a5a5a]"><Icon name="chevron-up-down" size={14} /></button>
      </div>
    </aside>
  );
}
