// Vyuu admin console — Device detail drawer, Devices v2, Relation graph, Prompt Policy v2
const { Wifi: Wifi3, Battery: Batt3, MapPin: Pin3, Shield: Shield3, ShieldCheck: ShieldChk3,
  HardDrive: HD3, Cpu: Cpu3, Clock: Clk3, Activity: Act3,
  Terminal: Term3, Github: Gh3, Mail: Mail3, Box: Box3, FileText: FT3, Database: DB3,
  AlertTriangle: Alert4, CheckCircle2: Check3, XCircle, Bot: Bot2,
  ArrowUpRight: AUR3, Filter: F3, Download: DL3, MoreHorizontal: MH4,
  UserPlus: UP3, Plus: P3 } = window.LucideReact;

// ─────────────────────────────────────────────────────────────────
// Device detail drawer
// ─────────────────────────────────────────────────────────────────
const DEVICE_DETAIL = {
  'LLP-PRIYA-14': {
    host:'LLP-PRIYA-14', user:'priya.sharma@llp.in', name:'Priya Sharma', role:'Product Manager',
    os:'macOS 14.5 (Sonoma)', hw:'MacBook Pro 14" · M3 Pro · 32 GB',
    agent:'1.3.2', agentHealth:'healthy', lastCheckIn:'2 min ago', enrolled:'Aug 14, 2024',
    network:'LLP-Corp-WiFi · 10.42.8.14', location:'Bangalore office',
    batt:84, wifi:true, diskEnc:true, osPatch:'Current',
    postureScore:92,
    aiApps:[
      { n:'Claude Desktop', v:'0.7.12', events7d:412, risk:'low' },
      { n:'ChatGPT (browser)', v:'web', events7d:188, risk:'medium' },
      { n:'Cursor', v:'0.42.3', events7d:64, risk:'low' },
    ],
    mcps:[
      { n:'filesystem', calls7d:47, blocked:0 },
      { n:'github', calls7d:112, blocked:2 },
    ],
    recent:[
      { t:'10:42:18', kind:'prompt', app:'Claude Desktop', v:'allow', s:'Asked about Q3 product roadmap phrasing' },
      { t:'10:28:04', kind:'mcp', app:'github.create_issue', v:'allow', s:'Repo: llp-pm · "Spec: mobile v2"' },
      { t:'09:51:23', kind:'prompt', app:'ChatGPT', v:'redact', s:'PAN redacted from pasted invoice' },
      { t:'09:04:10', kind:'mcp', app:'filesystem.read_file', v:'allow', s:'/Users/priya/notes/q3.md' },
    ],
  },
};

const DeviceDetail = ({host, onClose}) => {
  if (!host) return null;
  // fall back to Priya's template, swapping hostname/user
  const base = DEVICE_DETAIL['LLP-PRIYA-14'];
  const device = MOCK_DEVICES.find(d => d.host===host);
  const d = device ? { ...base, host:device.host, user:device.user, os:device.os, agent:device.agent, lastCheckIn:device.last } : base;

  return (
    <Drawer open={!!host} onClose={onClose} width={620}>
      <DrawerHeader onClose={onClose} eyebrow="Device · Endpoint detail"
        title={d.host}
        actions={<Button small icon={F3}>Quarantine</Button>}/>

      <div style={{flex:1, overflow:'auto'}}>
        {/* User card */}
        <div style={{padding:'20px 24px', background:theme.panel, borderBottom:`1px solid ${theme.line}`}}>
          <div style={{display:'flex', gap:14, alignItems:'center'}}>
            <div style={{width:48, height:48, borderRadius:999, background:theme.sand, display:'flex', alignItems:'center', justifyContent:'center', fontFamily:theme.serif, fontSize:20, color:theme.ink, fontWeight:500}}>{(d.user||'?').charAt(0).toUpperCase()}</div>
            <div>
              <div style={{fontFamily:theme.serif, fontSize:17, color:theme.ink, fontWeight:500}}>{d.name || d.user}</div>
              <div style={{fontSize:12, color:theme.muted, fontFamily:theme.mono}}>{d.user}</div>
              {d.role && <div style={{fontSize:11.5, color:theme.muted, marginTop:2}}>{d.role}</div>}
            </div>
            <div style={{marginLeft:'auto', textAlign:'right'}}>
              <div style={{fontSize:10.5, color:theme.muted, textTransform:'uppercase', letterSpacing:1.4, fontWeight:600}}>Posture</div>
              <div style={{fontFamily:theme.serif, fontSize:26, color:theme.orangeDeep, fontWeight:500, letterSpacing:-0.5}}>{d.postureScore}<span style={{fontSize:13, color:theme.muted}}> /100</span></div>
            </div>
          </div>
        </div>

        {/* Health strip */}
        <div style={{padding:'18px 24px', borderBottom:`1px solid ${theme.line}`, display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:14}}>
          <Stat label="Agent" value={`v${d.agent}`} tone="orange" icon={Act3}/>
          <Stat label="Last check-in" value={d.lastCheckIn} tone="orange" icon={Clk3}/>
          <Stat label="Disk" value={d.diskEnc?'Encrypted':'—'} tone="orange" icon={ShieldChk3}/>
          <Stat label="OS patch" value={d.osPatch} tone="orange" icon={Check3}/>
        </div>

        {/* Device facts */}
        <Section title="Device">
          <FactRow k="OS" v={d.os}/>
          <FactRow k="Hardware" v={d.hw}/>
          <FactRow k="Network" v={d.network}/>
          <FactRow k="Location" v={d.location}/>
          <FactRow k="Enrolled" v={d.enrolled}/>
        </Section>

        {/* AI apps on this device */}
        <Section title="AI apps observed (7 days)">
          <div style={{display:'grid', gap:8}}>
            {d.aiApps.map(a => (
              <div key={a.n} style={{display:'flex', alignItems:'center', gap:12, padding:'10px 12px', border:`1px solid ${theme.line}`, borderRadius:8, background:theme.panel}}>
                <div style={{width:32, height:32, borderRadius:8, background:theme.orangeSoft, display:'flex', alignItems:'center', justifyContent:'center'}}>
                  <Bot2 size={15} color={theme.orangeDeep}/>
                </div>
                <div style={{flex:1}}>
                  <div style={{fontSize:13, color:theme.ink, fontWeight:500}}>{a.n}</div>
                  <div style={{fontSize:11, color:theme.muted, fontFamily:theme.mono}}>{a.v}</div>
                </div>
                <div style={{fontFamily:theme.mono, fontSize:12.5, color:theme.ink}}>{a.events7d}</div>
                <RiskPill level={a.risk}/>
              </div>
            ))}
          </div>
        </Section>

        {/* MCP usage */}
        <Section title="MCP servers invoked">
          <div style={{display:'grid', gap:8}}>
            {d.mcps.map(m => (
              <div key={m.n} style={{display:'flex', alignItems:'center', gap:12, padding:'10px 12px', border:`1px solid ${theme.line}`, borderRadius:8, background:theme.panel}}>
                <div style={{fontFamily:theme.mono, fontSize:13, color:theme.oceanInk, fontWeight:600, flex:1}}>{m.n}</div>
                <div style={{fontSize:11.5, color:theme.muted}}><strong style={{color:theme.ink, fontFamily:theme.mono}}>{m.calls7d}</strong> calls</div>
                {m.blocked>0 && <Pill tone="terracotta">{m.blocked} blocked</Pill>}
              </div>
            ))}
          </div>
        </Section>

        {/* Recent events */}
        <Section title="Recent activity">
          <div style={{borderLeft:`2px solid ${theme.lineSoft}`, paddingLeft:14, marginLeft:4}}>
            {d.recent.map((e, i) => (
              <div key={i} style={{position:'relative', paddingBottom:14}}>
                <div style={{position:'absolute', left:-21, top:4, width:10, height:10, borderRadius:999,
                  background: e.v==='block'?theme.terracotta:e.v==='redact'?theme.amber:theme.orange,
                  boxShadow:`0 0 0 3px ${theme.bg}`}}/>
                <div style={{display:'flex', gap:10, alignItems:'center', marginBottom:3}}>
                  <span style={{fontFamily:theme.mono, fontSize:11, color:theme.muted}}>{e.t}</span>
                  <Pill tone={e.kind==='mcp'?'ocean':'neutral'}>{e.kind.toUpperCase()}</Pill>
                  <VerdictPill v={e.v}/>
                </div>
                <div style={{fontSize:12.5, color:theme.ink, marginLeft:2}}>{e.s}</div>
                <div style={{fontSize:11, color:theme.muted, marginLeft:2, fontFamily:theme.mono}}>{e.app}</div>
              </div>
            ))}
          </div>
        </Section>
      </div>
    </Drawer>
  );
};

const Section = ({title, children}) => (
  <div style={{padding:'20px 24px', borderBottom:`1px solid ${theme.line}`}}>
    <div style={{fontSize:10.5, color:theme.muted, letterSpacing:2, textTransform:'uppercase', fontWeight:600, marginBottom:12}}>{title}</div>
    {children}
  </div>
);
const FactRow = ({k, v}) => (
  <div style={{display:'grid', gridTemplateColumns:'140px 1fr', gap:12, alignItems:'baseline', padding:'6px 0', fontSize:13}}>
    <span style={{color:theme.muted, fontSize:11.5}}>{k}</span>
    <span style={{color:theme.ink}}>{v}</span>
  </div>
);
const Stat = ({label, value, tone, icon:Icon}) => (
  <div>
    <div style={{display:'flex', alignItems:'center', gap:6, marginBottom:4}}>
      {Icon && <Icon size={12} color={theme[tone==='orange'?'sageDeep':'muted']} strokeWidth={1.8}/>}
      <span style={{fontSize:10, color:theme.muted, letterSpacing:1.4, textTransform:'uppercase', fontWeight:600}}>{label}</span>
    </div>
    <div style={{fontSize:13, color:theme.ink, fontWeight:500}}>{value}</div>
  </div>
);

// ─────────────────────────────────────────────────────────────────
// Devices v2 (clickable)
// ─────────────────────────────────────────────────────────────────
const DevicesV2 = () => {
  const [openHost, setOpenHost] = React.useState(null);
  return (
    <div>
      <SectionTitle eyebrow="Inventory" title="Devices with Vyuu agent"
        actions={<><Button small icon={F3}>Filter</Button><Button small icon={DL3}>CSV</Button></>}/>
      <Card padded={false}>
        <table style={{width:'100%', borderCollapse:'collapse', fontSize:13}}>
          <thead><tr style={{borderBottom:`1px solid ${theme.line}`}}>
            {['','Hostname','User','OS','Agent','Last active','Events (30d)',''].map((h,i)=><th key={i} style={{padding:'12px 16px', textAlign:'left', fontSize:10.5, letterSpacing:1.5, color:theme.muted, fontWeight:600, textTransform:'uppercase', fontFamily:theme.sans}}>{h}</th>)}
          </tr></thead>
          <tbody>
            {MOCK_DEVICES.map(d=>(
              <tr key={d.host} onClick={()=>setOpenHost(d.host)} style={{borderBottom:`1px solid ${theme.lineSoft}`, cursor:'pointer'}}>
                <td style={{padding:'14px 16px'}}><StatDot status={d.status}/></td>
                <td style={{padding:'14px 16px', fontFamily:theme.mono, fontWeight:600, color:theme.ink}}>{d.host}</td>
                <td style={{padding:'14px 16px', color:theme.ink}}>{d.user}</td>
                <td style={{padding:'14px 16px', color:theme.muted}}>{d.os}</td>
                <td style={{padding:'14px 16px', fontFamily:theme.mono, color:theme.muted}}>{d.agent}</td>
                <td style={{padding:'14px 16px', color:theme.muted}}>{d.last}</td>
                <td style={{padding:'14px 16px', fontFamily:theme.mono, color:theme.ink}}>{d.events}</td>
                <td style={{padding:'14px 16px', color:theme.orangeDeep}}><AUR3 size={14}/></td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
      <DeviceDetail host={openHost} onClose={()=>setOpenHost(null)}/>
    </div>
  );
};

// ─────────────────────────────────────────────────────────────────
// Relation graph — users ↔ apps / MCPs / agents (sanctioned vs not)
// ─────────────────────────────────────────────────────────────────
const GRAPH_USERS = [
  {id:'u1', label:'Priya', team:'Product'},
  {id:'u2', label:'Rahul', team:'Eng'},
  {id:'u3', label:'Anita', team:'Eng'},
  {id:'u4', label:'Vikram', team:'Eng'},
  {id:'u5', label:'Sneha', team:'Support'},
  {id:'u6', label:'Deepak', team:'Data'},
  {id:'u7', label:'Meera', team:'Security'},
];
const GRAPH_NODES = [
  {id:'claude', label:'Claude Desktop', kind:'ai', sanctioned:true},
  {id:'chatgpt', label:'ChatGPT', kind:'ai', sanctioned:true},
  {id:'cursor', label:'Cursor', kind:'ai', sanctioned:true},
  {id:'merlin', label:'Merlin AI', kind:'ai', sanctioned:false},
  {id:'notion-ai', label:'Notion AI', kind:'agent', sanctioned:false},
  {id:'glean', label:'Glean', kind:'agent', sanctioned:true},
  {id:'copilot', label:'Copilot Workspace', kind:'agent', sanctioned:true},
  {id:'github', label:'github MCP', kind:'mcp', sanctioned:true},
  {id:'fs', label:'filesystem MCP', kind:'mcp', sanctioned:true},
  {id:'postgres', label:'postgres MCP', kind:'mcp', sanctioned:true},
  {id:'shell', label:'shell-exec MCP', kind:'mcp', sanctioned:false},
];
const GRAPH_EDGES = [
  ['u1','claude',42],['u1','chatgpt',18],['u1','glean',12],
  ['u2','chatgpt',67],['u2','cursor',88],['u2','github',34],['u2','shell',4],
  ['u3','cursor',104],['u3','github',52],['u3','copilot',22],['u3','fs',44],
  ['u4','claude',71],['u4','fs',38],['u4','postgres',12],
  ['u5','chatgpt',22],['u5','merlin',8],['u5','notion-ai',14],
  ['u6','claude',31],['u6','postgres',28],['u6','notion-ai',9],
  ['u7','claude',14],['u7','glean',6],
  // cross-links (agents invoke MCPs)
  ['copilot','github',24],['copilot','fs',12],['glean','fs',6],
];

// Build a layered radial layout: users on the left, targets on the right grouped by kind.
const RelationGraph = () => {
  const [hover, setHover] = React.useState(null); // id of hovered node
  const [filter, setFilter] = React.useState('all'); // all | sanctioned | unsanctioned

  const width = 920, height = 440;
  // Left column: users
  const userX = 80;
  const userYStart = 40, userYStep = (height - 80) / (GRAPH_USERS.length - 1);
  const userPos = {};
  GRAPH_USERS.forEach((u, i) => { userPos[u.id] = { x: userX, y: userYStart + i*userYStep }; });

  // Right side: group by kind (ai, mcp, agent) in 3 columns
  const kinds = ['ai','mcp','agent'];
  const rightX = { ai: 460, mcp: 640, agent: 820 };
  const nodePos = {};
  kinds.forEach(k => {
    const items = GRAPH_NODES.filter(n => n.kind===k);
    const step = (height - 80) / Math.max(items.length - 1, 1);
    items.forEach((n, i) => { nodePos[n.id] = { x: rightX[k], y: 40 + i*step, kind:k, sanctioned:n.sanctioned, label:n.label }; });
  });
  // cross-link (agents → MCPs) — agents are column 3, MCPs column 2, so they'll just flow backward visually but we keep it
  const getPos = (id) => userPos[id] || nodePos[id];

  const colorForKind = (k) => k==='ai'?theme.terracotta:k==='mcp'?theme.ocean:k==='agent'?theme.amber:theme.orange;
  const inkForKind  = (k) => k==='ai'?theme.terracottaInk:k==='mcp'?theme.oceanInk:k==='agent'?theme.amberInk:theme.orangeDeep;
  const softForKind = (k) => k==='ai'?theme.terracottaSoft:k==='mcp'?theme.oceanSoft:k==='agent'?theme.amberSoft:theme.orangeSoft;

  // Filter edges based on sanction
  const edgesShown = GRAPH_EDGES.filter(([a,b,w]) => {
    if (filter==='all') return true;
    const node = nodePos[b] || nodePos[a];
    if (!node) return true;
    return filter==='sanctioned' ? node.sanctioned : !node.sanctioned;
  });

  const isHighlighted = (id) => {
    if (!hover) return false;
    if (hover===id) return true;
    // highlight adjacent
    return GRAPH_EDGES.some(([a,b]) => (a===hover && b===id) || (b===hover && a===id));
  };

  const edgeHighlighted = (a,b) => !hover ? false : (a===hover || b===hover);

  const maxW = Math.max(...GRAPH_EDGES.map(e=>e[2]));

  return (
    <Card>
      <div style={{display:'flex', justifyContent:'space-between', alignItems:'flex-start', marginBottom:10, flexWrap:'wrap', gap:12}}>
        <div>
          <h3 style={{fontFamily:theme.serif, fontSize:18, margin:0, color:theme.ink, fontWeight:500}}>People &amp; AI — who uses what</h3>
          <p style={{fontSize:12, color:theme.muted, margin:'4px 0 0'}}>Users ↔ AI apps, MCP servers, and agents. Thicker edges = more interactions. Dashed circles = unsanctioned.</p>
        </div>
        <div style={{display:'flex', gap:6}}>
          {[['all','All'],['sanctioned','Sanctioned'],['unsanctioned','Unsanctioned']].map(([k,l])=>(
            <button key={k} onClick={()=>setFilter(k)} style={{
              padding:'6px 12px', borderRadius:999, cursor:'pointer',
              border:`1px solid ${filter===k?theme.orangeDeep:theme.line}`,
              background: filter===k?theme.orangeDeep:theme.panel,
              color: filter===k?theme.onPrimary:theme.ink,
              fontSize:11.5, fontWeight:500, fontFamily:theme.sans,
            }}>{l}</button>
          ))}
        </div>
      </div>

      {/* Legend */}
      <div style={{display:'flex', gap:16, marginBottom:12, fontSize:11.5, color:theme.muted, flexWrap:'wrap'}}>
        <LegendDot color={theme.orangeDeep} label="User"/>
        <LegendDot color={theme.terracotta} label="AI app"/>
        <LegendDot color={theme.ocean} label="MCP server"/>
        <LegendDot color={theme.amber} label="Agent"/>
        <span style={{display:'inline-flex', alignItems:'center', gap:6}}>
          <svg width="18" height="12"><circle cx="9" cy="6" r="5" fill="none" stroke={theme.muted} strokeWidth="1.5" strokeDasharray="2 2"/></svg>
          Unsanctioned
        </span>
      </div>

      <svg viewBox={`0 0 ${width} ${height}`} style={{width:'100%', height:'auto', display:'block'}}>
        {/* Column labels */}
        <text x={userX} y={20} fontSize="10" fill={theme.muted} textAnchor="middle" letterSpacing="2" style={{fontFamily:theme.sans, fontWeight:600, textTransform:'uppercase'}}>Users</text>
        <text x={rightX.ai} y={20} fontSize="10" fill={theme.terracottaInk} textAnchor="middle" letterSpacing="2" style={{fontFamily:theme.sans, fontWeight:600, textTransform:'uppercase'}}>AI apps</text>
        <text x={rightX.mcp} y={20} fontSize="10" fill={theme.oceanInk} textAnchor="middle" letterSpacing="2" style={{fontFamily:theme.sans, fontWeight:600, textTransform:'uppercase'}}>MCP servers</text>
        <text x={rightX.agent} y={20} fontSize="10" fill={theme.amberInk} textAnchor="middle" letterSpacing="2" style={{fontFamily:theme.sans, fontWeight:600, textTransform:'uppercase'}}>Agents</text>

        {/* Edges */}
        {edgesShown.map(([a,b,w], i) => {
          const pa = getPos(a), pb = getPos(b); if (!pa || !pb) return null;
          const hl = edgeHighlighted(a,b);
          const dim = hover && !hl;
          const targetNode = nodePos[b];
          const strokeColor = targetNode ? colorForKind(targetNode.kind) : theme.orange;
          // bezier control points
          const cx1 = pa.x + (pb.x - pa.x) * 0.5;
          const cx2 = pa.x + (pb.x - pa.x) * 0.5;
          return (
            <path key={i}
              d={`M ${pa.x} ${pa.y} C ${cx1} ${pa.y}, ${cx2} ${pb.y}, ${pb.x} ${pb.y}`}
              fill="none"
              stroke={strokeColor}
              strokeWidth={1 + (w/maxW)*3.5}
              strokeOpacity={dim ? 0.08 : (hl ? 0.85 : 0.32)}
              strokeDasharray={targetNode && !targetNode.sanctioned ? '3 3' : 'none'}
            />
          );
        })}

        {/* User nodes */}
        {GRAPH_USERS.map(u => {
          const p = userPos[u.id];
          const hl = hover && isHighlighted(u.id);
          const dim = hover && !hl;
          return (
            <g key={u.id} onMouseEnter={()=>setHover(u.id)} onMouseLeave={()=>setHover(null)} style={{cursor:'pointer'}}>
              <circle cx={p.x} cy={p.y} r="13" fill={theme.orangeSoft} stroke={theme.orangeDeep} strokeWidth="1.5" opacity={dim?0.4:1}/>
              <text x={p.x} y={p.y+4} fontSize="10" fill={theme.orangeDeep} textAnchor="middle" style={{fontFamily:theme.serif, fontWeight:600}}>{u.label.charAt(0)}</text>
              <text x={p.x - 22} y={p.y+4} fontSize="11" fill={dim?theme.subtle:theme.ink} textAnchor="end" style={{fontFamily:theme.sans, fontWeight:500}}>{u.label}</text>
              <text x={p.x - 22} y={p.y+15} fontSize="9" fill={theme.muted} textAnchor="end" style={{fontFamily:theme.sans}}>{u.team}</text>
            </g>
          );
        })}

        {/* Target nodes */}
        {GRAPH_NODES.map(n => {
          const p = nodePos[n.id]; if (!p) return null;
          const hl = hover && isHighlighted(n.id);
          const dim = hover && !hl;
          const fill = softForKind(n.kind), stroke = colorForKind(n.kind), ink = inkForKind(n.kind);
          return (
            <g key={n.id} onMouseEnter={()=>setHover(n.id)} onMouseLeave={()=>setHover(null)} style={{cursor:'pointer'}}>
              <circle cx={p.x} cy={p.y} r="11" fill={fill} stroke={stroke} strokeWidth="1.5" strokeDasharray={n.sanctioned?'none':'2 2'} opacity={dim?0.35:1}/>
              {!n.sanctioned && <circle cx={p.x+8} cy={p.y-8} r="3" fill={theme.terracotta} stroke={theme.panel} strokeWidth="1"/>}
              <text x={p.x + 17} y={p.y+4} fontSize="11" fill={dim?theme.subtle:theme.ink} textAnchor="start" style={{fontFamily:theme.sans, fontWeight:500}}>{n.label}</text>
            </g>
          );
        })}
      </svg>

      <div style={{marginTop:10, padding:'10px 12px', background:theme.ivory, border:`1px solid ${theme.line}`, borderRadius:8, fontSize:11.5, color:theme.muted, display:'flex', gap:18, flexWrap:'wrap'}}>
        <span><strong style={{color:theme.ink}}>{GRAPH_USERS.length}</strong> users</span>
        <span><strong style={{color:theme.terracottaInk}}>{GRAPH_NODES.filter(n=>n.kind==='ai').length}</strong> AI apps · <strong style={{color:theme.terracotta}}>{GRAPH_NODES.filter(n=>n.kind==='ai' && !n.sanctioned).length}</strong> unsanctioned</span>
        <span><strong style={{color:theme.oceanInk}}>{GRAPH_NODES.filter(n=>n.kind==='mcp').length}</strong> MCP servers · <strong style={{color:theme.terracotta}}>{GRAPH_NODES.filter(n=>n.kind==='mcp' && !n.sanctioned).length}</strong> unsanctioned</span>
        <span><strong style={{color:theme.amberInk}}>{GRAPH_NODES.filter(n=>n.kind==='agent').length}</strong> agents · <strong style={{color:theme.terracotta}}>{GRAPH_NODES.filter(n=>n.kind==='agent' && !n.sanctioned).length}</strong> unsanctioned</span>
        <span style={{marginLeft:'auto', fontStyle:'italic'}}>Hover a node to trace its connections.</span>
      </div>
    </Card>
  );
};

const LegendDot = ({color, label}) => (
  <span style={{display:'inline-flex', alignItems:'center', gap:6}}>
    <span style={{width:10, height:10, borderRadius:999, background:color, display:'inline-block'}}/>{label}
  </span>
);

// ─────────────────────────────────────────────────────────────────
// Prompt Policy v2 — adds Users/Groups column + Create Rule drawer
// ─────────────────────────────────────────────────────────────────
const PromptPolicyV2 = () => {
  const [rules, setRules] = React.useState([
    { id:1, name:'Block Aadhaar in prompts', pattern:'AADHAAR (12-digit)', action:'block', scope:'All users', apps:'All apps', active:true, hits:127, version:7, lastEdit:'meera.nair@llp.in · 2 days ago' },
    { id:2, name:'Redact PAN in prompts', pattern:'PAN (ABCDE1234F)', action:'redact', scope:'All users', apps:'All apps', active:true, hits:312, version:4, lastEdit:'krishna@llp.in · 1 week ago' },
    { id:3, name:'Block prod credentials', pattern:'password=, api_key=, DATABASE_URL', action:'block', scope:'Engineering', apps:'Cursor, Claude', active:true, hits:48, version:12, lastEdit:'arjun.d@llp.in · today' },
    { id:4, name:'Warn on customer list (>10 rows)', pattern:'email + name + phone', action:'warn', scope:'Support · CS tier 2', apps:'Browser only', active:true, hits:74, version:2, lastEdit:'meera.nair@llp.in · 3 weeks ago' },
    { id:5, name:'Block GSTIN bulk export', pattern:'GSTIN ×5+ in single prompt', action:'block', scope:'Finance & Treasury', apps:'All apps', active:false, hits:0, version:1, lastEdit:'arjun.d@llp.in · drafted today' },
    { id:6, name:'Redact source code from exec accounts', pattern:'SOURCE_CODE > 20 lines', action:'redact', scope:'Leadership (14 users)', apps:'ChatGPT, Claude', active:true, hits:22, version:3, lastEdit:'krishna@llp.in · 4 days ago' },
  ]);
  const [createOpen, setCreateOpen] = React.useState(false);
  const [historyFor, setHistoryFor] = React.useState(null);

  return (
    <div>
      <SectionTitle eyebrow="Prompt Protection · Policy" title="Prompt control"
        actions={<>
          <Button small onClick={()=>setHistoryFor({all:true, name:'Prompt Protection bundle'})}>Bundle history</Button>
          <Button primary icon={P3} onClick={()=>setCreateOpen(true)}>Create rule</Button>
        </>}/>
      <div style={{display:'flex', gap:14, marginBottom:14, padding:'10px 14px', border:`1px solid ${theme.line}`, borderRadius:10, background:theme.panel, fontSize:12, color:theme.muted, alignItems:'center'}}>
        <Pill tone="orange">Bundle v23</Pill>
        <span>Latest revision <strong style={{color:theme.ink, fontFamily:theme.mono}}>v23</strong> · published <strong style={{color:theme.ink}}>today, 10:42</strong> by <strong style={{color:theme.ink, fontFamily:theme.mono}}>krishna@llp.in</strong></span>
        <span style={{marginLeft:'auto', display:'inline-flex', alignItems:'center', gap:6}}><Pill tone="amber">3 unpublished drafts</Pill></span>
      </div>
      <Card padded={false}>
        <table style={{width:'100%', borderCollapse:'collapse', fontSize:13}}>
          <thead><tr style={{borderBottom:`1px solid ${theme.line}`}}>
            {['Active','Name','Version','Pattern','Action','Users / Groups','Apps','Hits (7d)',''].map((h,i)=><th key={i} style={{padding:'12px 16px', textAlign:'left', fontSize:10.5, letterSpacing:1.5, color:theme.muted, fontWeight:600, textTransform:'uppercase', fontFamily:theme.sans}}>{h}</th>)}
          </tr></thead>
          <tbody>
            {rules.map(r=>(
              <tr key={r.id} style={{borderBottom:`1px solid ${theme.lineSoft}`}}>
                <td style={{padding:'14px 16px'}}><Toggle on={r.active} onChange={()=>setRules(rs=>rs.map(x=>x.id===r.id?{...x,active:!x.active}:x))}/></td>
                <td style={{padding:'14px 16px', color:theme.ink, fontWeight:500}}>
                  {r.name}
                  <div style={{fontSize:11, color:theme.muted, marginTop:2, fontWeight:400}}>edited by {r.lastEdit}</div>
                </td>
                <td style={{padding:'14px 16px'}}>
                  <button onClick={()=>setHistoryFor(r)} style={{display:'inline-flex', alignItems:'center', gap:5, padding:'3px 9px', border:`1px solid ${theme.line}`, borderRadius:999, background:theme.panel, color:theme.orangeDeep, fontFamily:theme.mono, fontSize:11.5, fontWeight:600, cursor:'pointer'}}>
                    v{r.version} <Clk3 size={11} strokeWidth={1.8}/>
                  </button>
                </td>
                <td style={{padding:'14px 16px', fontFamily:theme.mono, fontSize:12, color:theme.muted}}>{r.pattern}</td>
                <td style={{padding:'14px 16px'}}>
                  <Pill tone={r.action==='block'?'terracotta':r.action==='redact'?'amber':'ocean'}>{r.action.toUpperCase()}</Pill>
                </td>
                <td style={{padding:'14px 16px', fontSize:12.5}}>
                  <Pill tone={r.scope==='All users'?'neutral':'orange'}>{r.scope}</Pill>
                </td>
                <td style={{padding:'14px 16px', color:theme.muted, fontSize:12}}>{r.apps}</td>
                <td style={{padding:'14px 16px', color:theme.ink, fontFamily:theme.mono}}>{r.hits}</td>
                <td style={{padding:'14px 16px', color:theme.muted, cursor:'pointer'}}><MH4 size={15}/></td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
      <CreateRuleDrawer open={createOpen} onClose={()=>setCreateOpen(false)} kind="prompt"/>
      <PolicyHistoryDrawer rule={historyFor} onClose={()=>setHistoryFor(null)} kind="prompt"/>
    </div>
  );
};

// ─────────────────────────────────────────────────────────────────
// OverviewV2 — Overview + Relation graph embedded
// ─────────────────────────────────────────────────────────────────
const OverviewV2 = () => (
  <div>
    <Overview/>
    <div style={{marginTop:16}}>
      <RelationGraph/>
    </div>
  </div>
);

Object.assign(window, {DeviceDetail, DevicesV2, RelationGraph, PromptPolicyV2, OverviewV2});
