/* Compose screen content (scrollable). CTA lives in the App sticky bar. window.Compose */
const { useState: useStateC, useEffect: useEffectC, useRef: useRefC } = React;

function StyleSwatch({ s }) {
  const fc = window.fontClassOf(s.font);
  return (
    <div className="w-full overflow-hidden rounded-[9px] flex flex-col items-center justify-center" style={{ background:s.bg, aspectRatio:'9/11' }}>
      <div className={fc} style={{ color:s.text, opacity:.55, fontSize:'7px', lineHeight:1, marginBottom:'3px', textTransform:s.upper?'uppercase':'none', letterSpacing:s.upper?'.04em':0 }}>now?</div>
      <div className={fc} style={{ color:s.accent, fontWeight:s.weight, fontSize:'15px', lineHeight:.9, letterSpacing:s.tracking, textTransform:s.upper?'uppercase':'none', fontStyle:s.font==='serif'?'italic':'normal', textShadow:s.glow?`0 0 8px ${s.accent}`:'none' }}>moat</div>
    </div>
  );
}

function Waveform({ active }) {
  const bars = 40;
  return (
    <div className="flex items-center justify-center gap-[3px] h-14 w-full">
      {Array.from({length:bars}).map((_,i)=>{ const seed=(Math.sin(i*1.7)+1)/2;
        return <div key={i} className="w-[3px] rounded-full" style={{ height: active?`${18+seed*70}%`:'12%', background: active?'#FFE600':'#2C2C36', transformOrigin:'center', animation: active?`barpulse ${0.5+seed*0.7}s ease-in-out ${i*0.035}s infinite`:'none', transition:'height .3s, background .3s' }}/>; })}
    </div>
  );
}

function Segmented({ value, onChange, options, full }) {
  return (
    <div className={`inline-flex p-1 rounded-xl bg-surface border border-border ${full?'w-full':''}`}>
      {options.map(o=>(
        <button key={o.v} onClick={()=>onChange(o.v)}
          className={`px-3.5 py-2 rounded-lg text-[13px] font-medium transition-all flex items-center justify-center gap-1.5 ${full?'flex-1':''} ${value===o.v?'bg-hi text-text shadow-sm':'text-muted hover:text-text'}`}>
          {o.icon}{o.label}
        </button>
      ))}
    </div>
  );
}
window.Segmented = Segmented;

function Compose({ K, inputMode, setInputMode, idea, setIdea, recording, setRecording, hasAudio, setHasAudio, onAudio, clearAudio, styleId, setStyleId, detail, setDetail }) {
  const I = window.Icon;
  const taRef = useRefC(null);
  const recRef = useRefC(null);
  const fileRef = useRefC(null);
  const [recMs, setRecMs] = useStateC(0);
  const [audioSec, setAudioSec] = useStateC(0);

  useEffectC(()=>{ if (taRef.current){ taRef.current.style.height='auto'; taRef.current.style.height=Math.min(taRef.current.scrollHeight,320)+'px'; } }, [idea, inputMode]);
  useEffectC(()=>{ if(!recording) return; const t=setInterval(()=>setRecMs(m=>m+100),100); return ()=>clearInterval(t); }, [recording]);

  const startRec = async ()=>{
    try {
      const stream = await navigator.mediaDevices.getUserMedia({ audio:true });
      const rec = new MediaRecorder(stream); const chunks=[];
      rec.ondataavailable = e => e.data.size && chunks.push(e.data);
      rec.onstop = ()=>{ stream.getTracks().forEach(t=>t.stop()); onAudio && onAudio(new Blob(chunks, { type: rec.mimeType||'audio/webm' })); };
      recRef.current = rec; rec.start(); setRecording(true); setRecMs(0);
    } catch (e) { alert('Microphone blocked: ' + e.message); }
  };
  const stopRec = ()=>{ setAudioSec(Math.round(recMs/1000)); try { recRef.current && recRef.current.stop(); } catch {} setRecording(false); };
  const pickFile = (f)=>{ if(!f) return; onAudio && onAudio(f); const url=URL.createObjectURL(f); const a=new Audio(); a.onloadedmetadata=()=>{ setAudioSec(Number.isFinite(a.duration)?a.duration:0); URL.revokeObjectURL(url); }; a.src=url; };
  const removeAudio = ()=>{ clearAudio && clearAudio(); setAudioSec(0); setRecMs(0); };
  const fmtRec = (ms)=>`0:${String(Math.floor(ms/1000)).padStart(2,'0')}`;
  const fmtDur = (s)=>{ const x=Math.max(0,Math.round(s)); return `${Math.floor(x/60)}:${String(x%60).padStart(2,'0')}`; };
  const detailHelp = { low:'punchier · ~3 scenes', medium:'balanced · ~5 scenes', high:'more story · ~7 scenes' }[detail];

  return (
    <div className="flex flex-col gap-7">
      <div className="anim-floatup">
        <div className="flex items-center gap-2 text-[11px] font-semibold tracking-[0.14em] text-muted uppercase mb-2 whitespace-nowrap">
          <span className="w-1.5 h-1.5 rounded-full bg-accent"/> New reel
        </div>
        <h1 className="text-[26px] sm:text-[30px] leading-[1.05] font-bold tracking-tight">
          Your idea, <span className="text-muted">a scroll-stopping reel.</span> No camera.
        </h1>
      </div>

      {/* input card */}
      <div className="anim-floatup rounded-2xl bg-surface border border-border p-3.5 sm:p-4" style={{ animationDelay:'.05s' }}>
        <div className="flex items-center justify-between mb-3 gap-2">
          <Segmented value={inputMode} onChange={setInputMode} options={[
            { v:'type', label:'Type', icon:<I.Type size={14}/> },
            { v:'talk', label:'Talk', icon:<I.Mic size={14}/> },
          ]}/>
          {inputMode==='type' && <span className="text-[11px] font-mono text-faint tnum shrink-0">{idea.trim().length} chars</span>}
        </div>

        {inputMode==='type' ? (
          <>
            <textarea ref={taRef} value={idea} onChange={e=>setIdea(e.target.value)}
              placeholder="Braindump it — a rough idea, a hot take, a messy thought. I'll write it into a tight script you can edit."
              className="w-full bg-transparent resize-none outline-none text-[16px] sm:text-[17px] leading-relaxed placeholder:text-faint min-h-[120px]"/>
            <div className="flex flex-wrap gap-2 mt-3 pt-3 border-t border-border">
              <span className="text-[11px] text-faint self-center mr-0.5">try</span>
              {K.EXAMPLES.map((ex,i)=>(
                <button key={i} onClick={()=>setIdea(ex)} className="text-[12px] px-2.5 py-1.5 rounded-lg bg-hi/60 hover:bg-hi border border-border text-muted hover:text-text transition-colors text-left">
                  {ex.length>40?ex.slice(0,38)+'…':ex}
                </button>
              ))}
            </div>
          </>
        ) : (
          <div className="flex flex-col items-center gap-3 py-1">
            {!hasAudio ? (
              <>
                <p className="text-[12.5px] text-muted text-center leading-relaxed px-2">Talk like you’re explaining to a friend: your take, why it matters, one example. <span className="text-faint">20–40s is plenty.</span></p>
                <button onClick={()=>recording?stopRec():startRec()}
                  className="relative w-[88px] h-[88px] rounded-full grid place-items-center transition-all active:scale-95 mt-1"
                  style={{ background: recording?'#FF3B30':'#FFE600', color:'#000', boxShadow: recording?'0 0 0 8px rgba(255,59,48,.16)':'0 0 0 8px rgba(255,230,0,.12)' }}>
                  {recording ? <I.Dot size={26} className="animate-pulse"/> : <I.Mic size={30}/>}
                  {recording && <span className="absolute inset-0 rounded-full" style={{ animation:'glowpulse 1.4s infinite' }}/>}
                </button>
                <Waveform active={recording}/>
                <div className="text-[13px] h-5">{recording
                  ? <span className="flex items-center gap-2"><span className="font-mono tnum text-alert">{fmtRec(recMs)}</span><span className="text-muted">recording — tap to stop</span></span>
                  : <span className="text-muted">Tap to record your voice note</span>}</div>
                <div className="flex items-center gap-2 w-full my-1"><div className="h-px flex-1 bg-border"/><span className="text-[11px] text-faint">or</span><div className="h-px flex-1 bg-border"/></div>
                <input ref={fileRef} type="file" accept="audio/*" className="hidden" onChange={e=>pickFile(e.target.files && e.target.files[0])}/>
                <button onClick={()=>fileRef.current && fileRef.current.click()} className="w-full rounded-xl border border-dashed border-borders hover:border-faint py-4 flex flex-col items-center gap-1.5 text-muted hover:text-text transition-colors">
                  <I.Upload size={18}/><span className="text-[13px]">Choose an audio file <span className="text-faint">· mp3, m4a, wav</span></span>
                </button>
              </>
            ) : (
              <div className="w-full flex items-center gap-3 rounded-xl bg-hi border border-border p-3 anim-popin">
                <div className="w-11 h-11 rounded-lg grid place-items-center bg-accent/15 text-accent shrink-0"><I.Volume size={18}/></div>
                <div className="flex-1 min-w-0">
                  <div className="text-[13px] font-medium">Voice note</div>
                  <div className="text-[11px] text-muted">{audioSec?fmtDur(audioSec)+' · ':''}we’ll transcribe + trim it</div>
                </div>
                <button onClick={removeAudio} className="text-faint hover:text-text p-1 -mr-1"><I.X size={16}/></button>
              </div>
            )}
          </div>
        )}
      </div>

      {/* style */}
      <div className="anim-floatup" style={{ animationDelay:'.1s' }}>
        <div className="flex items-baseline justify-between mb-3">
          <h2 className="text-[14px] font-semibold">Visual style</h2>
          <span className="text-[11px] text-faint">the reel’s look</span>
        </div>
        <div className="grid grid-cols-5 gap-2 sm:gap-2.5">
          {K.STYLES.map(s=>{ const sel=s.id===styleId;
            return (
              <button key={s.id} onClick={()=>setStyleId(s.id)} className={`group rounded-xl p-1.5 border transition-all ${sel?'border-accent bg-accent/[0.06] shadow-[0_0_18px_-6px_rgba(255,230,0,.5)]':'border-border hover:border-borders bg-surface'}`}>
                <StyleSwatch s={s}/>
                <div className={`text-[10.5px] sm:text-[11px] font-medium mt-1.5 text-center truncate ${sel?'text-text':'text-muted'}`}>{s.name}</div>
              </button>
            ); })}
        </div>
        <div className="text-[11.5px] text-faint mt-2">{K.STYLES.find(s=>s.id===styleId).desc}</div>
      </div>

      {/* detail */}
      <div className="anim-floatup" style={{ animationDelay:'.14s' }}>
        <div className="flex items-baseline justify-between mb-2.5">
          <h2 className="text-[14px] font-semibold">Detail</h2>
          <span className="text-[11.5px] text-faint">{detailHelp}</span>
        </div>
        <Segmented full value={detail} onChange={setDetail} options={[{v:'low',label:'Low'},{v:'medium',label:'Medium'},{v:'high',label:'High'}]}/>
      </div>
    </div>
  );
}

window.Compose = Compose;
window.StyleSwatch = StyleSwatch;
