/* global React, Icon, Button, Badge, Avatar, Card, StatusDot, BarChart, LineChart, ProgressBar, Logo, DATA, MenuItem,
   AdminTeam, AdminRoles, AdminIPhones, AdminTasks, AdminAnalytics */
// ============================================================
// Admin — shell + sidebar + Overview
// ============================================================
const NAV = [
  { id: "overview", label: "Overview",    icon: "chart" },
  { id: "requests", label: "Demandes",    icon: "user" },
  { id: "pilotage", label: "Pilotage iPhone", icon: "phone" },
  { id: "team",     label: "Team",        icon: "users" },
  { id: "messages", label: "Messages",    icon: "send" },
  { id: "iphones",  label: "iPhones",     icon: "phone" },
  { id: "folders",  label: "Dossiers",    icon: "grid" },
  { id: "tasks",    label: "Tasks / SOP", icon: "clipboard" },
  { id: "analytics",label: "Analytics",   icon: "list" },
  { id: "roles",    label: "Roles",       icon: "shield",  ownerOnly: true },
  { id: "billing",  label: "Facturation", icon: "wallet",  ownerOnly: true },
];

function AdminShell({ user, role = "admin", onLogout, onSwitchRole, theme, setTheme }) {
  const { useState } = React;
  const isOwner = role === "admin";
  const roles = useRoles();
  const msg = useMsg();
  const [page, setPage] = useState("overview");
  const [msgTarget, setMsgTarget] = useState(null);
  const [watchOp, setWatchOp] = useState(null);
  const goMessage = (opId) => { setMsgTarget(opId); setPage("messages"); };
  const onWatch = (opId) => setWatchOp(opId);
  const unreadMsg = msg.totalAdmin();
  // manager : billing visible seulement si le owner lui a coché la permission
  const canSee = (n) => isOwner || !n.ownerOnly || (n.id === "billing" && roles.can("Manager", "billing"));
  const nav = NAV.filter(canSee);
  // nb de comptes en attente (badge de nav)
  const { users: regUsers } = useRegUsers(6000);
  const pendingCount = (regUsers || []).filter(u => u.status === "pending").length;
  const pages = {
    overview: <Overview onGo={setPage} onMessage={goMessage} onWatch={onWatch} isOwner={isOwner} />,
    requests: <AdminRequests me={user} />,
    pilotage: <AdminPilotage user={user} />,
    team: <AdminTeam onMessage={goMessage} onWatch={onWatch} me={user} />,
    messages: <AdminMessages initialOp={msgTarget} onWatch={onWatch} />,
    roles: <AdminRoles />,
    iphones: <AdminIPhones />,
    folders: <AdminFolders />,
    tasks: <AdminTasks />,
    analytics: <AdminAnalytics onWatch={onWatch} onMessage={goMessage} />,
    billing: <AdminBilling />,
  };
  // garde-fou : un manager ne peut atteindre une page owner-only (sauf billing si autorisé)
  const allowed = (id) => { const n = NAV.find(x => x.id === id); return n ? canSee(n) : true; };
  const safePage = allowed(page) ? page : "overview";
  const [collapsed, setCollapsed] = useState(false);
  return (
    <div style={{ display: "grid", gridTemplateColumns: collapsed ? "1fr" : "248px 1fr", minHeight: "100%" }}>
      {/* sidebar */}
      {!collapsed && <aside style={{ position: "sticky", top: 0, height: "100vh", background: "var(--bg-2)", borderRight: "1px solid var(--border)", display: "flex", flexDirection: "column", padding: "18px 14px" }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "6px 8px 14px" }}>
          <Logo />
          <button onClick={() => setCollapsed(true)} title="Replier le menu" style={{ background: "var(--surface-2)", border: "1px solid var(--border)", borderRadius: 8, width: 30, height: 30, display: "grid", placeItems: "center", color: "var(--muted)", flex: "none" }}>
            {React.createElement(Icon.left, { size: 16 })}
          </button>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 7, margin: "0 8px 14px", padding: "7px 10px", borderRadius: 9, background: isOwner ? "var(--accent-soft)" : "var(--cyan-soft)", border: "1px solid " + (isOwner ? "var(--accent-line)" : "rgba(34,211,238,.3)") }}>
          {React.createElement(Icon[isOwner ? "shield" : "eye"], { size: 14, color: isOwner ? "var(--accent)" : "var(--accent-2)" })}
          <span className="mono" style={{ fontSize: 10.5, fontWeight: 700, letterSpacing: ".04em", color: isOwner ? "var(--accent)" : "var(--accent-2)" }}>{isOwner ? "ACCÈS PROPRIÉTAIRE" : "ACCÈS SUPERVISEUR"}</span>
        </div>
        <nav style={{ display: "grid", gap: 3, flex: 1 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 6, padding: "8px 10px 6px" }}>
            <span className="mono" style={{ fontSize: 10, color: "var(--faint)", letterSpacing: ".12em" }}>PILOTAGE</span>
          </div>
          {nav.map(({ id, label, icon }) => (
            <button key={id} onClick={() => setPage(id)} style={navBtn(safePage === id)}>
              {React.createElement(Icon[icon], { size: 18, color: safePage === id ? "var(--accent)" : "var(--muted)" })}
              <span>{label}</span>
              {id === "tasks" && <span className="num" style={{ marginLeft: "auto", fontSize: 10.5, padding: "1px 7px", borderRadius: 99, background: "rgba(245,185,66,.16)", color: "var(--busy)" }}>1</span>}
              {id === "requests" && pendingCount > 0 && <span className="num" style={{ marginLeft: "auto", fontSize: 10.5, padding: "1px 7px", borderRadius: 99, background: "var(--danger)", color: "#fff", fontWeight: 700 }}>{pendingCount}</span>}
              {id === "messages" && unreadMsg > 0 && <span className="num" style={{ marginLeft: "auto", fontSize: 10.5, padding: "1px 7px", borderRadius: 99, background: "var(--accent)", color: "#06281c", fontWeight: 700 }}>{unreadMsg}</span>}
              {safePage === id && <span style={{ position: "absolute", left: 0, top: 8, bottom: 8, width: 3, borderRadius: 99, background: "var(--accent)" }} />}
            </button>
          ))}
        </nav>
        <div style={{ display: "grid", gap: 3, borderTop: "1px solid var(--border)", paddingTop: 12 }}>
          <button onClick={() => setTheme(theme === "dark" ? "light" : "dark")} style={navBtn(false)}>
            {React.createElement(Icon[theme === "dark" ? "sun" : "moon"], { size: 18, color: "var(--muted)" })}
            <span>Thème {theme === "dark" ? "clair" : "sombre"}</span>
          </button>
          <button onClick={onSwitchRole} style={navBtn(false)}>
            {React.createElement(Icon.user, { size: 18, color: "var(--muted)" })}<span>Vue Opérateur</span>
          </button>
          <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "9px 10px", marginTop: 4, borderRadius: 10, background: "var(--surface)" }}>
            <Avatar user={user} size={32} />
            <div style={{ lineHeight: 1.25, flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 12.5, fontWeight: 600, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{user.name}</div>
              <div className="mono" style={{ fontSize: 10, color: "var(--faint)" }}>{user.role}</div>
            </div>
            <button onClick={onLogout} title="Déconnexion" style={{ background: "none", border: "none", color: "var(--faint)", display: "grid", padding: 4 }}>{React.createElement(Icon.logout, { size: 17 })}</button>
          </div>
        </div>
      </aside>}

      {/* contenu */}
      <main style={{ minWidth: 0, overflow: "auto" }}>
        {collapsed && (
          <button onClick={() => setCollapsed(false)} title="Afficher le menu" style={{ position: "sticky", top: 20, marginLeft: 18, marginTop: 6, zIndex: 25, display: "inline-flex", alignItems: "center", gap: 8, background: "var(--surface-2)", border: "1px solid var(--border-2)", borderRadius: 9, padding: "8px 12px", color: "var(--text)", fontSize: 13, fontWeight: 600, boxShadow: "var(--shadow)" }}>
            {React.createElement(Icon.switcher, { size: 16 })} Menu
          </button>
        )}
        <div key={safePage} className="app-fade" style={{ padding: safePage === "pilotage" ? (collapsed ? "52px 12px 30px" : "10px 12px 30px") : (collapsed ? "60px 34px 60px" : "30px 34px 60px"), maxWidth: safePage === "pilotage" ? "none" : 1500, margin: "0 auto" }}>
          {pages[safePage]}
        </div>
      </main>
      {watchOp && <WatchOverlay opId={watchOp} onClose={() => setWatchOp(null)} />}
    </div>
  );
}
function navBtn(active) {
  return {
    position: "relative", display: "flex", alignItems: "center", gap: 12, padding: "10px 12px", width: "100%",
    background: active ? "var(--surface)" : "transparent", border: "1px solid " + (active ? "var(--border)" : "transparent"),
    borderRadius: 10, color: active ? "var(--text)" : "var(--muted)", fontSize: 13.5, fontWeight: 600, textAlign: "left",
  };
}

// ---------- Overview ----------
function Overview({ onGo, onMessage, onWatch, isOwner }) {
  // KPI RÉELS : parc (backend), équipe inscrite, tâches du store
  const farm = useLiveDevices();
  const parc = (farm.online && farm.list) ? farm.list : [];
  const team = DATA.realTeam();
  const opsList = team.filter(o => o.role === "Opérateur");
  useTasks();   // charge/rafraîchit les tâches réelles (cloud)
  const tasks = TaskStore.list();
  const ovDays = useRealDays(14);   // série réelle 14 j (uptime + tâches)
  const tasksDone = tasks.filter(t => t.status === "done").length;
  const k = {
    devicesOnline: parc.filter(d => d.status === "online" || d.status === "busy").length,
    devicesTotal: parc.length,
    operatorsActive: opsList.filter(o => o.status === "active").length,
    operatorsTotal: opsList.length,
    tasksDone, tasksTotal: tasks.length,
    completion: tasks.length ? Math.round((tasksDone / tasks.length) * 100) : 0,
  };
  // supervision : seulement s'il y a un manager (réel si équipe inscrite)
  const manager = team.find(o => o.role === "Manager") || null;
  const managerIsReal = !!(manager && manager.registered);
  // à surveiller : RÉEL — opérateurs sans iPhone assigné ou suspendus (plus de fausses personnes)
  const watch = [];
  opsList.forEach(o => {
    if (o.status !== "active") watch.push({ who: o, why: "compte suspendu", tone: "red" });
    else if (farm.online && !parc.some(d => d.operator && d.operator.id === o.id)) watch.push({ who: o, why: "aucun iPhone assigné", tone: "amber" });
  });
  return (
    <div style={{ display: "grid", gap: 22 }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", flexWrap: "wrap", gap: 14 }}>
        <div>
          <h1 style={{ margin: 0, fontSize: 24, fontWeight: 700, letterSpacing: "-.01em" }}>Overview</h1>
          <p style={{ margin: "6px 0 0", color: "var(--muted)", fontSize: 13.5 }}>{new Date().toLocaleDateString("fr-FR", { weekday: "long", day: "numeric", month: "long", year: "numeric" })} · {farm.online ? "● parc synchronisé" : "parc non synchronisé"} · {isOwner ? "vue d'ensemble de l'agence" : "supervision de l'équipe opérateurs"}</p>
        </div>
        <div style={{ display: "flex", gap: 10 }}>
          <Button variant="outline" icon="download">Export CSV</Button>
          <Button variant="primary" icon="plus" onClick={() => onGo("team")}>Inviter un membre</Button>
        </div>
      </div>

      {/* KPI */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 16 }} className="kpi-grid">
        <KPI label="Devices en ligne" value={k.devicesOnline} sub={`/ ${k.devicesTotal} total`} icon="phone" tone="green" spark="online" />
        <KPI label="Opérateurs actifs" value={k.operatorsActive} sub={`/ ${k.operatorsTotal} aujourd'hui`} icon="users" tone="cyan" spark="ops" />
        <KPI label="Tâches faites" value={k.tasksDone} sub={`/ ${k.tasksTotal} du jour`} icon="check" tone="green" spark="tasks" />
        <KPI label="Taux de complétion" value={k.completion + "%"} sub="objectif 80%" icon="bolt" tone={k.completion >= 80 ? "green" : "amber"} ring={k.completion} />
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr", gap: 16 }} className="ov-grid">
        {/* graphe usage */}
        <Card pad={20}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 18 }}>
            <div>
              <div style={{ fontSize: 14.5, fontWeight: 700 }}>Activité par jour</div>
              <div className="mono" style={{ fontSize: 11, color: "var(--faint)", marginTop: 3 }}>minutes connectées (parc) + tâches faites · 14 jours · réel</div>
            </div>
            <div style={{ display: "flex", gap: 14, fontSize: 11.5 }}>
              <Legend c="var(--accent)" label="minutes" />
              <Legend c="var(--accent-2)" label="tâches" />
            </div>
          </div>
          <BarChart data={ovDays} keys={["active", "tasksDone"]} colors={["var(--accent)", "var(--accent-2)"]} h={186} />
          <div style={{ display: "flex", justifyContent: "space-between", marginTop: 8 }}>
            {ovDays.filter((_, i) => i % 3 === 0).map((d, i) => <span key={i} className="mono" style={{ fontSize: 9.5, color: "var(--faint)" }}>{d.label}</span>)}
          </div>
        </Card>

        {/* à surveiller */}
        <Card pad={20}>
          <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 16 }}>
            <span style={{ width: 7, height: 7, borderRadius: 99, background: "var(--busy)" }} />
            <div style={{ fontSize: 14.5, fontWeight: 700 }}>À surveiller</div>
          </div>
          <div style={{ display: "grid", gap: 11 }}>
            {watch.length === 0 && <div style={{ color: "var(--faint)", fontSize: 12.5, padding: "16px 0", textAlign: "center" }}>Rien à signaler — tous les opérateurs sont actifs et équipés. ✓</div>}
            {watch.map((w, i) => (
              <div key={i} style={{ display: "flex", alignItems: "center", gap: 11, padding: "10px 12px", borderRadius: 11, background: "var(--surface-2)", border: "1px solid var(--border)" }}>
                <Avatar user={w.who} size={32} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 600 }}>{w.who.name}</div>
                  <div style={{ fontSize: 11.5, color: w.tone === "red" ? "var(--danger)" : "var(--busy)" }}>{w.why}</div>
                </div>
                <div style={{ display: "flex", gap: 7 }}>
                  <button onClick={() => onWatch && onWatch(w.who.id)} title="Voir son écran" style={{ display: "grid", placeItems: "center", width: 32, height: 32, borderRadius: 9, background: "var(--cyan-soft)", color: "var(--accent-2)", border: "1px solid rgba(34,211,238,.3)" }}>{React.createElement(Icon.eye, { size: 15 })}</button>
                  <button onClick={() => onMessage && onMessage(w.who.id)} title="Message in-app" style={{ display: "grid", placeItems: "center", width: 32, height: 32, borderRadius: 9, background: "var(--accent-soft)", color: "var(--accent)", border: "1px solid var(--accent-line)" }}>{React.createElement(Icon.send, { size: 15 })}</button>
                  <WhatsAppBtn user={w.who} variant="icon" />
                  <TelegramBtn user={w.who} variant="icon" />
                </div>
              </div>
            ))}
          </div>
        </Card>
      </div>

      {/* Supervision du manager — OWNER UNIQUEMENT (masquée s'il n'y a pas de manager) */}
      {isOwner && manager && (
        <Card pad={20}>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", flexWrap: "wrap", gap: 12, marginBottom: 16 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
              {React.createElement(Icon.eye, { size: 17, color: "var(--accent-2)" })}
              <div>
                <div style={{ fontSize: 14.5, fontWeight: 700 }}>Supervision du manager</div>
                <div className="mono" style={{ fontSize: 11, color: "var(--faint)", marginTop: 2 }}>activité récente · visible par vous seul (propriétaire)</div>
              </div>
            </div>
            <div style={{ display: "flex", alignItems: "center", gap: 11, padding: "7px 12px 7px 8px", borderRadius: 99, background: "var(--surface-2)", border: "1px solid var(--border)" }}>
              <Avatar user={manager} size={30} />
              <div style={{ lineHeight: 1.2 }}>
                <div style={{ fontSize: 12.5, fontWeight: 600 }}>{manager.name}</div>
                <div style={{ fontSize: 10.5, color: "var(--accent)", display: "flex", alignItems: "center", gap: 5 }}><StatusDot status="online" pulse /> en ligne</div>
              </div>
              <button onClick={() => onMessage && onMessage(manager.id)} title="Message" style={{ display: "grid", placeItems: "center", width: 30, height: 30, borderRadius: 8, background: "var(--accent-soft)", color: "var(--accent)", border: "1px solid var(--accent-line)" }}>{React.createElement(Icon.send, { size: 14 })}</button>
              <WhatsAppBtn user={manager} variant="icon" />
              <TelegramBtn user={manager} variant="icon" />
            </div>
          </div>
          <div style={{ display: "grid", gap: 0 }}>
            {managerIsReal && <div style={{ color: "var(--faint)", fontSize: 12.5, padding: "12px 4px" }}>Aucune activité enregistrée pour l'instant — le journal se remplira avec les actions réelles du manager.</div>}
            {!managerIsReal && DATA.MANAGER_LOG.map((l, i) => (
              <div key={i} style={{ display: "flex", alignItems: "center", gap: 12, padding: "10px 4px", borderTop: i ? "1px solid var(--border)" : "none" }}>
                <span style={{ width: 6, height: 6, borderRadius: 99, background: "var(--accent-2)", flex: "none" }} />
                <span style={{ fontSize: 13, fontWeight: 600, flex: 1 }}>{l.action}</span>
                <span className="mono" style={{ fontSize: 11, color: "var(--faint)" }}>{l.meta}</span>
                <span className="mono" style={{ fontSize: 11, color: "var(--muted)", minWidth: 110, textAlign: "right" }}>{l.at}</span>
              </div>
            ))}
          </div>
        </Card>
      )}
    </div>
  );
}

function KPI({ label, value, sub, icon, tone, ring }) {
  const c = { green: "var(--accent)", cyan: "var(--accent-2)", amber: "var(--busy)" }[tone];
  return (
    <Card pad={18}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
        <div style={{ width: 38, height: 38, borderRadius: 11, background: "color-mix(in srgb, " + c + " 14%, transparent)", display: "grid", placeItems: "center", color: c }}>
          {React.createElement(Icon[icon], { size: 19 })}
        </div>
        {ring != null
          ? <Ring pct={ring} color={c} />
          : <span className="mono" style={{ fontSize: 11, color: "var(--accent)" }}>▲ +{4 + (label.length % 6)}%</span>}
      </div>
      <div className="num" style={{ fontSize: 30, fontWeight: 700, marginTop: 14, letterSpacing: "-.02em" }}>{value}</div>
      <div style={{ fontSize: 12.5, color: "var(--text)", fontWeight: 600, marginTop: 2 }}>{label}</div>
      <div className="mono" style={{ fontSize: 11, color: "var(--faint)", marginTop: 2 }}>{sub}</div>
    </Card>
  );
}
function Ring({ pct, color }) {
  const r = 16, c = 2 * Math.PI * r;
  return (
    <svg width="42" height="42" viewBox="0 0 42 42">
      <circle cx="21" cy="21" r={r} fill="none" stroke="var(--surface-3)" strokeWidth="4" />
      <circle cx="21" cy="21" r={r} fill="none" stroke={color} strokeWidth="4" strokeLinecap="round"
        strokeDasharray={c} strokeDashoffset={c * (1 - pct / 100)} transform="rotate(-90 21 21)" />
    </svg>
  );
}
function Legend({ c, label }) {
  return <span style={{ display: "inline-flex", alignItems: "center", gap: 6, color: "var(--muted)" }}><span style={{ width: 9, height: 9, borderRadius: 3, background: c }} />{label}</span>;
}

Object.assign(window, { AdminShell, Overview, KPI, Ring, Legend, navBtn });
