// screens-create.jsx — real Mini App Create hub + project flows
const { useState: _cs_useState, useEffect: _cs_useEffect } = React;

const FS_STEPS = ['source','target','quality','process','result'];
const MF_STEPS = ['target','faces','process','result'];
const IG_STEPS = ['prompt','aspect','process','result'];

function CreateScreen({ ctx }){
  const { t: T, navigate, premium } = ctx;
  return (
    <div className="screen">
      <ScreenHeader title={T('create_title')} subtitle={T('create_subtitle')}
        right={<HelpButton topic="create" lang={ctx.lang}/>}/>

      <div className="col">
        <CreateModeCard
          onClick={()=>navigate('faceswap')}
          icon={<Icon.face size={20}/>} accent="purple"
          title={T('face_swap')} sub={T('face_swap_sub')}
          cost={T('cost_uses_photo') + ' / ' + T('cost_uses_video')}
        />
        <CreateModeCard
          onClick={()=>navigate('multiface')}
          icon={<Icon.multiface size={20}/>} accent="gold"
          title={T('multiface')} sub={T('multiface_sub')}
          cost={T('cost_multiface')}
          locked={premium === 'free'}
        />
        <CreateModeCard
          onClick={()=>navigate('imagegen')}
          icon={<Icon.wand size={20}/>} accent="cyan"
          title={T('image_gen')} sub={T('image_gen_sub')}
          cost={T('cost_uses_photo')}
        />
      </div>
    </div>
  );
}

function CreateModeCard({ icon, title, sub, cost, locked, accent, onClick }){
  return (
    <button onClick={onClick} className="card" style={{
      textAlign:'left', color: 'inherit', cursor:'pointer',
      display:'flex', alignItems:'center', gap: 14, padding: 14,
      border: '1px solid ' + (accent === 'gold' ? 'rgba(246,200,95,0.22)' :
                              accent === 'cyan' ? 'rgba(34,211,238,0.18)' :
                              'rgba(155,92,255,0.18)'),
      background: 'linear-gradient(135deg, ' +
        (accent === 'gold' ? 'rgba(246,200,95,0.08), rgba(12,15,33,0.4)' :
         accent === 'cyan' ? 'rgba(34,211,238,0.07), rgba(12,15,33,0.4)' :
         'rgba(155,92,255,0.07), rgba(12,15,33,0.4)') + ')'
    }}>
      <div style={{
        width: 48, height: 48, borderRadius: 14, flex:'none',
        background: accent === 'gold' ? 'rgba(246,200,95,0.16)' :
                    accent === 'cyan' ? 'rgba(34,211,238,0.16)' :
                    'rgba(155,92,255,0.18)',
        color: accent === 'gold' ? 'var(--gold)' : accent === 'cyan' ? 'var(--cyan)' : 'var(--purple-3)',
        display:'flex',alignItems:'center',justifyContent:'center'
      }}>{icon}</div>
      <div style={{flex:1, minWidth:0}}>
        <div className="row" style={{gap: 8}}>
          <div className="h-card">{title}</div>
          {locked && <span className="chip chip-gold" style={{padding:'2px 7px',fontSize:10}}><Icon.lock size={10}/> Premium</span>}
        </div>
        <div className="dim" style={{marginTop: 2}}>{sub}</div>
        <div className="mute" style={{marginTop: 6, fontSize: 11}}>{cost}</div>
      </div>
      <Icon.chevronRight size={18}/>
    </button>
  );
}

function FilePickerCard({ title, subtitle, accept, file, onFile, icon, disabled }){
  return (
    <label className="dropzone" style={{cursor: disabled ? 'default' : 'pointer', opacity: disabled ? .7 : 1}}>
      <input
        type="file"
        accept={accept}
        disabled={disabled}
        style={{display:'none'}}
        onChange={(event)=>onFile(event.target.files && event.target.files[0] ? event.target.files[0] : null)}
      />
      <div className="ph-art">{icon || <Icon.upload size={26}/>}</div>
      <div style={{fontSize: 13, fontWeight: 600}}>{file ? file.name : title}</div>
      <div className="hint">{file ? formatFileSize(file.size) : subtitle}</div>
    </label>
  );
}

function formatFileSize(bytes){
  if (!bytes && bytes !== 0) return '';
  if (bytes < 1024 * 1024) return Math.max(1, Math.round(bytes / 1024)) + ' KB';
  return (bytes / (1024 * 1024)).toFixed(bytes > 100 * 1024 * 1024 ? 0 : 1) + ' MB';
}

function statusLabel(project){
  const status = project && project.status;
  if (status === 'SUCCESS') return 'Ready';
  if (status === 'FAILED') return 'Failed';
  if (project && project.started_at) return 'Processing';
  return 'Queued';
}

function MiniAppError({ message, onCredits }){
  if (!message) return null;
  const payment = String(message).toLowerCase().includes('credit') || String(message).includes('402');
  return (
    <div className="banner-info miniapp-session-error">
      <Icon.warning size={15}/>
      <span style={{flex:1}}>{message}</span>
      {payment && onCredits && <button className="btn btn-primary btn-sm" onClick={onCredits}>Credits</button>}
    </div>
  );
}

function JobProcessing({ ctx, initialProject, onReady }){
  const [project, setProject] = _cs_useState(initialProject);
  const [error, setError] = _cs_useState(null);

  _cs_useEffect(() => {
    let cancelled = false;
    let timer = null;
    async function poll(){
      if (!project || !project.job_id) return;
      try {
        const data = await window.RavanaMiniApp.getProject(project.job_id);
        if (cancelled) return;
        const next = data.project;
        setProject(next);
        if (next.status === 'SUCCESS') {
          onReady(next);
          return;
        }
        if (next.status === 'FAILED') {
          setError('Processing failed. Try another file.');
          return;
        }
        timer = window.setTimeout(poll, 4000);
      } catch (err) {
        if (!cancelled) setError(err.message || 'Status check failed.');
        timer = window.setTimeout(poll, 6000);
      }
    }
    timer = window.setTimeout(poll, 1200);
    return () => {
      cancelled = true;
      if (timer) window.clearTimeout(timer);
    };
  }, [project && project.job_id]);

  return (
    <div className="col">
      <div className="card" style={{textAlign:'center', padding: 18}}>
        <div className="ph-art pulse-cyan" style={{margin:'4px auto 12px'}}>
          <Icon.sparkles size={28}/>
        </div>
        <div className="h-card">{statusLabel(project)}</div>
        <div className="dim" style={{marginTop: 6}}>
          {project && project.queue_name ? project.queue_name.replaceAll('_', ' ') : 'Waiting for worker'}
        </div>
      </div>
      {project && <CostPanel items={[
        { k: 'Job', v: '#' + project.project_id },
        { k: 'Cost', v: project.cost + ' credits', tone: 'gold' },
        { k: 'Status', v: statusLabel(project), tone: project.status === 'SUCCESS' ? 'gold' : '' },
      ]}/>}
      <MiniAppError message={error}/>
    </div>
  );
}

function ResultView({ ctx, project, title, onAgain }){
  const url = project && project.result_url;
  const isVideoResult = project && String(project.project_type || '').includes('video');
  return (
    <div className="col">
      <div className="card" style={{padding: 10}}>
        {url ? (
          isVideoResult ? (
            <video src={url} controls playsInline style={{width:'100%', borderRadius: 12, display:'block'}}/>
          ) : (
            <img src={url} alt="" style={{width:'100%', borderRadius: 12, display:'block'}}/>
          )
        ) : (
          <div className="placeholder-art" style={{height: 220}}><Icon.checkCircle size={28}/></div>
        )}
      </div>
      <CostPanel items={[
        { k: 'Result', v: title || 'Ready', tone: 'gold' },
        { k: 'Charged', v: (project && project.cost ? project.cost : 0) + ' credits' },
      ]}/>
      <div className="row" style={{gap:8}}>
        {url && <button className="btn btn-primary btn-block" onClick={()=>window.open(url, '_blank')}>
          <Icon.download size={16}/> Open result
        </button>}
        <button className="btn btn-secondary btn-block" onClick={onAgain}>
          <Icon.refresh size={16}/> Again
        </button>
      </div>
    </div>
  );
}

function FaceSwapFlow({ ctx }){
  const { t: T, navigate } = ctx;
  const [step, setStep] = _cs_useState(0);
  const [source, setSource] = _cs_useState(null);
  const [target, setTarget] = _cs_useState(null);
  const [quality, setQuality] = _cs_useState('simple');
  const [project, setProject] = _cs_useState(null);
  const [error, setError] = _cs_useState(null);
  const [busy, setBusy] = _cs_useState(false);

  const submit = async () => {
    if (!source || !target) return;
    setBusy(true); setError(null);
    try {
      const sourceUpload = await window.RavanaMiniApp.uploadFile(source);
      const targetUpload = await window.RavanaMiniApp.uploadFile(target);
      const data = await window.RavanaMiniApp.createFaceSwap({
        source_upload_id: sourceUpload.upload_id,
        target_upload_id: targetUpload.upload_id,
        regime: quality,
      });
      setProject(data.project);
      setStep(3);
    } catch (err) {
      setError(err.message || 'Failed to start Face Swap.');
    } finally {
      setBusy(false);
    }
  };

  const back = () => {
    if (step > 0 && step < 3) setStep(step - 1);
    else navigate('create');
  };

  return (
    <div className="screen">
      <ScreenHeader title={T('face_swap')} subtitle={'Step ' + (step + 1) + ' / ' + FS_STEPS.length}
        onBack={back} right={<HelpButton topic="faceswap" lang={ctx.lang}/>}/>
      <Stepper steps={FS_STEPS} current={step}/>
      <MiniAppError message={error} onCredits={()=>navigate('credits')}/>

      {step === 0 && <div className="col">
        <div className="h-card">{T('upload_source')}</div>
        <FilePickerCard title="Choose source face" subtitle="Photo with the face to use" accept="image/*"
          file={source} onFile={setSource} icon={<Icon.face size={26}/>}/>
        <button className="btn btn-primary btn-block btn-lg" disabled={!source} onClick={()=>setStep(1)}>
          Continue <Icon.arrowRight size={16}/>
        </button>
      </div>}

      {step === 1 && <div className="col">
        <div className="h-card">{T('upload_target')}</div>
        <FilePickerCard title="Choose target photo or video" subtitle="Large files upload directly to Ravana"
          accept="image/*,video/*" file={target} onFile={setTarget} icon={<Icon.upload size={26}/>}/>
        <button className="btn btn-primary btn-block btn-lg" disabled={!target} onClick={()=>setStep(2)}>
          Continue <Icon.arrowRight size={16}/>
        </button>
      </div>}

      {step === 2 && <div className="col">
        <div className="h-card">{T('choose_quality')}</div>
        <button className={"pkg-card " + (quality === 'simple' ? 'selected' : '')} onClick={()=>setQuality('simple')}>
          <div className="row-between">
            <div><div className="h-card">{T('quality_normal')}</div><div className="dim">{T('quality_normal_sub')}</div></div>
            {quality === 'simple' && <Icon.checkCircle size={18} style={{color:'var(--gold)'}}/>}
          </div>
        </button>
        <button className={"pkg-card " + (quality === 'enhanced' ? 'selected' : '')} onClick={()=>setQuality('enhanced')}>
          <div className="row-between">
            <div><div className="h-card">{T('quality_enhanced')}</div><div className="dim">{T('quality_enhanced_sub')}</div></div>
            {quality === 'enhanced' && <Icon.checkCircle size={18} style={{color:'var(--gold)'}}/>}
          </div>
        </button>
        <CostPanel items={[
          { k: 'Source', v: source ? source.name : '-' },
          { k: 'Target', v: target ? target.name : '-' },
          { k: 'Quality', v: quality === 'enhanced' ? T('quality_enhanced') : T('quality_normal'), tone: 'gold' },
        ]}/>
        <button className="btn btn-primary btn-block btn-lg" disabled={busy} onClick={submit}>
          {busy ? 'Uploading...' : T('confirm_process')} <Icon.sparkles size={16}/>
        </button>
      </div>}

      {step === 3 && <JobProcessing ctx={ctx} initialProject={project} onReady={(p)=>{ setProject(p); setStep(4); }}/>}
      {step === 4 && <ResultView ctx={ctx} project={project} title={T('face_swap')}
        onAgain={()=>{ setStep(0); setSource(null); setTarget(null); setProject(null); }}/>}
    </div>
  );
}

function MultiFaceFlow({ ctx }){
  const { t: T, navigate, premium } = ctx;
  const [step, setStep] = _cs_useState(0);
  const [target, setTarget] = _cs_useState(null);
  const [analysis, setAnalysis] = _cs_useState(null);
  const [sources, setSources] = _cs_useState({});
  const [project, setProject] = _cs_useState(null);
  const [quality, setQuality] = _cs_useState('simple');
  const [busy, setBusy] = _cs_useState(false);
  const [error, setError] = _cs_useState(null);

  const analyze = async () => {
    if (!target) return;
    setBusy(true); setError(null);
    try {
      const uploaded = await window.RavanaMiniApp.uploadFile(target);
      const data = await window.RavanaMiniApp.analyzeMultiface({ target_upload_id: uploaded.upload_id });
      setAnalysis(data);
      setStep(1);
    } catch (err) {
      setError(err.message || 'Face analysis failed.');
    } finally {
      setBusy(false);
    }
  };

  const submit = async () => {
    if (!analysis) return;
    setBusy(true); setError(null);
    try {
      const mapping = {};
      for (const face of analysis.faces || []) {
        const file = sources[face.index];
        if (!file) continue;
        const uploaded = await window.RavanaMiniApp.uploadFile(file);
        mapping[String(face.index)] = uploaded.upload_id;
      }
      const data = await window.RavanaMiniApp.submitMultiface({
        analysis_id: analysis.analysis_id,
        face_mapping: mapping,
        regime: quality,
      });
      setProject(data.project);
      setStep(2);
    } catch (err) {
      setError(err.message || 'Failed to start MultiFace.');
    } finally {
      setBusy(false);
    }
  };

  if (premium === 'free') {
    return (
      <div className="screen">
        <ScreenHeader title={T('multiface')} onBack={()=>navigate('create')}
          right={<HelpButton topic="multiface" lang={ctx.lang}/>}/>
        <div className="card center">
          <Icon.lock size={26} style={{color:'var(--gold)'}}/>
          <div className="h-card" style={{marginTop: 10}}>{T('multiface_paywall_title')}</div>
          <div className="dim" style={{marginTop: 4}}>{T('multiface_paywall_sub')}</div>
        </div>
        <button className="btn btn-primary btn-block btn-lg" onClick={()=>navigate('credits')}>
          <Icon.crown size={16}/> {T('multiface_buy')}
        </button>
      </div>
    );
  }

  return (
    <div className="screen">
      <ScreenHeader title={T('multiface')} subtitle={'Step ' + (step + 1) + ' / ' + MF_STEPS.length}
        onBack={()=>step > 0 && step < 2 ? setStep(step - 1) : navigate('create')}
        right={<HelpButton topic="multiface" lang={ctx.lang}/>}/>
      <Stepper steps={MF_STEPS} current={step}/>
      <MiniAppError message={error} onCredits={()=>navigate('credits')}/>

      {step === 0 && <div className="col">
        <div className="h-card">{T('upload_target')}</div>
        <FilePickerCard title="Choose group photo or video" subtitle="Faces will be detected automatically"
          accept="image/*,video/*" file={target} onFile={setTarget} icon={<Icon.multiface size={26}/>}/>
        <button className="btn btn-primary btn-block btn-lg" disabled={!target || busy} onClick={analyze}>
          {busy ? 'Analyzing...' : 'Analyze faces'} <Icon.sparkles size={16}/>
        </button>
      </div>}

      {step === 1 && <div className="col">
        <div className="h-card">Detected faces</div>
        {(analysis && analysis.faces || []).map(face => (
          <div className="card" key={face.index} style={{display:'flex', gap: 12, alignItems:'center'}}>
            <img src={face.crop_url} alt="" style={{width:64, height:64, objectFit:'cover', borderRadius:12}}/>
            <div style={{flex:1, minWidth:0}}>
              <div className="h-card">Face {Number(face.index) + 1}</div>
              <div className="dim">{sources[face.index] ? sources[face.index].name : 'Choose replacement source'}</div>
            </div>
            <label className="btn btn-secondary btn-sm" style={{flex:'none'}}>
              <input type="file" accept="image/*" style={{display:'none'}}
                onChange={(event)=>setSources(s => ({...s, [face.index]: event.target.files[0]}))}/>
              Select
            </label>
          </div>
        ))}
        <button className={"pkg-card " + (quality === 'simple' ? 'selected' : '')} onClick={()=>setQuality('simple')}>
          {T('quality_normal')}
        </button>
        <button className={"pkg-card " + (quality === 'enhanced' ? 'selected' : '')} onClick={()=>setQuality('enhanced')}>
          {T('quality_enhanced')}
        </button>
        <button className="btn btn-primary btn-block btn-lg" disabled={busy || Object.keys(sources).length === 0} onClick={submit}>
          {busy ? 'Uploading...' : T('confirm_process')} <Icon.sparkles size={16}/>
        </button>
      </div>}

      {step === 2 && <JobProcessing ctx={ctx} initialProject={project} onReady={(p)=>{ setProject(p); setStep(3); }}/>}
      {step === 3 && <ResultView ctx={ctx} project={project} title={T('multiface')}
        onAgain={()=>{ setStep(0); setTarget(null); setAnalysis(null); setSources({}); setProject(null); }}/>}
    </div>
  );
}

function ImageGenFlow({ ctx }){
  const { t: T, navigate } = ctx;
  const [step, setStep] = _cs_useState(0);
  const [prompt, setPrompt] = _cs_useState('');
  const [aspect, setAspect] = _cs_useState('1:1');
  const [project, setProject] = _cs_useState(null);
  const [busy, setBusy] = _cs_useState(false);
  const [error, setError] = _cs_useState(null);

  const submit = async () => {
    setBusy(true); setError(null);
    try {
      const data = await window.RavanaMiniApp.createImageGen({ prompt, aspect_ratio: aspect });
      setProject(data.project);
      setStep(2);
    } catch (err) {
      setError(err.message || 'Failed to start Image Gen.');
    } finally {
      setBusy(false);
    }
  };

  return (
    <div className="screen">
      <ScreenHeader title={T('image_gen')} subtitle={'Step ' + (step + 1) + ' / ' + IG_STEPS.length}
        onBack={()=>step > 0 && step < 2 ? setStep(step - 1) : navigate('create')}
        right={<HelpButton topic="imagegen" lang={ctx.lang}/>}/>
      <Stepper steps={IG_STEPS} current={step}/>
      <MiniAppError message={error} onCredits={()=>navigate('credits')}/>

      {step === 0 && <div className="col">
        <textarea value={prompt} onChange={event=>setPrompt(event.target.value)}
          placeholder="Describe the image you want"
          style={{
            width:'100%', minHeight: 150, resize:'vertical', borderRadius: 14,
            border:'1px solid rgba(155,92,255,0.22)', background:'rgba(10,13,30,0.72)',
            color:'var(--text-1)', padding: 14, font:'inherit', lineHeight: 1.45,
          }}/>
        <button className="btn btn-primary btn-block btn-lg" disabled={prompt.trim().length < 3} onClick={()=>setStep(1)}>
          Continue <Icon.arrowRight size={16}/>
        </button>
      </div>}

      {step === 1 && <div className="col">
        <div className="h-card">{T('aspect_ratio')}</div>
        <div className="grid-2">
          {['1:1','16:9','9:16','4:3','3:4'].map(ratio => (
            <button key={ratio} className={"pkg-card " + (aspect === ratio ? 'selected' : '')} onClick={()=>setAspect(ratio)}>
              <div className="row-between">
                <span>{ratio}</span>
                {aspect === ratio && <Icon.checkCircle size={16} style={{color:'var(--gold)'}}/>}
              </div>
            </button>
          ))}
        </div>
        <CostPanel items={[
          { k: 'Prompt', v: prompt.slice(0, 42) + (prompt.length > 42 ? '...' : '') },
          { k: 'Aspect', v: aspect, tone: 'gold' },
          { k: 'Cost', v: '1 photo credit' },
        ]}/>
        <button className="btn btn-primary btn-block btn-lg" disabled={busy} onClick={submit}>
          {busy ? 'Submitting...' : T('imagegen_start')} <Icon.sparkles size={16}/>
        </button>
      </div>}

      {step === 2 && <JobProcessing ctx={ctx} initialProject={project} onReady={(p)=>{ setProject(p); setStep(3); }}/>}
      {step === 3 && <ResultView ctx={ctx} project={project} title={T('image_gen')}
        onAgain={()=>{ setStep(0); setPrompt(''); setProject(null); }}/>}
    </div>
  );
}

window.FaceSwapFlow = FaceSwapFlow;
window.MultiFaceFlow = MultiFaceFlow;
window.ImageGenFlow = ImageGenFlow;
