const { useState: useStateApp, useEffect: useEffectApp } = React;

const DEFAULTS = {
  name:'', category:'', goal:'', langs:['en'],
  pkg:'growth',
  stations:{},
  audioMode:'ai', audioReady:false, audioName:'', audioLen:'0:30', audioSource:'', script:'', voice:'', adLen:'0:30',
  startDate:'', dayparts:['am','pm'],
  payMethod:'card', cardNum:'', cardExp:'', cardCvc:'', cardName:'',
};

function App(){
  const I = window.Icons;
  const T = window.T;
  const [step,setStep] = useStateApp(0);
  // Re-render the whole wizard when the UI language toggles (i18n.js dispatches 'langchange').
  const [, setLangTick] = useStateApp(0);
  useEffectApp(()=>{
    const h = ()=> setLangTick(n=>n+1);
    window.addEventListener('langchange', h);
    return ()=> window.removeEventListener('langchange', h);
  },[]);
  const [data,setData] = useStateApp(()=>{
    try{ const s = JSON.parse(localStorage.getItem('ra360_campaign')||'null'); return s?{...DEFAULTS,...s}:DEFAULTS; }catch(e){ return DEFAULTS; }
  });
  const [launching,setLaunching] = useStateApp(false);

  const set = (patch)=> setData(d=>{ const n={...d,...patch}; try{localStorage.setItem('ra360_campaign',JSON.stringify(n));}catch(e){} return n; });

  useEffectApp(()=>{
    const sc = document.querySelector('.scroll'); if(sc) sc.scrollTo({top:0,behavior:'smooth'});
  },[step]);

  const selStations = Object.values(data.stations).filter(Boolean).length;
  const valid = [
    data.name.trim() && data.category && data.goal && data.langs.length>0,
    !!data.pkg,
    selStations>0,
    data.audioReady,
    data.startDate && data.dayparts.length>0,
    true,
  ];

  // Archive the finished campaign into the history array 'ra360_campaigns' (read by mis-campanas.html).
  // Adds the fields the history needs (id/status/createdAt/total + station&market counts). New = 'review'.
  const archiveCampaign = (d)=>{
    try{
      const sum = window.selectionSummary ? window.selectionSummary(d) : null;
      const pkg = (window.PACKAGES||[]).find(p=>p.id===d.pkg) || null;
      const rec = {
        id: 'c'+Date.now(),
        name: d.name, category: d.category, goal: d.goal, pkg: d.pkg, langs: d.langs,
        status: 'review',                                   // a new campaign starts under review
        createdAt: new Date().toISOString().slice(0,10),    // YYYY-MM-DD
        stations: sum ? sum.stations.length : Object.values(d.stations||{}).filter(Boolean).length,
        markets: sum ? sum.markets.length : 0,
        total: pkg ? pkg.price : null,                      // enterprise price is null -> "Custom"
      };
      const list = JSON.parse(localStorage.getItem('ra360_campaigns')||'[]');
      list.unshift(rec);                                     // newest first
      localStorage.setItem('ra360_campaigns', JSON.stringify(list));
    }catch(e){}
  };

  const next = ()=>{
    if(step===5){
      setLaunching(true);
      // archive BEFORE clearing the draft, then clear (unchanged flow otherwise)
      setTimeout(()=>{ setLaunching(false); setStep(6); try{ archiveCampaign(data); localStorage.removeItem('ra360_campaign'); }catch(e){} },1900);
      return;
    }
    if(valid[step]) setStep(s=>Math.min(6,s+1));
  };
  const back = ()=> setStep(s=>Math.max(0,s-1));

  const reset = ()=>{ setData(DEFAULTS); setStep(0); };

  const stepView = ()=>{
    switch(step){
      case 0: return <window.StepBasics data={data} set={set}/>;
      case 1: return <window.StepPackage data={data} set={set}/>;
      case 2: return <window.StepStations data={data} set={set}/>;
      case 3: return <window.StepAudio data={data} set={set}/>;
      case 4: return <window.StepSchedule data={data} set={set}/>;
      case 5: return <window.StepReview data={data} set={set}/>;
      case 6: return <window.StepConfirm data={data} onDash={reset} onNew={reset}/>;
    }
  };

  return (
    <div className="app">
      <window.Sidebar/>
      <div className="main">
        <window.Topbar/>
        <div className="scroll">
          <div className="wrap">
            {step<6 && <window.Stepper current={step}/>}
            {stepView()}
            {step<6 && (
              <div className="foot">
                {step>0 ? (
                  <button className="btn btn-ghost" onClick={back}><I.arrowL/> {T('camp.back')}</button>
                ) : <span className="tiny" style={{display:'flex',alignItems:'center',gap:7}}><I.lock w={14}/> {T('camp.autosave')}</span>}
                <button className="btn btn-primary btn-lg" disabled={!valid[step]||launching} onClick={next}>
                  {launching ? <><I.refresh w={18} className="spin"/> {T('camp.processing')}</>
                    : step===5 ? <><I.zap w={18}/> {T('camp.launch')}</>
                    : <>{T('camp.continue')} <I.arrowR/></>}
                </button>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App/>);
