import {C,screen,rect,text,label,icon,line,card,metric,pill,button,tabs,table,chart,progress,aiNote,codeBlock,rowList,field} from './design-lib.mjs';
const ch='08 / Organisation & account';
export function admin(){
function settings(id,title,chapter,section,{subtitle,fields,guide,notes,tabNames=['General','Access','Integrations'],action='Save changes',target='org-settings'}={}){screen(id,title,chapter,section,()=>{tabs(256,189,1152,tabNames);card(256,255,745,655,title,'Workspace-scoped configuration',()=>{fields.forEach((f,i)=>{field(24+(i%2)*360,87+Math.floor(i/2)*127,336,f[0],f[1],{hint:f[2],select:f[3]||false,secret:f[4]||false});});line(24,555,698);button(24,585,action,{w:220,target,icon:'check'});text(265,596,'Unsaved changes are retained locally.',11,C.muted,400,451);});card(1023,255,385,333,guide?.[0]||'Configuration context',null,()=>{text(22,84,guide?.[1]||'Settings apply to Northstar. Review the scope before saving changes.',15,C.muted,400,339);line(22,229,341);text(22,258,'Changes are recorded in the audit log.',12,C.green,500,339,{target:'audit-log'});});if(notes)aiNote(1023,612,385,notes[0],notes[1],{h:181,target:null});},{subtitle});}
function adminList(id,title,headers,rows,{subtitle,action,target,tabNames=['Overview','Configuration','Activity']}={}){screen(id,title,ch,'Organisation',()=>{tabs(256,188,1152,tabNames);card(256,254,1152,594,title,subtitle,()=>{table(22,90,1108,headers,rows,{rowH:77,targets:rows.map(()=>target)});});text(256,887,'Changes require the corresponding workspace permission and appear in the audit log.',11,C.muted,400,1133);},{subtitle,action:action?{label:action[0],target:action[1]}:undefined});}

settings('org-settings','Organisation settings',ch,'Organisation',{subtitle:'Northstar · Organisation identity and operating defaults.',fields:[['Organisation name','Northstar'],['Default region','Europe',{toString:()=>''},true],['Default environment','Production',null,true],['Time zone','Europe / Stockholm',null,true],['Data retention','90 days',null,true],['Default currency','EUR',null,true]],guide:['One workspace, shared context','Organisation defaults establish the context inherited by teams, applications, clusters, and AI agents.'],notes:['Settings inheritance','Cluster and application overrides remain visible next to the inherited value.']});
adminList('members','Members & invitations',['MEMBER','ROLE','ACCESS','TWO-FACTOR','STATUS'],[['Alex Morgan|alex@northstar.example','Owner','All clusters','Enabled',{text:'Active',kind:'green'}],['Sam Chen|sam@northstar.example','Platform engineer','Production','Enabled',{text:'Active',kind:'green'}],['Riley Brooks|riley@northstar.example','Developer','Staging','Enabled',{text:'Active',kind:'green'}],['Taylor Kim|taylor@northstar.example','Viewer','All clusters','Pending',{text:'Invited',kind:'amber'}]],{subtitle:'People, invitations, roles, and authentication posture.',action:['Invite member','member-invite'],target:'roles',tabNames:['Members','Invitations','Roles & access']});
screen('roles','Roles & access',ch,'Organisation',()=>{
tabs(256,188,1152,['Roles','Assignments','Cluster groups']);card(256,254,282,636,'Roles',null,()=>{['Owner','Platform engineer','Developer','Viewer','Incident responder'].forEach((s,i)=>{if(i===1)rect(12,78+i*58,258,48,C.greenSoft,7);text(25,91+i*58,s,13,i===1?C.green:C.muted,i===1?600:400,229);});button(22,558,'Create custom role',{kind:'secondary',w:238,target:'member-invite',icon:'plus'});});
card(561,254,847,636,'Platform engineer','Permissions are explicit; cluster scope is assigned separately.',()=>{table(22,94,802,['CAPABILITY','READ','CHANGE','APPROVE'],[['Infrastructure','✓','✓','✓'],['Applications','✓','✓','✓'],['Security','✓','✓','✓'],['AI plans','✓','✓','✓'],['Billing','✓','—','—'],['Members & roles','—','—','—']],{widths:[366,150,148,138],rowH:64});text(22,550,'Assignments: Platform team · Production cluster group',12,C.muted,400,800);});
},{subtitle:'Least-privilege access that remains understandable.'});
adminList('audit-log','Audit log',['TIME / ACTOR','ACTION','SCOPE','RESOURCE','RESULT'],[['10:18 UTC|Alex Morgan','Approved AI plan','eu-prod-01','AP-204',{text:'Success',kind:'green'}],['10:18 UTC|SRE agent','Updated deployment','commerce','checkout',{text:'Success',kind:'green'}],['10:25 UTC|SRE agent','Verified rollout','commerce','OP-928',{text:'Success',kind:'green'}],['09:41 UTC|CI service token','Pushed image','Organisation','checkout:v2.8.4',{text:'Success',kind:'green'}]],{subtitle:'Actors, permissions, approvals, changes, and outcomes in one durable record.',target:'ai-execution',tabNames:['All events','Human actions','Agent actions','Exports']});
adminList('credentials','Connections & credentials',['CONNECTION','PROVIDER','USED BY','ROTATION','STATUS'],[['hetzner-production','Hetzner','3 clusters','In 22 days',{text:'Connected',kind:'green'}],['aws-production','AWS','4 clusters','In 14 days',{text:'Connected',kind:'green'}],['github-northstar','GitHub App','48 applications','Managed',{text:'Connected',kind:'green'}],['private-registry','OCI registry','12 stacks','Overdue',{text:'Needs review',kind:'amber'}]],{subtitle:'Connection health, usage, and credential lifecycle without exposing secret values.',action:['Add connection','credential-add'],target:'credential-detail',tabNames:['All connections','Cloud providers','Source control','Registries','SSH']});
settings('credential-add','Add a connection',ch,'Organisation',{subtitle:'Connect a provider with the scope needed for your workflow.',fields:[['Provider','Hetzner Cloud',null,true],['Connection name','hetzner-production'],['API token','secret', 'Stored securely · never shown in AI context',false,true],['Environment scope','Production',null,true],['Owner','Platform team',null,true],['Rotation reminder','Every 90 days',null,true]],guide:['Check the connection first','Validate access and show which resources the credential can reach before saving it.'],notes:['Secret handling','Use dedicated secret inputs. Never paste credentials into AI conversations, logs, or shared configuration.'],action:'Validate & connect',target:'credentials'});
settings('credential-detail','Connection / hetzner-production',ch,'Organisation',{subtitle:'Access scope, capacity, rotation, and the resources that rely on this connection.',fields:[['Connection name','hetzner-production'],['Provider','Hetzner Cloud'],['Credential value','secret','Last rotated 68 days ago',false,true],['Used by','3 clusters · 24 nodes'],['Capacity region','Helsinki',null,true],['Rotation due','29 September 2026']],guide:['Impact before rotation','Every cluster and operation using this credential is listed under Used by. Validate replacement access before switching.'],tabNames:['Overview','Capacity','Used by','Rotation','Activity'],notes:['GitHub connections','Repository reach, installation state, webhooks, and identity verification use this same connection-detail pattern.']});
adminList('tokens','Service & personal tokens',['TOKEN','OWNER','SCOPES','LAST USED','EXPIRES'],[['ci-delivery|Service token','Platform','mcp:read, mcp:write','2 min ago','30 Sep 2026'],['editor-readonly|Personal token','Alex Morgan','mcp:read','1 hour ago','7 Oct 2026'],['monitoring-export|Service token','Platform','metrics.read','5 min ago','30 Sep 2026']],{subtitle:'Choose scopes, expiration, and ownership before issuing access.',action:['Create token','token-create'],target:'token-create',tabNames:['Service tokens','Personal tokens','Editor setup']});
screen('billing','Plan & usage',ch,'Organisation',()=>{
tabs(256,188,1152,['Overview','Plan','Usage analytics','Invoices']);card(256,254,745,199,'Northstar workspace','Platform subscription',()=>{text(22,91,'Team plan',29,C.ink,600,359);text(22,143,'Current billing period · 1–30 September 2026',12,C.muted,400,697);button(524,96,'Manage plan',{kind:'secondary',w:198,target:'billing-plan'});});card(1023,254,385,199,'Current estimate','Illustrative billing data',()=>{text(22,83,'€640.00',37,C.ink,600,337);text(22,148,'Excludes cloud provider infrastructure cost',11,C.muted,400,336);});
card(256,476,745,382,'Platform usage','Billed capacity and usage over time',()=>{chart(22,93,700,196,{seed:3});text(22,322,'48 worker vCPU · separate from provider-priced compute',12,C.muted,400,699);});card(1023,476,385,382,'Billing details',null,()=>{rowList(22,84,337,[{title:'Billing contact',detail:'finance@northstar.example',icon:'user'},{title:'Invoice history',detail:'Monthly invoices and receipts',icon:'file'},{title:'Cloud cost',detail:'Tracked separately under Cost',icon:'chart'}]);button(22,310,'View invoices',{kind:'secondary',w:338,target:'invoices'});});
},{subtitle:'Platform billing stays separate from infrastructure spend.'});
adminList('invoices','Invoices',['INVOICE','PERIOD','AMOUNT','ISSUED','STATE'],[['INV-2026-008','August 2026','€640.00','1 Sep 2026',{text:'Paid',kind:'green'}],['INV-2026-007','July 2026','€620.00','1 Aug 2026',{text:'Paid',kind:'green'}],['INV-2026-006','June 2026','€610.00','1 Jul 2026',{text:'Paid',kind:'green'}]],{subtitle:'Download receipts and inspect line items. Amounts are illustrative.',target:'billing',tabNames:['All invoices','Paid','Outstanding']});
adminList('dns','Domains & DNS',['HOSTNAME','TYPE','TARGET','TLS','STATUS'],[['api.northstar.example','CNAME','checkout ingress','Valid',{text:'Active',kind:'green'}],['shop.northstar.example','CNAME','storefront ingress','Valid',{text:'Active',kind:'green'}],['*.preview.example','Wildcard','preview gateway','Valid',{text:'Active',kind:'green'}]],{subtitle:'DNS records, Cloudflare connections, certificate status, and routing.',action:['Add record','dns-edit'],target:'dns-edit',tabNames:['DNS records','Cloudflare','Certificates','Preview domains']});
adminList('backups','Backups & recovery',['POLICY','TARGET','SCHEDULE','LAST BACKUP','STATUS'],[['Commerce database','PostgreSQL / commerce','Daily · 02:00 UTC','Today · 02:04',{text:'Verified',kind:'green'}],['Cluster configuration','All production','Daily · 03:00 UTC','Today · 03:02',{text:'Verified',kind:'green'}],['Analytics data','analytics / data','Every 6 hours','Today · 06:03',{text:'Verified',kind:'green'}]],{subtitle:'Retention, backup destination, restore points, and a reviewable recovery workflow.',action:['Create policy','backup-policy'],target:'backup-restore',tabNames:['Policies','Restore points','Restore history','Storage targets']});
adminList('variables','Variables & secret bindings',['KEY','SCOPE','VALUE','INHERITANCE','STATE'],[['REGION','Organisation','eu-central','Inherited by 12 clusters',{text:'Active',kind:'green'}],['LOG_LEVEL','Staging','debug','Overrides organisation',{text:'Active',kind:'green'}],['DATABASE_URL','commerce','Secret reference','Bound at deployment',{text:'Bound',kind:'green'}]],{subtitle:'Make inherited values and secret references explicit.',action:['Add variable','variable-edit'],target:'variable-edit',tabNames:['Organisation','Cluster overrides','Secret bindings']});
settings('ai-autonomy','AI boundaries','03 / Intelligence','Intelligence',{subtitle:'Define where agents may read, propose, and execute.',fields:[['Production writes','Always require approval',null,true],['Staging writes','Allow scoped low-risk actions',null,true],['Maximum actions per incident','5'],['Cooldown','30 minutes'],['Default run budget','€10.00'],['Global autonomy','Enabled · production gated',null,true]],guide:['Autonomy is a policy','Human approvals apply to a specific plan and resource revision. Secret access and destructive actions require their own permissions.'],notes:['Pause is always available','Pause new autonomous actions globally, by agent, or by automation. Running operations retain their receipts.'],tabNames:['Autonomy','Capabilities','Models','Usage'],target:'ai-home'});
settings('ai-models','Models & routing','03 / Intelligence','Intelligence',{subtitle:'Model selection, provider connection, fallback behavior, and budgets.',fields:[['Provider connection','Organisation AI gateway',null,true],['Default model','Approved general-purpose model',null,true],['Reasoning tasks','Approved reasoning model',null,true],['Fallback policy','Stop and ask if unavailable',null,true],['Monthly budget','€250.00'],['Data routing','Approved providers only',null,true]],guide:['Choose for the task','Runtime model availability and provider pricing determine available choices. The design does not hard-code model versions or prices.'],notes:['Usage is attributable','Token use and cost are associated with conversations, tasks, agents, and operations.'],tabNames:['Models','Capabilities','Autonomy','Connections'],target:'ai-home'});
settings('ai-capabilities','Capabilities & permissions','03 / Intelligence','Intelligence',{subtitle:'Discover tools and define what an agent can access.',fields:[['Infrastructure reads','Allowed',null,true],['Application writes','Approval required',null,true],['External tool connections','Approved MCP servers',null,true],['Secret handling','Dedicated secret slots',null,true],['Custom skills','Organisation approved',null,true],['Destructive actions','Human approval',null,true]],guide:['Permission-aware by design','A model cannot use a tool beyond the actor’s platform permissions. The UI explains disabled actions and names the required role.'],notes:['Custom tools','Tools declare purpose, input schema, connection state, scope, and execution risk.'],tabNames:['Tools','Skills','Permission policies'],target:'ai-home'});
settings('ai-context','Context & memory','03 / Intelligence','Intelligence',{subtitle:'Connect the knowledge agents need and inspect what they remember.',fields:[['Runbook repository','northstar / runbooks',null,true],['Reference branch','main',null,true],['Cluster context','Production cluster group',null,true],['Memory retention','90 days',null,true],['Memory review','Review suggestions before saving',null,true],['Workspace domain','preview.northstar.example']],guide:['Source-linked knowledge','Each context source has a scope, last sync, and permission boundary. Memory records show provenance and can be edited or removed.'],notes:['Freshness matters','Stale repositories and unavailable sources are identified before the agent uses them.'],tabNames:['Repositories','Memory','Workspaces','Skills'],target:'ai-home'});
screen('ai-usage','AI usage & feedback','03 / Intelligence','Intelligence',()=>{
tabs(256,188,1152,['Usage','By agent','By model','Feedback']);metric(256,254,369,'Monthly spend','€86.20','€250 budget · EUR');metric(647,254,369,'Verified outcomes','142','Last 30 days');metric(1038,254,370,'Reviews requested','28','24 approved · 4 revised');
card(256,405,745,356,'Spend and outcomes','Last 30 days · attributed to recorded runs',()=>{chart(22,93,700,196,{seed:5});});card(1023,405,385,356,'Budget','Organisation limit',()=>{text(22,88,'34%',48,C.green,600,320);progress(22,169,340,.344);text(22,213,'€163.80 remaining this month',14,C.ink,500,337);text(22,254,'At the limit: pause new runs and notify the owner.',13,C.muted,400,337);});aiNote(256,785,1152,'Feedback improves the operating context','Inspect accepted, revised, and rejected suggestions with their reasons. Feedback is linked to the outcome it describes.',{h:131,target:null});
},{subtitle:'Budgets and quality are visible at the same level as activity.'});
settings('integrations','Integrations & notification routes',ch,'Organisation',{subtitle:'Connect communication, monitoring, and external tools.',fields:[['Slack workspace','Northstar',null,true],['Default channel','#platform-operations',null,true],['Microsoft Teams','Not connected',null,true],['Webhook destination','Incident webhook',null,true],['Routing rule','Critical production → on-call',null,true],['Retry policy','3 attempts with backoff',null,true]],guide:['Know what gets sent','Destinations show payload previews, permissions, last delivery, and test results. Notification routes match severity and scope.'],notes:['Ingest credentials','Inbound integrations use separately scoped credentials. Incoming data is treated as context, not trusted instructions.'],tabNames:['Connections','Destinations','Routes','Ingest credentials'],target:'org-settings'});
settings('cluster-settings','Cluster settings','05 / Infrastructure','Infrastructure',{subtitle:'eu-prod-01 · Configuration, access, GitOps, integration health, and node lifecycle.',fields:[['Cluster display name','eu-prod-01'],['Environment','Production',null,true],['GitOps repository','northstar / infrastructure',null,true],['Reconciliation branch','main',null,true],['Metrics source','Prometheus / connected',null,true],['Access group','Platform engineering',null,true]],guide:['Scope is always visible','Cluster settings override organisation defaults only where supported. Kubernetes sync, agent connection, and provider capacity remain observable.'],notes:['Reconciliation','Configuration drift leads to a reviewed diff. Migration and ArgoCD decommissioning use the operation and rollback patterns.'],tabNames:['General','GitOps','Connections','Access','Audit','Advanced'],target:'cluster-overview'});
settings('app-settings','Application settings','04 / Applications & delivery','Applications',{subtitle:'checkout · Build, environment, networking, ownership, and lifecycle.',fields:[['Repository','northstar / checkout'],['Production branch','main',null,true],['Build context','./'],['Health check','/healthz'],['Owner','Commerce team',null,true],['Domain','checkout.northstar.example']],guide:['Delivery stays connected','Settings include environment variables, deployment strategy, source-control webhooks, image publishing, and access.'],notes:['Lifecycle actions','Stopping or deleting an application explains running resources, retained data, and recovery options.'],tabNames:['General','Build & deploy','Environment','Domains','Access'],target:'app-overview'});
settings('preview-config','Preview environment profile','04 / Applications & delivery','Applications',{subtitle:'Define reusable previews, demo inputs, secret bindings, and expiry.',fields:[['Profile','commerce-preview',null,true],['Target cluster','eu-staging-01',null,true],['Namespace pattern','pr-{number}-checkout'],['Expiry','48 hours',null,true],['Teardown on merge','Enabled',null,true],['Database secret','Bound secret reference',null,true]],guide:['Make previews repeatable','A published profile defines resources and dependency order. Required secret inputs are collected securely for each environment.'],notes:['Expiry is visible','Every preview shows an expiration time, owner, estimated cost, and teardown policy.'],tabNames:['Configuration','Inputs','Variables','Secrets'],target:'app-previews'});
settings('profile','Your account',ch,'Organisation',{subtitle:'Your identity, sign-in methods, notifications, and appearance.',fields:[['Display name','Alex Morgan'],['Email','alex@northstar.example'],['GitHub identity','alex-northstar'],['Time zone','Europe / Stockholm',null,true],['Theme','System',null,true],['Density','Comfortable',null,true]],guide:['Personal preferences','Appearance and notification preferences follow you across organisations. Organisation permissions remain separately managed.'],notes:['Authentication','Passkeys, two-factor enrollment, recovery codes, and personal API tokens remain available from account settings.'],tabNames:['General','Authentication','Appearance','Notifications','API tokens'],target:'overview'});
settings('authentication','Authentication & recovery',ch,'Organisation',{subtitle:'Sign-in methods, passkeys, two-factor protection, and recovery.',fields:[['Primary sign-in','GitHub'],['Passkey','MacBook · added 4 Sep'],['Two-factor authentication','Enabled'],['Authenticator app','Configured'],['Recovery codes','8 remaining · hidden'],['Active session','This device · Stockholm']],guide:['Protect account recovery','New factors are verified before activation. Recovery codes are revealed once in a dedicated secure view.'],notes:['High-impact changes','Removing the final recovery method or resetting another member’s factor requires a clearly explained confirmation.'],tabNames:['Sign-in methods','Two-factor','Passkeys','Sessions'],target:'profile'});
adminList('support','Support',['REQUEST','CATEGORY','PRIORITY','UPDATED','STATUS'],[['Cluster bootstrap question','Technical','Normal','2 hours ago',{text:'In progress',kind:'blue'}],['Invoice details','Billing','Normal','Yesterday',{text:'Resolved',kind:'green'}],['Feature request: custom report','Product','Low','3 days ago',{text:'Open',kind:'neutral'}]],{subtitle:'Support requests stay attached to their technical context.',action:['New request','support-create'],target:'support-detail',tabNames:['Open','Resolved','All requests']});
settings('support-create','New support request',ch,'Organisation',{subtitle:'Share the problem and review the context before sending.',fields:[['Category','Technical',null,true],['Affected cluster','eu-prod-01',null,true],['Severity','Normal',null,true],['Subject','Help with cluster networking'],['Description','Describe symptoms and what you tried'],['Attachments','Add screenshots or redacted logs']],guide:['Review before sending','Ankra can help summarize the incident. Inspect the summary and any attached cluster details before submitting the request.'],notes:['Private data','Secret values and authentication credentials are excluded from automatically attached context.'],action:'Review request',target:'support-detail'});

const extra=[
['member-invite','Invite a member',[['Email','teammate@northstar.example'],['Role','Developer',null,true],['Cluster access','Staging group',null,true],['Invite expiry','7 days',null,true]],'members'],
['token-create','Create an access token',[['Token name','ci-deployment'],['Type','Service token',null,true],['Scopes','mcp:read + mcp:write',null,true],['Expiration','30 days',null,true]],'tokens'],
['dns-edit','Configure DNS record',[['Hostname','api.northstar.example'],['Record type','CNAME',null,true],['Target','checkout ingress',null,true],['TTL','Automatic',null,true]],'dns'],
['variable-edit','Configure variable',[['Key','LOG_LEVEL'],['Value','info'],['Scope','Organisation',null,true],['Type','Plain value',null,true]],'variables'],
['backup-policy','Backup policy',[['Target','PostgreSQL / commerce',null,true],['Schedule','Daily · 02:00 UTC'],['Retention','30 days'],['Storage destination','Encrypted object storage',null,true]],'backups'],
['encryption','Encryption & secret storage',[['SOPS key','Organisation managed'],['Secret storage','Encrypted at rest'],['Rotation policy','Every 90 days',null,true],['Key access','Security administrators',null,true]],'org-settings'],
['pipelines','Pipeline infrastructure',[['Build cluster','eu-staging-01',null,true],['Namespace','ankra-ci'],['Image registry','registry.northstar.example'],['Concurrent builds','4']], 'org-settings'],
['cost-settings','Cost settings',[['Currency','EUR',null,true],['Private-cloud compute rate','Custom hourly rate card'],['Allocation method','Requested resources',null,true],['Unpriced resources','Show as unpriced',null,true]],'cost'],
['policy-detail','Risk decision',[['Finding scope','ADV-2026-0011 / legacy-api'],['Decision','Accept temporarily',null,true],['Owner','Security team',null,true],['Expires','14 September 2026'],['Rationale','Upgrade is scheduled for maintenance'],['Review trigger','Fix availability or expiry',null,true]],'security-policies'],
['alert-create','Create alert',[['Name','Checkout latency above SLO'],['Resource scope','eu-prod-01 / checkout',null,true],['Condition','p95 > 500 ms for 5 minutes'],['Severity','High',null,true],['Destination','Platform on-call',null,true],['Automation','Incident triage',null,true]],'alerts'],
];
for(const [id,title,fields,target] of extra)settings(id,title,ch,'Organisation',{subtitle:'Review scope, ownership, and impact before saving.',fields,guide:['Specific, reviewable changes','The form preserves existing create and edit workflows. Required fields, validation, and permissions are visible before submission.'],target});
}
