// ----- Root app + pipeline orchestration -----
function App(){
  // Initial pipeline state: stages keyed by id -> "idle" | "active" | "done" | "failed"
  const initialStages = () => Object.fromEntries(PIPELINE_STAGES.map(s=>[s.id,"idle"]));

  const [pipelineState, setPipelineState] = useState({
    stages: initialStages(),
    currentStage: null,
    log: [],
    runId: null,
    status: "idle", // idle | running | done | failed
  });
  const [pdrItems, setPdrItems] = useState(PDR_QUEUE);
  const [toast, setToast] = useState(null);

  const showToast = (text, tone="blue") => {
    setToast({text, tone, id: Date.now()});
    setTimeout(()=>setToast(t => (t && t.text===text ? null : t)), 3200);
  };

  const stamp = () => {
    const d = new Date();
    return d.toTimeString().slice(0,8);
  };

  const [portfolio, setPortfolio] = useState(null);

  // Fetch real portfolio data on load
  useEffect(() => {
    fetch(`${API_BASE_URL}/api/portfolio`)
      .then(res => res.json())
      .then(data => {
        if (!data.error) {
          setPortfolio(data);
          showToast(`Connected to agent wallet: ${data.address.slice(0,6)}...`, "green");
        }
      })
      .catch(() => console.log("Backend offline, using simulation mode."));
  }, []);

  const triggerPipeline = useCallback(async (dryArg = false)=>{
    const isDryRun = typeof dryArg === "boolean" ? dryArg : false;
    if(pipelineState.status==="running") return;
    
    const runId = (isDryRun ? "DRY_" : "run_") + Math.random().toString(36).slice(2,10).toUpperCase();
    
    setPipelineState({
      stages: initialStages(),
      currentStage: null,
      log: [{ts:stamp(), tag:"[orch]", msg:`pipeline ${runId} armed ${isDryRun ? "(SIMULATION)" : ""}`, kind: isDryRun ? "info" : "ok"}],
      runId,
      status: "running",
    });

    showToast(isDryRun ? `Dry-run simulation started` : `Pipeline ${runId} started`, isDryRun ? "amber" : "blue");

    // Connect to REAL backend SSE
    const es = new EventSource(`${API_BASE_URL}/api/run?dry=${isDryRun}`);
    
    es.onmessage = (e) => {
      const ev = JSON.parse(e.data);
      
      setPipelineState(s => {
        const stages = {...s.stages};
        if (ev.stage) {
          if (ev.status === "active") stages[ev.stage] = "active";
          if (ev.status === "done") stages[ev.stage] = "done";
          if (ev.status === "failed") stages[ev.stage] = "failed";
        }

        const newLog = [...s.log];
        if (ev.msg) {
          newLog.push({ ts: stamp(), tag: ev.tag || "[agent]", msg: ev.msg, kind: ev.kind || "info" });
        }

        let newStatus = s.status;
        if (ev.status === "complete") {
          newStatus = "done";
          showToast("Pipeline completed successfully", "green");
          es.close();
        }
        if (ev.status === "halted") {
          newStatus = "failed";
          showToast("Pipeline halted by auditor", "red");
          es.close();
        }

        return {
          ...s,
          stages,
          currentStage: ev.status === "active" ? ev.stage : s.currentStage,
          log: newLog.slice(-60),
          status: newStatus
        };
      });
    };

    es.onerror = () => {
      console.log("SSE Connection lost. Likely local script ended.");
      es.close();
      setPipelineState(s => ({ ...s, status: s.status === "running" ? "failed" : s.status }));
    };

    return () => es.close();
  // eslint-disable-next-line react-hooks/exhaustive-deps
  },[pipelineState.status]);

  const onPdrAction = (pdrId, action) => {
    setPdrItems(items => items.filter(p=>p.pdrId!==pdrId));
    setPipelineState(s=>({...s, log:[...s.log, {ts:stamp(), tag:"[auditor]", msg:`${pdrId} → ${action.toUpperCase()}`, kind: action==="approve"?"ok":"err"}]}));
    showToast(`PDR ${action==="approve"?"approved":"rejected"} · ${pdrId}`, action==="approve"?"green":"red");
  };

  return (
    <>
      <InteractiveBackground/>
      <div style={{position:"relative", zIndex:1}}>
        <Header onTriggerPipeline={triggerPipeline}/>
        <main>
          <Hero onTrigger={triggerPipeline}/>
          <WalletVerification/>
          <PortfolioDashboard data={portfolio}/>
          <PipelineControl
            pipelineState={pipelineState}
            onTriggerRun={triggerPipeline}
            pdrItems={pdrItems}
            onPdrAction={onPdrAction}
          />
          <OperationsConsole/>
          <CtaSection/>
        </main>
        <Footer/>
      </div>
      <Toast toast={toast}/>
    </>
  );
}

function Toast({toast}){
  if(!toast) return null;
  const tones = {
    blue:{bg:"rgba(41,98,239,0.95)", color:"white"},
    green:{bg:"rgba(16,185,129,0.95)", color:"white"},
    red:{bg:"rgba(239,68,68,0.95)", color:"white"},
  };
  const t = tones[toast.tone] || tones.blue;
  return (
    <div className="slide-in" style={{
      position:"fixed", bottom:24, right:24, zIndex:100,
      padding:"12px 18px", borderRadius:14,
      background:t.bg, color:t.color,
      fontSize:14, fontWeight:500,
      boxShadow:"0 18px 48px -16px rgba(0,0,0,0.6)",
      backdropFilter:"blur(8px)",
    }}>{toast.text}</div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App/>);
