const ExistingAICostPage=window.AICostPage;
function AgentControlPage(){
  const [editingId,setEditingId]=React.useState(null),[daily,setDaily]=React.useState(false);
  const [data,setData]=React.useState(null),[error,setError]=React.useState(''),[busy,setBusy]=React.useState(false);
  const [name,setName]=React.useState('Financial advisor'),[task,setTask]=React.useState('Review available cash, upcoming bills, and goals. Recommend priorities for my approval.'),[model,setModel]=React.useState('amazon.nova-micro-v1:0'),[budget,setBudget]=React.useState('5');
  const load=()=>window.NGM.api('GET','/assigned-agents').then(setData).catch(e=>setError(e.message));
  React.useEffect(()=>{load();},[]);
  const save=async()=>{setBusy(true);setError('');try{await window.NGM.api('POST','/assigned-agents',{id:editingId||undefined,name,task,model,allowanceCents:Math.round(Number(budget)*100),enabled:true,daily});setEditingId(null);await load();}catch(e){setError(e.message);}finally{setBusy(false);}};
  const edit=a=>{setEditingId(a.id);setName(a.name);setTask(a.task);setModel(a.model);setBudget(String(a.allowance));setDaily(a.daily===true);window.scrollTo({top:0,behavior:'smooth'});};
  const change=async(a)=>{setBusy(true);try{await window.NGM.api('POST','/assigned-agents',{...a,allowanceCents:Math.round(a.allowance*100),enabled:!a.enabled});await load();}catch(e){setError(e.message);}finally{setBusy(false);}};
  const run=async(a)=>{setBusy(true);setError('');try{await window.NGM.api('POST',`/assigned-agents/${a.id}/run`,{});await load();}catch(e){setError(e.message);}finally{setBusy(false);}};
  return <div className="ngm-controls"><h1>Advisors</h1><p>Assign tasks, choose a connected model, and control monthly spend. Agents can read and recommend; financial actions require your approval.</p>
    <div className="card" style={{padding:20,marginBottom:18}}><h2>{editingId?'Edit advisor':'Create an advisor'}</h2>
      <div style={{display:'flex',gap:12,flexWrap:'wrap'}}><label>Name <input value={name} onChange={e=>setName(e.target.value)}/></label><label>Model <select value={model} onChange={e=>setModel(e.target.value)}>{(data?.models||[]).map(m=><option key={m.id} value={m.id} disabled={!m.available}>{m.label}</option>)}</select></label><label>Monthly budget ($) <input type="number" min="0" max="100" value={budget} onChange={e=>setBudget(e.target.value)}/></label></div>
      <label style={{display:'block',marginTop:12}}>Task <textarea value={task} onChange={e=>setTask(e.target.value)} style={{display:'block',width:'100%',minHeight:80}}/></label><button disabled={busy||!data} onClick={save}>Save agent</button>
      <label style={{display:'block',marginTop:12}}><input type="checkbox" checked={daily} onChange={e=>setDaily(e.target.checked)}/> Run daily after the morning bank check</label>{editingId&&<button onClick={()=>{setEditingId(null);setName('Financial advisor');}}>Cancel editing</button>}
      <p>Only verified provider connections can be selected. Daily runs use the same monthly limit as manual analysis.</p><p role="status">{busy?'Working…':error}</p>
    </div>
    {(data?.agents||[]).map(a=><div className="card" style={{padding:18,marginBottom:12}} key={a.id}><h3>{a.name} · {a.enabled?'Enabled':'Paused'}</h3><p>{a.task}</p><p>{a.model} · ${(a.allowance||0).toFixed(2)} monthly limit · {a.daily?'Daily after bank check':'Manual runs'}</p><button disabled={busy||!a.enabled} onClick={()=>run(a)}>Run analysis</button> <button disabled={busy} onClick={()=>edit(a)}>Edit task and model</button> <button disabled={busy} onClick={()=>change(a)}>{a.enabled?'Pause':'Enable'}</button></div>)}
    <h2>Spend by model this month</h2><p>{data?.costBasis}</p><table style={{width:'100%'}}><thead><tr><th>Model</th><th>Runs</th><th>Input tokens</th><th>Output tokens</th><th>Estimated spend</th></tr></thead><tbody>{(data?.byModel||[]).map(m=><tr key={m.model}><td>{m.model}</td><td>{m.calls}</td><td>{m.tokensIn}</td><td>{m.tokensOut}</td><td>${(m.cost||0).toFixed(6)}</td></tr>)}</tbody></table>
    <h2>Recommendations & decision history</h2>{!(data?.runs||[]).length&&<p>No assigned agent has run yet.</p>}{(data?.runs||[]).map(r=><details key={r.id} className="card" style={{padding:16,marginBottom:10}}><summary>{r.agentName} · {new Date(r.createdAt).toLocaleString()} · Needs review</summary><p>{r.model} · {r.tokensIn} input / {r.tokensOut} output tokens · ${(r.cost||0).toFixed(6)}</p><p style={{whiteSpace:'pre-wrap'}}>{r.summary}</p><p>No financial action executed. Evidence: {(r.evidence||[]).join(', ')||'Financial snapshot'}</p></details>)}
    <details style={{marginTop:24}}><summary>Existing workflow cost report</summary><ExistingAICostPage/></details>
  </div>;
}
window.AICostPage=AgentControlPage;
