// Wander — Creator Studio (Dashboard + Tour Editor)

const HERO_COLORS = ['#FFC93C','#FF8A4C','#FF6B5A','#2DD4A7','#4FB7E8','#9B7EDC','#E89B6C','#1A1812'];
const ALL_FORMATS  = ['audio','video','text','ar','quiz'];

// ─── CREATOR DASHBOARD ────────────────────────────────────────────────────────
function CreatorDashboardScreen({ authUser, authToken, onBack, onCreateTour, onEditTour }) {
  const [tours, setTours]   = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const wrapRef = React.useRef(null);

  const loadTours = () => {
    fetch('/api/my/tours', { headers:{ Authorization:`Bearer ${authToken}` } })
      .then(r => r.json())
      .then(d => { setTours(Array.isArray(d)?d:[]); setLoading(false); })
      .catch(()  => setLoading(false));
  };

  React.useEffect(() => {
    loadTours();
    if (window.anime && wrapRef.current) {
      anime({ targets: wrapRef.current, opacity:[0,1], translateY:[20,0], duration:400, easing:'easeOutQuart' });
    }
  }, []);

  const deleteTour = async id => {
    if (!window.confirm('Delete this tour? This cannot be undone.')) return;
    await fetch(`/api/my/tours/${id}`, { method:'DELETE', headers:{ Authorization:`Bearer ${authToken}` } });
    setTours(t => t.filter(x => x.id !== id));
    if (window.anime) {
      anime({ targets:`[data-tour-id="${id}"]`, opacity:[1,0], height:[80,0], marginBottom:[10,0], duration:280, easing:'easeInQuart' });
    }
  };

  const totalAudio = tours.filter(t => t.audio_url).length;
  const totalVideo = tours.filter(t => t.video_url).length;

  return (
    <div style={{ height:'100%', display:'flex', flexDirection:'column', background:'var(--w-cream)' }} ref={wrapRef}>
      <IOSStatusBar/>

      {/* Header */}
      <div style={{ padding:'14px 20px 12px', display:'flex', alignItems:'center', gap:10, borderBottom:'1px solid var(--w-line)', flexShrink:0 }}>
        <button onClick={onBack} style={{ width:36, height:36, borderRadius:18, background:'var(--w-paper)', border:'none', cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center', boxShadow:'var(--sh-card)' }}>
          <Icon.arrow size={16} color="var(--w-ink)" style={{ transform:'scaleX(-1)' }}/>
        </button>
        <div style={{ flex:1 }}>
          <div style={{ fontSize:11, color:'var(--w-mute)', fontWeight:700, letterSpacing:0.4, textTransform:'uppercase' }}>Creator Studio</div>
          <div className="t-display" style={{ fontSize:20, fontWeight:600, lineHeight:1.1 }}>
            {authUser?.avatar_emoji || '🧭'} {authUser?.name || 'My Tours'}
          </div>
        </div>
        <button onClick={onCreateTour} style={{ height:36, padding:'0 14px', borderRadius:18, background:'var(--w-yellow)', border:'none', cursor:'pointer', fontFamily:'inherit', fontWeight:700, fontSize:13, color:'var(--w-yellow-ink)', display:'flex', alignItems:'center', gap:5 }}>
          <span style={{ fontSize:16 }}>+</span> New tour
        </button>
      </div>

      {/* Stats */}
      <div style={{ display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:8, padding:'14px 16px 10px', flexShrink:0 }}>
        {[['Tours',tours.length,'🗺️'],['🎙️ Audio',totalAudio,null],['📹 Video',totalVideo,null]].map(([label,v]) => (
          <div key={label} style={{ background:'var(--w-paper)', borderRadius:14, padding:'10px 8px', textAlign:'center', boxShadow:'var(--sh-card)' }}>
            <div className="t-display" style={{ fontSize:22, fontWeight:600, color:'var(--w-yellow-ink)' }}>{v}</div>
            <div style={{ fontSize:10, color:'var(--w-mute)', textTransform:'uppercase', letterSpacing:0.4, fontWeight:600, marginTop:2 }}>{label}</div>
          </div>
        ))}
      </div>

      {/* Tour list */}
      <div style={{ flex:1, overflowY:'auto', padding:'0 16px 100px' }} className="no-scroll app-scroll">
        {loading ? (
          <div style={{ textAlign:'center', padding:40, color:'var(--w-mute)' }}>Loading your tours…</div>
        ) : tours.length === 0 ? (
          <div style={{ textAlign:'center', padding:'40px 16px' }}>
            <div style={{ fontSize:52, marginBottom:14 }}>🗺️</div>
            <div className="t-display" style={{ fontSize:22, fontWeight:600, marginBottom:8 }}>No tours yet</div>
            <div style={{ fontSize:14, color:'var(--w-mute)', marginBottom:24, lineHeight:1.5 }}>
              Create your first tour and share your local stories with travelers from around the world.
            </div>
            <button onClick={onCreateTour} className="w-btn" style={{ padding:'13px 28px' }}>
              Create my first tour
            </button>
          </div>
        ) : (
          <div style={{ display:'flex', flexDirection:'column', gap:10, paddingTop:4 }}>
            {tours.map(t => (
              <div key={t.id} data-tour-id={t.id} style={{ background:'var(--w-paper)', borderRadius:20, padding:12, boxShadow:'var(--sh-card)', display:'flex', gap:12, alignItems:'center' }}>
                <div style={{ width:64, height:64, flexShrink:0 }}><TourArt tour={t} h={64} rounded={12}/></div>
                <div style={{ flex:1, minWidth:0 }}>
                  <div style={{ fontWeight:700, fontSize:14, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap', color:'var(--w-ink)' }}>{t.title}</div>
                  <div style={{ fontSize:11, color:'var(--w-mute)', marginTop:2 }}>{t.duration} · {t.stops} stops</div>
                  <div style={{ display:'flex', gap:5, marginTop:5, alignItems:'center', flexWrap:'wrap' }}>
                    {t.tier==='pro'
                      ? <span className="w-chip w-chip--pro"   style={{ padding:'2px 7px', fontSize:9 }}>PRO ${t.price}</span>
                      : <span className="w-chip w-chip--free"  style={{ padding:'2px 7px', fontSize:9 }}>FREE</span>}
                    <span style={{ fontSize:10, color: t.audio_url ? 'var(--w-mute)' : 'var(--w-coral)' }}>
                      {t.audio_url ? '🎙️ audio' : '⚠️ no audio'}
                    </span>
                    {t.video_url && <span style={{ fontSize:10, color:'var(--w-mute)' }}>📹 video</span>}
                  </div>
                </div>
                <div style={{ display:'flex', flexDirection:'column', gap:6, flexShrink:0 }}>
                  <button onClick={()=>onEditTour(t)} style={{ width:34, height:34, borderRadius:11, background:'var(--w-yellow-soft)', border:'none', cursor:'pointer', fontSize:15, display:'flex', alignItems:'center', justifyContent:'center' }}>✏️</button>
                  <button onClick={()=>deleteTour(t.id)} style={{ width:34, height:34, borderRadius:11, background:'#FFE9E9', border:'none', cursor:'pointer', fontSize:15, display:'flex', alignItems:'center', justifyContent:'center' }}>🗑️</button>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

// ─── TOUR EDITOR ──────────────────────────────────────────────────────────────
function TourEditorScreen({ authToken, existingTour, onBack }) {
  const isNew = !existingTour;
  const [tab, setTab]           = React.useState('details');
  const [savedTour, setSavedTour] = React.useState(existingTour || null);
  const [saving, setSaving]     = React.useState(false);
  const [saveErr, setSaveErr]   = React.useState('');
  const [saveOk, setSaveOk]     = React.useState('');

  const [form, setForm] = React.useState({
    title:    existingTour?.title    || '',
    subtitle: existingTour?.subtitle || '',
    blurb:    existingTour?.blurb    || '',
    duration: existingTour?.duration || '30 min',
    distance: existingTour?.distance || '1.0 km',
    stops:    existingTour?.stops    || 3,
    tier:     existingTour?.tier     || 'free',
    price:    existingTour?.price    || 0,
    emoji:    existingTour?.emoji    || '📍',
    formats:  existingTour?.formats  || ['audio'],
    hero:     existingTour?.hero     || ['#FFC93C','#FF8A4C'],
  });

  // Media upload state
  const [audioProgress, setAudioProgress] = React.useState(null);
  const [audioError, setAudioError]       = React.useState('');
  const [audioDone, setAudioDone]         = React.useState(!!existingTour?.audio_url);
  const [videoProgress, setVideoProgress] = React.useState(null);
  const [videoError, setVideoError]       = React.useState('');
  const [videoDone, setVideoDone]         = React.useState(!!existingTour?.video_url);
  const audioInputRef = React.useRef();
  const videoInputRef = React.useRef();

  const currentId = savedTour?.id;

  const setF = k => e => setForm(f => ({ ...f, [k]: e.target.value }));
  const setFN = k => e => setForm(f => ({ ...f, [k]: parseFloat(e.target.value)||0 }));
  const toggleFormat = fmt => setForm(f => ({
    ...f, formats: f.formats.includes(fmt) ? f.formats.filter(x=>x!==fmt) : [...f.formats, fmt],
  }));

  const handleSave = async e => {
    e.preventDefault();
    if (!form.title.trim()) { setSaveErr('Tour title is required'); return; }
    setSaving(true); setSaveErr(''); setSaveOk('');
    try {
      const method = (isNew && !savedTour) ? 'POST' : 'PUT';
      const url    = (isNew && !savedTour) ? '/api/my/tours' : `/api/my/tours/${currentId}`;
      const r = await fetch(url, {
        method, headers:{ 'Content-Type':'application/json', Authorization:`Bearer ${authToken}` },
        body: JSON.stringify({ ...form, stops: parseInt(form.stops)||0 }),
      });
      const d = await r.json();
      if (!r.ok) throw new Error(d.error);
      setSavedTour(d);
      setSaveOk(isNew && !savedTour ? 'Tour created! Now upload your audio & video below.' : 'Changes saved ✓');
      if (isNew && !savedTour) {
        setTimeout(() => setTab('media'), 800);
      }
    } catch(e) {
      setSaveErr(e.message);
    } finally { setSaving(false); }
  };

  const uploadFile = (type, file) => {
    if (!currentId) return;
    const setProgress = type==='audio' ? setAudioProgress : setVideoProgress;
    const setError    = type==='audio' ? setAudioError    : setVideoError;
    const setDone     = type==='audio' ? setAudioDone     : setVideoDone;
    setProgress(0); setError('');
    const fd = new FormData();
    fd.append('file', file);
    const xhr = new XMLHttpRequest();
    xhr.open('POST', `/api/my/tours/${currentId}/${type}`);
    xhr.setRequestHeader('Authorization', `Bearer ${authToken}`);
    xhr.upload.onprogress = ev => {
      if (ev.lengthComputable) setProgress(Math.round(ev.loaded/ev.total*100));
    };
    xhr.onload = () => {
      if (xhr.status===200) { setDone(true); setProgress(null); }
      else { setError('Upload failed — please try again'); setProgress(null); }
    };
    xhr.onerror = () => { setError('Network error — check your connection'); setProgress(null); };
    xhr.send(fd);
  };

  const deleteMedia = async type => {
    if (!currentId) return;
    await fetch(`/api/my/tours/${currentId}/${type}`, { method:'DELETE', headers:{ Authorization:`Bearer ${authToken}` } });
    if (type==='audio') setAudioDone(false);
    else setVideoDone(false);
  };

  // Styles
  const S = {
    label: { fontSize:11, fontWeight:700, color:'var(--w-mute)', textTransform:'uppercase', letterSpacing:0.5, display:'block', marginBottom:5 },
    input: { width:'100%', padding:'12px 14px', borderRadius:13, border:'1.5px solid var(--w-line)', fontSize:14, fontFamily:'inherit', color:'var(--w-ink)', background:'#fff', boxSizing:'border-box', outline:'none' },
    section: { marginBottom:18 },
    chip: active => ({ padding:'8px 14px', borderRadius:999, border:'none', cursor:'pointer', fontFamily:'inherit', fontWeight:600, fontSize:12, background: active?'var(--w-ink)':'var(--w-paper)', color: active?'var(--w-yellow)':'var(--w-mute)', boxShadow: active?'none':'inset 0 0 0 1px var(--w-line)' }),
  };

  return (
    <div style={{ height:'100%', display:'flex', flexDirection:'column', background:'var(--w-cream)' }}>
      <IOSStatusBar/>

      {/* Header */}
      <div style={{ padding:'14px 20px', display:'flex', alignItems:'center', gap:10, borderBottom:'1px solid var(--w-line)', flexShrink:0 }}>
        <button onClick={onBack} style={{ width:36, height:36, borderRadius:18, background:'var(--w-paper)', border:'none', cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center', boxShadow:'var(--sh-card)' }}>
          <Icon.arrow size={16} color="var(--w-ink)" style={{ transform:'scaleX(-1)' }}/>
        </button>
        <div className="t-display" style={{ fontSize:18, fontWeight:600, flex:1, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>
          {isNew && !savedTour ? 'New Tour' : form.title || 'Edit Tour'}
        </div>
        {form.emoji && <span style={{ fontSize:22 }}>{form.emoji}</span>}
      </div>

      {/* Tab bar */}
      <div style={{ display:'flex', borderBottom:'1px solid var(--w-line)', background:'var(--w-cream)', flexShrink:0 }}>
        {[['details','📝 Details'],['media','🎙️ Media']].map(([id,label]) => (
          <button key={id} onClick={()=>setTab(id)} style={{ flex:1, padding:'12px 0', border:'none', background:'none', fontFamily:'inherit', fontWeight:700, fontSize:13, cursor:'pointer', color: tab===id?'var(--w-yellow-ink)':'var(--w-mute)', borderBottom:`2.5px solid ${tab===id?'var(--w-yellow)':'transparent'}`, transition:'all .18s' }}>
            {label}
          </button>
        ))}
      </div>

      {/* Scrollable content */}
      <div style={{ flex:1, overflowY:'auto', padding:'16px 20px 80px' }} className="no-scroll app-scroll">

        {/* ── DETAILS TAB ── */}
        {tab==='details' && (
          <form onSubmit={handleSave}>
            <div style={S.section}>
              <label style={S.label}>Tour title *</label>
              <input style={S.input} value={form.title} onChange={setF('title')} placeholder="e.g. Marina Bay Sunset Walk" required/>
            </div>
            <div style={S.section}>
              <label style={S.label}>Subtitle</label>
              <input style={S.input} value={form.subtitle} onChange={setF('subtitle')} placeholder="Short tagline (optional)"/>
            </div>
            <div style={S.section}>
              <label style={S.label}>Description</label>
              <textarea style={{ ...S.input, minHeight:80, resize:'none', lineHeight:1.5 }} value={form.blurb} onChange={setF('blurb')} placeholder="Tell travelers what makes this route special…"/>
            </div>
            <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:10, ...S.section }}>
              <div>
                <label style={S.label}>Duration</label>
                <input style={S.input} value={form.duration} onChange={setF('duration')} placeholder="45 min"/>
              </div>
              <div>
                <label style={S.label}>Distance</label>
                <input style={S.input} value={form.distance} onChange={setF('distance')} placeholder="1.8 km"/>
              </div>
            </div>
            <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:10, ...S.section }}>
              <div>
                <label style={S.label}>Number of stops</label>
                <input style={S.input} type="number" min="1" max="50" value={form.stops} onChange={e=>setForm(f=>({...f,stops:e.target.value}))}/>
              </div>
              <div>
                <label style={S.label}>Emoji icon</label>
                <input style={S.input} value={form.emoji} onChange={setF('emoji')} placeholder="📍" maxLength={4}/>
              </div>
            </div>

            {/* Tier */}
            <div style={S.section}>
              <label style={S.label}>Access tier</label>
              <div style={{ display:'flex', gap:8 }}>
                {[['free','🆓 Free'],['pro','⭐ Pro (paid)']].map(([val,label])=>(
                  <button key={val} type="button" onClick={()=>setForm(f=>({...f,tier:val}))} style={{ flex:1, padding:'12px 0', borderRadius:13, border:'none', cursor:'pointer', fontFamily:'inherit', fontWeight:700, fontSize:13, background: form.tier===val?'var(--w-yellow)':'var(--w-paper)', color: form.tier===val?'var(--w-yellow-ink)':'var(--w-mute)', boxShadow: form.tier===val?'0 4px 14px rgba(255,201,60,0.38)':'var(--sh-card)', transition:'all .15s' }}>
                    {label}
                  </button>
                ))}
              </div>
            </div>
            {form.tier==='pro' && (
              <div style={S.section}>
                <label style={S.label}>Price (USD)</label>
                <input style={S.input} type="number" min="0.99" step="0.01" value={form.price} onChange={setFN('price')} placeholder="6.00"/>
              </div>
            )}

            {/* Formats */}
            <div style={S.section}>
              <label style={S.label}>Content formats</label>
              <div style={{ display:'flex', flexWrap:'wrap', gap:8 }}>
                {ALL_FORMATS.map(fmt=>(
                  <button key={fmt} type="button" onClick={()=>toggleFormat(fmt)} style={S.chip(form.formats.includes(fmt))}>{fmt}</button>
                ))}
              </div>
            </div>

            {/* Hero colours */}
            <div style={S.section}>
              <label style={S.label}>Hero gradient</label>
              <div style={{ height:36, borderRadius:12, background:`linear-gradient(90deg,${form.hero[0]},${form.hero[1]})`, marginBottom:10 }}/>
              <div style={{ fontSize:11, color:'var(--w-mute)', marginBottom:6, fontWeight:600 }}>FROM</div>
              <div style={{ display:'flex', gap:7, flexWrap:'wrap', marginBottom:12 }}>
                {HERO_COLORS.map(c=>(
                  <button key={c} type="button" onClick={()=>setForm(f=>({...f,hero:[c,f.hero[1]]}))} style={{ width:30, height:30, borderRadius:9, background:c, border: form.hero[0]===c?'2.5px solid var(--w-ink)':'2px solid transparent', cursor:'pointer' }}/>
                ))}
              </div>
              <div style={{ fontSize:11, color:'var(--w-mute)', marginBottom:6, fontWeight:600 }}>TO</div>
              <div style={{ display:'flex', gap:7, flexWrap:'wrap' }}>
                {HERO_COLORS.map(c=>(
                  <button key={c} type="button" onClick={()=>setForm(f=>({...f,hero:[f.hero[0],c]}))} style={{ width:30, height:30, borderRadius:9, background:c, border: form.hero[1]===c?'2.5px solid var(--w-ink)':'2px solid transparent', cursor:'pointer' }}/>
                ))}
              </div>
            </div>

            {saveErr && <div style={{ padding:'11px 14px', borderRadius:12, background:'#FFE9E9', color:'#C0392B', fontSize:13, marginBottom:12 }}>{saveErr}</div>}
            {saveOk  && <div style={{ padding:'11px 14px', borderRadius:12, background:'#E6FBF0', color:'#1A7A4A', fontSize:13, marginBottom:12 }}>{saveOk}</div>}

            <button type="submit" className="w-btn" style={{ width:'100%', height:50 }} disabled={saving}>
              {saving ? 'Saving…' : savedTour ? 'Save changes' : 'Create tour →'}
            </button>
            {isNew && !savedTour && (
              <div style={{ textAlign:'center', fontSize:12, color:'var(--w-mute)', marginTop:8 }}>
                You can upload audio & video after saving
              </div>
            )}
          </form>
        )}

        {/* ── MEDIA TAB ── */}
        {tab==='media' && (
          <div>
            {!currentId ? (
              <div style={{ textAlign:'center', padding:'40px 0', color:'var(--w-mute)' }}>
                <div style={{ fontSize:40, marginBottom:12 }}>💾</div>
                Save your tour details first, then come back here to upload audio and video.
                <br/>
                <button onClick={()=>setTab('details')} style={{ marginTop:14, padding:'10px 20px', borderRadius:9999, background:'var(--w-yellow)', border:'none', cursor:'pointer', fontFamily:'inherit', fontWeight:700, fontSize:14, color:'var(--w-yellow-ink)' }}>Go to Details →</button>
              </div>
            ) : (
              <div style={{ display:'flex', flexDirection:'column', gap:14 }}>

                {/* Audio card */}
                <div style={{ background:'var(--w-paper)', borderRadius:20, padding:18, boxShadow:'var(--sh-card)' }}>
                  <div style={{ display:'flex', gap:12, alignItems:'center', marginBottom:14 }}>
                    <div style={{ width:44, height:44, borderRadius:13, background:'var(--w-yellow-soft)', display:'flex', alignItems:'center', justifyContent:'center', fontSize:22, flexShrink:0 }}>🎙️</div>
                    <div style={{ flex:1 }}>
                      <div style={{ fontWeight:700, fontSize:15, color:'var(--w-ink)' }}>Audio Narration</div>
                      <div style={{ fontSize:12, color:'var(--w-mute)', marginTop:1 }}>MP3, AAC, M4A, WAV · up to 200 MB</div>
                    </div>
                    {audioDone && <span style={{ fontSize:20 }}>✅</span>}
                  </div>

                  {audioProgress !== null ? (
                    <div>
                      <div style={{ height:7, borderRadius:4, background:'var(--w-line)', overflow:'hidden' }}>
                        <div style={{ height:'100%', width:`${audioProgress}%`, background:'var(--w-yellow)', borderRadius:4, transition:'width .25s' }}/>
                      </div>
                      <div style={{ display:'flex', justifyContent:'space-between', marginTop:6 }}>
                        <span style={{ fontSize:12, color:'var(--w-mute)' }}>Uploading…</span>
                        <span style={{ fontSize:12, fontWeight:700, color:'var(--w-yellow-ink)' }}>{audioProgress}%</span>
                      </div>
                    </div>
                  ) : (
                    <div style={{ display:'flex', gap:8 }}>
                      <input ref={audioInputRef} type="file" accept="audio/*" style={{ display:'none' }} onChange={e=>{ if(e.target.files[0]) uploadFile('audio',e.target.files[0]); e.target.value=''; }}/>
                      <button onClick={()=>audioInputRef.current?.click()} style={{ flex:1, padding:'11px 0', borderRadius:12, border:'1.5px dashed var(--w-line)', background:'var(--w-cream)', fontFamily:'inherit', fontWeight:600, fontSize:13, color:'var(--w-slate)', cursor:'pointer' }}>
                        {audioDone ? '⬆ Replace audio file' : '⬆ Upload audio narration'}
                      </button>
                      {audioDone && (
                        <button onClick={()=>deleteMedia('audio')} style={{ width:42, height:42, borderRadius:12, background:'#FFE9E9', border:'none', cursor:'pointer', fontSize:16, flexShrink:0 }}>🗑️</button>
                      )}
                    </div>
                  )}
                  {audioError && <div style={{ fontSize:12, color:'var(--w-coral)', marginTop:7 }}>{audioError}</div>}
                </div>

                {/* Video card */}
                <div style={{ background:'var(--w-paper)', borderRadius:20, padding:18, boxShadow:'var(--sh-card)' }}>
                  <div style={{ display:'flex', gap:12, alignItems:'center', marginBottom:14 }}>
                    <div style={{ width:44, height:44, borderRadius:13, background:'#EDE8FF', display:'flex', alignItems:'center', justifyContent:'center', fontSize:22, flexShrink:0 }}>📹</div>
                    <div style={{ flex:1 }}>
                      <div style={{ fontWeight:700, fontSize:15, color:'var(--w-ink)' }}>Video Content</div>
                      <div style={{ fontSize:12, color:'var(--w-mute)', marginTop:1 }}>MP4, MOV, MKV · up to 2 GB</div>
                    </div>
                    {videoDone && <span style={{ fontSize:20 }}>✅</span>}
                  </div>

                  {videoProgress !== null ? (
                    <div>
                      <div style={{ height:7, borderRadius:4, background:'var(--w-line)', overflow:'hidden' }}>
                        <div style={{ height:'100%', width:`${videoProgress}%`, background:'#9B7EDC', borderRadius:4, transition:'width .25s' }}/>
                      </div>
                      <div style={{ display:'flex', justifyContent:'space-between', marginTop:6 }}>
                        <span style={{ fontSize:12, color:'var(--w-mute)' }}>Uploading…</span>
                        <span style={{ fontSize:12, fontWeight:700, color:'#9B7EDC' }}>{videoProgress}%</span>
                      </div>
                    </div>
                  ) : (
                    <div style={{ display:'flex', gap:8 }}>
                      <input ref={videoInputRef} type="file" accept="video/*" style={{ display:'none' }} onChange={e=>{ if(e.target.files[0]) uploadFile('video',e.target.files[0]); e.target.value=''; }}/>
                      <button onClick={()=>videoInputRef.current?.click()} style={{ flex:1, padding:'11px 0', borderRadius:12, border:'1.5px dashed var(--w-line)', background:'var(--w-cream)', fontFamily:'inherit', fontWeight:600, fontSize:13, color:'var(--w-slate)', cursor:'pointer' }}>
                        {videoDone ? '⬆ Replace video file' : '⬆ Upload video content'}
                      </button>
                      {videoDone && (
                        <button onClick={()=>deleteMedia('video')} style={{ width:42, height:42, borderRadius:12, background:'#FFE9E9', border:'none', cursor:'pointer', fontSize:16, flexShrink:0 }}>🗑️</button>
                      )}
                    </div>
                  )}
                  {videoError && <div style={{ fontSize:12, color:'var(--w-coral)', marginTop:7 }}>{videoError}</div>}
                </div>

                {/* Tips */}
                <div style={{ padding:'14px 16px', borderRadius:16, background:'var(--w-yellow-soft)', lineHeight:1.55 }}>
                  <div style={{ fontWeight:700, fontSize:13, color:'var(--w-yellow-ink)', marginBottom:6 }}>💡 Recording tips</div>
                  <ul style={{ margin:0, padding:'0 0 0 16px', fontSize:12, color:'var(--w-yellow-ink)', opacity:0.85 }}>
                    <li>Record in a quiet room — ambient noise kills immersion</li>
                    <li>MP3 at 128 kbps or higher sounds great in the player</li>
                    <li>Aim for 1–3 min per stop · 720p video is fine</li>
                    <li>Files are streamed, so size doesn't affect the listener's experience</li>
                  </ul>
                </div>
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  );
}
