/* ===== Panex — App root ===== */

const ANALYSIS_KEYS = ["scores","temperature","verdict","patterns","highlights","suggestions","replay"];

function sampleAnalysis(){
  const D = window.CR_DATA;
  const data = {};
  ANALYSIS_KEYS.forEach(k=> data[k]=D[k]);
  return Promise.resolve(data);
}

async function realAnalysis(files){
  const fd = new FormData();
  files.forEach(f=> fd.append("images", f.file, f.name));
  const res = await fetch("/api/analyze", { method:"POST", body: fd });
  const data = await res.json().catch(()=>({}));
  if(!res.ok) throw new Error(data.error || "분석에 실패했어요. 잠시 후 다시 시도해주세요.");
  return data;
}

function App(){
  const [screen, setScreen] = useState("landing"); // landing | upload | analyzing | result
  const [analysis, setAnalysis] = useState(null);
  const [toastMsg, setToastMsg] = useState(null);
  const toastTimer = useRef(null);
  const jobRef = useRef(null);

  function toast(msg){
    setToastMsg(msg);
    clearTimeout(toastTimer.current);
    toastTimer.current = setTimeout(()=>setToastMsg(null), 2200);
  }
  function go(s){ window.scrollTo({top:0}); setScreen(s); }

  function startAnalysis(files){
    const isSample = files[0]?.url === "__sample";
    jobRef.current = isSample ? sampleAnalysis() : realAnalysis(files);
    go("analyzing");
  }
  function handleDone(data){ setAnalysis(data); go("result"); }
  function handleError(msg){ toast(msg); go("upload"); }

  const isApp = screen!=="landing";
  return (
    <div className={isApp?"appstage":""}>
      {screen==="landing"   && <Landing onStart={()=>go("upload")}/>}
      {isApp && (
        <div className="appcol">
          {screen==="upload"    && <Upload onBack={()=>go("landing")} onAnalyze={startAnalysis}/>}
          {screen==="analyzing" && <Analyzing job={jobRef.current} onDone={handleDone} onError={handleError}/>}
          {screen==="result" && analysis && <Result data={analysis} onBack={()=>go("landing")} onRestart={()=>go("upload")} toast={toast}/>}
        </div>
      )}
      {toastMsg && <div className="toast"><Icon name="check" size={16} color="#fff"/>{toastMsg}</div>}
    </div>
  );
}
ReactDOM.createRoot(document.getElementById("root")).render(<App/>);
