// Right-side detail drawers for guilds + commands.

function Drawer({ open, onClose, title, sub, children, width = 520 }) {
  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open, onClose]);

  return (
    <>
      <div className="drawer-scrim" data-open={open} onClick={onClose}/>
      <aside className="drawer" data-open={open} style={{ width }}>
        <header className="drawer-head">
          <div style={{ flex: 1, minWidth: 0 }}>
            <div className="card-title ellipsis">{title}</div>
            {sub && <div className="card-sub ellipsis">{sub}</div>}
          </div>
          <button className="icon-btn" onClick={onClose} title="Close">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round"><path d="m6 6 12 12M18 6 6 18"/></svg>
          </button>
        </header>
        <div className="drawer-body">{children}</div>
      </aside>
    </>
  );
}

function GuildDetail({ guild, onClose }) {
  const conn = useConn();
  if (!guild) return null;
  const channels = [
    { name: 'announcements', type: 'text', topic: 'Server announcements', members: guild.members },
    { name: 'general', type: 'text', topic: 'Main chat', members: guild.members },
    { name: 'shift-control', type: 'text', topic: 'Duty in/out panel', members: guild.members },
    { name: 'bot-log', type: 'text', topic: 'Bot logs', members: 4 },
    { name: 'bot-errors', type: 'text', topic: 'Error notifications', members: 2 },
    { name: 'Office', type: 'voice', topic: '', members: 0 },
    { name: 'Patrol 1', type: 'voice', topic: '', members: 0 },
  ];
  const roles = [
    { name: 'Owner', members: 1, color: '#fbbf24' },
    { name: 'Admin', members: 3, color: '#fb7185' },
    { name: 'Moderator', members: 6, color: '#c8a8ff' },
    { name: 'On Duty', members: 12, color: '#7cffb2' },
    { name: 'Verified', members: Math.floor(guild.members * 0.7), color: '#5eead4' },
    { name: 'Member', members: guild.members, color: '#9aa4b2' },
  ];
  const top = TOP_USERS.slice(0, 5);
  const events = LIVE.logs.filter((l) => l.msg.toLowerCase().includes(guild.name.toLowerCase().split(' ')[0].toLowerCase())).slice(0, 8);
  // sparkline of last 14 days
  const trend = Array.from({ length: 14 }, (_, i) => Math.round(guild.members * (0.85 + (i / 14) * 0.15 + Math.random() * 0.04)));

  return (
    <Drawer
      open={!!guild}
      onClose={onClose}
      title={guild.name}
      sub={`id ${guild.id.padStart(18, '0')} · joined ${guild.joined}`}
      width={560}
    >
      <div className="drawer-section">
        <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 14 }}>
          <div className="guild-avatar" style={{ background: guild.color, width: 56, height: 56, borderRadius: 14, fontSize: 18 }}>{guild.icon}</div>
          <div style={{ flex: 1 }}>
            <div style={{ display: 'flex', gap: 8, marginBottom: 6, flexWrap: 'wrap' }}>
              {guild.premium ? <span className="chip solid">Premium</span> : <span className="chip">Free</span>}
              <span className="chip mono">prefix {guild.prefix}</span>
              <span className="chip mono"><span className="dot" style={{ width: 5, height: 5, boxShadow: 'none' }}/>connected</span>
            </div>
            <div className="muted" style={{ fontSize: 12.5 }}>{guild.members} members · {guild.online} online · {channels.length} channels</div>
          </div>
        </div>

        <div className="grid grid-3" style={{ gap: 10 }}>
          <div className="stat-mini">
            <div className="stat-label">Members</div>
            <div className="stat-value-sm">{guild.members}</div>
            <div className="stat-spark"><Sparkline data={trend}/></div>
          </div>
          <div className="stat-mini">
            <div className="stat-label">Online</div>
            <div className="stat-value-sm" style={{ color: 'var(--accent)' }}>{guild.online}</div>
            <div className="muted" style={{ fontSize: 11 }}>{Math.round(guild.online / guild.members * 100)}% of total</div>
          </div>
          <div className="stat-mini">
            <div className="stat-label">Commands · 7d</div>
            <div className="stat-value-sm">{Math.round(guild.members * 6.2)}</div>
            <div className="muted" style={{ fontSize: 11 }}>{(guild.members * 6.2 / 7).toFixed(0)}/day avg</div>
          </div>
        </div>
      </div>

      <div className="drawer-section">
        <div className="card-title" style={{ marginBottom: 8 }}>Channels <span className="muted" style={{ fontWeight: 400 }}>({channels.length})</span></div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
          {channels.map((c) => (
            <div key={c.name} className="drawer-row">
              <span className="mono" style={{ color: 'var(--text-dim)', width: 14 }}>{c.type === 'voice' ? '🔊' : '#'}</span>
              <span style={{ flex: 1, fontSize: 13 }}>{c.name}</span>
              {c.topic && <span className="muted ellipsis" style={{ fontSize: 11.5, maxWidth: 180 }}>{c.topic}</span>}
            </div>
          ))}
        </div>
      </div>

      <div className="drawer-section">
        <div className="card-title" style={{ marginBottom: 8 }}>Roles</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
          {roles.map((r) => (
            <div key={r.name} className="drawer-row">
              <span style={{ width: 7, height: 7, borderRadius: 999, background: r.color }}/>
              <span style={{ flex: 1, fontSize: 13 }}>{r.name}</span>
              <span className="mono muted" style={{ fontSize: 12 }}>{r.members}</span>
            </div>
          ))}
        </div>
      </div>

      <div className="drawer-section">
        <div className="card-title" style={{ marginBottom: 8 }}>Top users in this guild</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
          {top.map((u) => (
            <div key={u.id} className="drawer-row">
              <div style={{ width: 22, height: 22, borderRadius: 999, background: `hsl(${u.rank * 47} 70% 60%)` }}/>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13 }}>{u.name}</div>
                <div className="muted mono" style={{ fontSize: 10.5 }}>{u.id}</div>
              </div>
              <div className="mono" style={{ fontSize: 12 }}>{u.commands}</div>
            </div>
          ))}
        </div>
      </div>

      <div className="drawer-section" style={{ borderBottom: 0 }}>
        <div className="row" style={{ gap: 8 }}>
          <button className="btn" onClick={() => window.open('https://discord.com/channels/' + guild.id, '_blank')}>Open in Discord</button>
        </div>
      </div>
    </Drawer>
  );
}

function CommandDetail({ cmd, onClose }) {
  const conn = useConn();
  if (!cmd) return null;
  // synth: hourly bars for this command
  const max = cmd.uses;
  const bars = Array.from({ length: 24 }, () => Math.round((Math.random() * 0.7 + 0.1) * (cmd.uses / 24)));
  const recentInvokers = TOP_USERS.slice(0, 5).map((u) => ({ ...u, calls: Math.round(cmd.uses * (Math.random() * 0.18 + 0.04)) }));
  const recentInvocations = Array.from({ length: 8 }, (_, i) => {
    const u = TOP_USERS[i % TOP_USERS.length];
    const g = GUILDS[i % GUILDS.length];
    const ms = 30 + Math.round(Math.random() * 200);
    const mins = i * 3 + Math.floor(Math.random() * 4);
    return { user: u.name, uid: u.id, guild: g.name, ms, ago: `${mins}m ago`, ok: Math.random() > 0.04 };
  });

  return (
    <Drawer
      open={!!cmd}
      onClose={onClose}
      title={<span><span className="mono" style={{ color: cmd.color }}>/{cmd.name}</span></span>}
      sub={cmd.categoryName + ' · ' + cmd.desc}
      width={520}
    >
      <div className="drawer-section">
        <div className="grid grid-3" style={{ gap: 10 }}>
          <div className="stat-mini">
            <div className="stat-label">All-time uses</div>
            <div className="stat-value-sm" style={{ color: cmd.color }}>{cmd.uses.toLocaleString()}</div>
          </div>
          <div className="stat-mini">
            <div className="stat-label">Today</div>
            <div className="stat-value-sm">{Math.round(cmd.uses * 0.05)}</div>
            <div className="muted" style={{ fontSize: 11 }}>≈ {Math.round(cmd.uses * 0.05 / 24)}/h</div>
          </div>
          <div className="stat-mini">
            <div className="stat-label">Avg latency</div>
            <div className="stat-value-sm">{(60 + cmd.name.length * 3) + 'ms'}</div>
            <div className="muted" style={{ fontSize: 11 }}>p99 {(180 + cmd.name.length * 5)}ms</div>
          </div>
        </div>
      </div>

      <div className="drawer-section">
        <div className="card-title" style={{ marginBottom: 8 }}>Hourly volume · last 24h</div>
        <MiniBars data={bars} color={cmd.color} highlightIdx={14}/>
      </div>

      <div className="drawer-section">
        <div className="card-title" style={{ marginBottom: 8 }}>Top invokers</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
          {recentInvokers.map((u) => {
            const m = recentInvokers[0].calls;
            return (
              <div key={u.id} className="drawer-row">
                <div style={{ width: 22, height: 22, borderRadius: 999, background: `hsl(${u.rank * 47} 70% 60%)` }}/>
                <div style={{ flex: 1, fontSize: 13 }}>{u.name}</div>
                <div className="bar-track" style={{ width: 100 }}>
                  <div className="bar-fill" style={{ width: `${(u.calls / m) * 100}%`, background: cmd.color }}/>
                </div>
                <div className="mono" style={{ fontSize: 12, width: 36, textAlign: 'right' }}>{u.calls}</div>
              </div>
            );
          })}
        </div>
      </div>

      <div className="drawer-section">
        <div className="card-title" style={{ marginBottom: 8 }}>Recent invocations</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>
          {recentInvocations.map((r, i) => (
            <div key={i} className="drawer-row" style={{ padding: '8px 0', borderBottom: '1px dashed color-mix(in oklab, var(--border) 60%, transparent)' }}>
              <span className={`dot ${r.ok ? '' : 'danger'}`} style={{ width: 6, height: 6, boxShadow: 'none' }}/>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 12.5 }}>{r.user} <span className="muted">in</span> {r.guild}</div>
                <div className="muted mono" style={{ fontSize: 10.5 }}>{r.uid}</div>
              </div>
              <span className="mono" style={{ fontSize: 11.5, color: r.ms > 150 ? 'var(--warn)' : 'var(--text-muted)' }}>{r.ms}ms</span>
              <span className="muted mono" style={{ fontSize: 11, width: 60, textAlign: 'right' }}>{r.ago}</span>
            </div>
          ))}
        </div>
      </div>

      <div className="drawer-section" style={{ borderBottom: 0 }}>
        <div className="row" style={{ gap: 8 }}>
          <button className="btn" onClick={() => window.open('https://github.com/adminfizz/discord-bot-v1/tree/main/src/commands', '_blank')}>View source</button>
        </div>
      </div>
    </Drawer>
  );
}

// Notification dropdown
function NotificationMenu({ open, onClose }) {
  const [read, setRead] = React.useState(false);
  if (!open) return null;
  const items = [
    { kind: 'error', t: '2m ago', title: '/sheetstyle failed', sub: '403 The caller does not have permission' },
    { kind: 'warn', t: '14m ago', title: 'Latency spike', sub: 'p99 reached 168ms (threshold 150ms)' },
    { kind: 'info', t: '1h ago', title: 'New guild joined', sub: 'บ้าน Tanaka Family · 19 members' },
    { kind: 'info', t: 'Y-1', title: 'Weekly report sent', sub: '5 guilds · 2,184 shift hours' },
    { kind: 'warn', t: 'Y-1', title: 'Cog reload', sub: 'utility cog reloaded after edit' },
  ];
  const colorFor = { error: 'var(--danger)', warn: 'var(--warn)', info: 'var(--info)' };
  return (
    <>
      <div className="dropdown-scrim" onClick={onClose}/>
      <div className="dropdown" style={{ width: 340 }}>
        <div className="dropdown-head">
          <div className="card-title">Notifications</div>
          <button className="btn" style={{ padding: '2px 8px', fontSize: 11 }} disabled={read} onClick={() => setRead(true)}>Mark all read</button>
        </div>
        <div className="dropdown-body">
          {read
            ? <div className="muted" style={{ fontSize: 12, textAlign: 'center', padding: '18px 0' }}>No unread notifications</div>
            : items.map((it, i) => (
            <div key={i} className="notif">
              <span className="dot" style={{ background: colorFor[it.kind], boxShadow: `0 0 0 3px color-mix(in oklab, ${colorFor[it.kind]} 22%, transparent)` }}/>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 12.5, fontWeight: 500 }}>{it.title}</div>
                <div className="muted ellipsis" style={{ fontSize: 11.5 }}>{it.sub}</div>
              </div>
              <span className="muted mono" style={{ fontSize: 10.5 }}>{it.t}</span>
            </div>
          ))}
        </div>
      </div>
    </>
  );
}

Object.assign(window, { Drawer, GuildDetail, CommandDetail, NotificationMenu });
