/* ============================================================
   SYMPHO — Administration
   Miembros · Permisos · Grupos · Dominio
   ============================================================ */

function AdminView() {
  const nav = useNav();
  const tab = nav.loc.sub || "members";
  const tabs = [
    { id: "members", label: "Miembros", icon: "users" },
    { id: "perms", label: "Permisos", icon: "lock" },
    { id: "groups", label: "Grupos", icon: "flow" },
    { id: "domain", label: "Dominio & plan", icon: "globe" },
  ];
  return (
    <div className="canvas-in wide rise">
      <div className="pagehead">
        <div style={{ width: 44, height: 44, borderRadius: 12, background: "var(--sympho-dim)", color: "var(--sympho)", display: "grid", placeItems: "center", border: "1px solid color-mix(in oklch, var(--sympho) 30%, transparent)" }}><Icon name="shield" size={22} /></div>
        <div style={{ flex: 1 }}>
          <h1 className="disp" style={{ fontSize: 24, fontWeight: 600, letterSpacing: "-0.02em" }}>Administración</h1>
          <p className="muted" style={{ fontSize: 13.5, marginTop: 4 }}>{window.WORKSPACE.name} · {window.WORKSPACE.domain}</p>
        </div>
      </div>

      <div className="seg" style={{ marginBottom: 24 }}>
        {tabs.map(t => (
          <button key={t.id} className="seg-btn" data-on={tab === t.id} onClick={() => nav.go({ view: "admin", sub: t.id })}>
            <Icon name={t.icon} size={15} /> {t.label}
          </button>
        ))}
      </div>

      {tab === "members" && <Members />}
      {tab === "perms" && <Perms />}
      {tab === "groups" && <Groups />}
      {tab === "domain" && <Domain />}
    </div>
  );
}

function Members() {
  const roleHue = { Owner: "var(--sympho)", Admin: "var(--ek)", Finanzas: "var(--muluk)", Miembro: "var(--text-3)", Externo: "var(--text-4)" };
  return (
    <div>
      <Section title="Miembros del dominio" sub="Personas con acceso al workspace. Asigna apps y roles por persona."
        right={<button className="btn btn-primary btn-sm"><Icon name="plus" size={14} /> Invitar miembro</button>}
        style={{ marginBottom: 16 }} />
      <div className="card" style={{ padding: 0, overflow: "hidden" }}>
        <table className="tbl">
          <thead><tr>
            <th>Miembro</th><th>Rol</th><th>Apps con acceso</th><th>Estado</th><th>Última actividad</th><th></th>
          </tr></thead>
          <tbody>
            {window.MEMBERS.map((m, i) => (
              <tr key={i}>
                <td>
                  <div style={{ display: "flex", alignItems: "center", gap: 11 }}>
                    <Avatar name={m.name} initials={m.initials} hue={m.hue} size={32} />
                    <div><div style={{ color: "var(--text)", fontWeight: 500, fontSize: 13 }}>{m.name}</div>
                    <div className="mono" style={{ fontSize: 11, color: "var(--text-4)" }}>{m.email}</div></div>
                  </div>
                </td>
                <td><span className="chip" style={{ height: 24, fontSize: 11, color: roleHue[m.role], borderColor: `color-mix(in oklch, ${roleHue[m.role]} 35%, transparent)` }}>{m.role}</span></td>
                <td>
                  <div style={{ display: "flex", gap: 5 }}>
                    {m.apps.map(aid => { const a = window.APPS.find(x => x.id === aid); return <span key={aid} title={a.name} className="app-pip"><Glyph app={a} size={22} radius={6} /></span>; })}
                  </div>
                </td>
                <td>{m.status === "active" ? <span className="badge ok dot">activo</span> : m.status === "invited" ? <span className="badge warn dot">invitado</span> : <span className="badge dot">externo</span>}</td>
                <td className="mono" style={{ fontSize: 12 }}>{m.last}</td>
                <td style={{ textAlign: "right" }}><button className="ic-btn btn-sm" style={{ width: 30, height: 30 }}><Icon name="more" size={16} /></button></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function Perms() {
  const [matrix, setMatrix] = useState(JSON.parse(JSON.stringify(window.PERM_MATRIX)));
  const toggle = (role, perm) => {
    if (role === "Owner") return;
    setMatrix(m => ({ ...m, [role]: { ...m[role], [perm]: !m[role][perm] } }));
  };
  return (
    <div>
      <Section title="Permisos por rol" sub="Define qué puede hacer cada rol en el workspace. El Owner siempre tiene control total."
        style={{ marginBottom: 16 }} />
      <div className="card" style={{ padding: 0, overflow: "hidden" }}>
        <table className="tbl perm-tbl">
          <thead><tr>
            <th style={{ width: 220 }}>Permiso</th>
            {window.ROLES.map(r => <th key={r} style={{ textAlign: "center" }}>{r}</th>)}
          </tr></thead>
          <tbody>
            {window.PERMS.map(p => (
              <tr key={p.id}>
                <td style={{ color: "var(--text)", fontWeight: 500 }}>{p.label}</td>
                {window.ROLES.map(r => (
                  <td key={r} style={{ textAlign: "center" }}>
                    <button className={"chk" + (matrix[r][p.id] ? " on" : "")} disabled={r === "Owner"} onClick={() => toggle(r, p.id)} title={`${r} · ${p.label}`}>
                      {matrix[r][p.id] ? <Icon name="check" size={14} /> : null}
                    </button>
                  </td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      <p className="muted" style={{ fontSize: 12, marginTop: 12, fontFamily: "var(--mono)" }}>Tip · Los permisos aplican a todas las apps. Restringe acceso por app desde cada miembro.</p>
    </div>
  );
}

function Groups() {
  return (
    <div>
      <Section title="Grupos de trabajo" sub="Colabora entre equipos —internos o externos— con acceso compartido a un subconjunto de apps."
        right={<button className="btn btn-primary btn-sm"><Icon name="plus" size={14} /> Nuevo grupo</button>}
        style={{ marginBottom: 18 }} />
      <div className="grid-2">
        {window.GROUPS.map((g, i) => (
          <div key={i} className="card" style={{ padding: 20 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
              <span className="feed-ic" style={{ "--c": g.hue, width: 38, height: 38 }}><Icon name={g.icon} size={18} /></span>
              <div style={{ flex: 1 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                  <b style={{ fontSize: 15 }}>{g.name}</b>
                  {g.external && <span className="badge dot">externo</span>}
                </div>
                <div className="mono" style={{ fontSize: 11, color: "var(--text-4)", marginTop: 2 }}>{g.members} miembros</div>
              </div>
              <button className="ic-btn btn-sm" style={{ width: 30, height: 30 }}><Icon name="more" size={16} /></button>
            </div>
            <p className="muted" style={{ fontSize: 13, marginTop: 14, lineHeight: 1.5 }}>{g.desc}</p>
            <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 16, paddingTop: 16, borderTop: "1px solid var(--line)" }}>
              <span className="eyebrow">Apps</span>
              <div style={{ display: "flex", gap: 6, flex: 1 }}>
                {g.apps.map(aid => { const a = window.APPS.find(x => x.id === aid); return <span key={aid} className="chip" style={{ height: 24, paddingLeft: 4, fontSize: 11 }}><Glyph app={a} size={16} radius={5} />{a.name}</span>; })}
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function Domain() {
  const W = window.WORKSPACE;
  const rows = [
    { k: "Dominio verificado", v: W.domain, badge: "ok" },
    { k: "Región de datos", v: W.region, badge: null },
    { k: "Plan", v: W.plan, badge: null },
    { k: "SSO", v: "Google + Microsoft", badge: "ok" },
    { k: "Autenticación 2 factores", v: "Obligatoria", badge: "ok" },
  ];
  const onMods = window.MODULES.filter(m => m.on && !m.locked);
  const monthly = onMods.reduce((s, m) => s + m.price, 0);
  return (
    <div className="grid-2" style={{ alignItems: "start" }}>
      <div className="card" style={{ padding: 22 }}>
        <Section title="Dominio & seguridad" style={{ marginBottom: 16 }} />
        {rows.map((r, i) => (
          <div key={i} style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "13px 0", borderTop: i ? "1px solid var(--line)" : "none" }}>
            <span className="muted" style={{ fontSize: 13 }}>{r.k}</span>
            <span style={{ display: "flex", alignItems: "center", gap: 8 }}>
              <span className="mono" style={{ fontSize: 12.5, color: "var(--text)" }}>{r.v}</span>
              {r.badge && <Icon name="check" size={15} style={{ color: "var(--ok)" }} />}
            </span>
          </div>
        ))}
      </div>
      <div className="card" style={{ padding: 22 }}>
        <Section title="Plan & consumo" style={{ marginBottom: 16 }} />
        <div style={{ display: "flex", alignItems: "baseline", gap: 8 }}>
          <span className="disp" style={{ fontSize: 32, fontWeight: 600 }}>{window.fmtMoney(monthly)}</span>
          <span className="muted" style={{ fontSize: 13 }}>/mes · {onMods.length} módulos</span>
        </div>
        <div className="bar" style={{ marginTop: 16 }}><i style={{ width: (W.seats.used / W.seats.total * 100) + "%" }} /></div>
        <div className="muted" style={{ fontSize: 12, marginTop: 8, fontFamily: "var(--mono)" }}>{W.seats.used} de {W.seats.total} asientos · {W.seats.total - W.seats.used} disponibles</div>
        <div style={{ marginTop: 18, display: "flex", flexDirection: "column", gap: 6 }}>
          {onMods.slice(0, 5).map(m => {
            const a = window.APPS.find(x => x.id === m.app);
            return <div key={m.id} style={{ display: "flex", alignItems: "center", gap: 9, fontSize: 12.5 }}>
              <span className="dot" style={{ background: a.hue }} />
              <span style={{ flex: 1, color: "var(--text-2)" }}>{m.name}</span>
              <span className="mono" style={{ color: "var(--text-3)" }}>{window.fmtMoney(m.price)}</span>
            </div>;
          })}
        </div>
        <button className="btn btn-sm" style={{ marginTop: 18, width: "100%", justifyContent: "center" }}><Icon name="download" size={14} /> Descargar factura</button>
      </div>
    </div>
  );
}

Object.assign(window, { AdminView });
