// Settings modal — Website Settings + Slides + YouTube Account (left), Hymns editor (right).
function SettingsModal({ config, themes, onSave, onClose, accounts, setAccounts, currentUser }){
  const [draft, setDraft] = React.useState(()=>JSON.parse(JSON.stringify(config)));
  const set = (k,v)=> setDraft(d=>({ ...d, [k]:v }));

  // live theme preview; revert on cancel
  function pickTheme(id){
    set('themeId', id);
    const t = themes.find(x=>x.id===id); if(t) window.applyTheme(t);
  }
  function cancel(){
    const t = themes.find(x=>x.id===config.themeId); if(t) window.applyTheme(t);
    onClose();
  }
  function clearAll(){
    setDraft(d=>({ ...d, name:'', logo:'', welcomeBg:'', admins:'', users:'',
      slidesName:'', slideImages:[], ytUser:'', ytPass:'',
      hymns: d.hymns.map(h=>({ title:h.title, url:'' })) }));
  }
  function fileName(e, key){
    const f = e.target.files && e.target.files[0]; if(f) set(key, f.name);
  }
  function setHymn(i, field, val){
    setDraft(d=>{ const h = d.hymns.map(x=>({...x})); h[i][field]=val; return { ...d, hymns:h }; });
  }
  function addHymn(){ setDraft(d=>({ ...d, hymns:[...d.hymns, { title:'New Hymn', url:'' }] })); }
  function removeHymn(i){ setDraft(d=>({ ...d, hymns: d.hymns.filter((_,n)=>n!==i) })); }

  function onSlidesPick(e){
    const files = Array.from(e.target.files || []);
    if(!files.length) return;
    Promise.all(files.map(f => new Promise(res => {
      const r = new FileReader();
      r.onload = () => res({ name: f.name, url: r.result });
      r.readAsDataURL(f);
    }))).then(imgs => {
      setDraft(d => ({ ...d, slideImages: [...(d.slideImages||[]), ...imgs],
        slidesName: d.slidesName || files[0].name.replace(/\.[^.]+$/, '') }));
    });
    e.target.value = '';
  }
  function removeSlide(i){ setDraft(d => ({ ...d, slideImages: (d.slideImages||[]).filter((_,n)=>n!==i) })); }
  function clearSlides(){ setDraft(d => ({ ...d, slideImages: [] })); }

  return (
    <div className="scrim" onMouseDown={e=>{ if(e.target===e.currentTarget) cancel(); }}>
      <div className="settings">
        {/* LEFT */}
        <div className="set-col left">
          <div className="set-head">Website Settings</div>
          <div className="set-body">
            <div className="set-row">
              <span className="lbl wide">Church Name</span>
              <input className="field" value={draft.name} onChange={e=>set('name',e.target.value)} />
            </div>
            <div className="set-row">
              <span className="lbl wide">Upload Church Logo</span>
              <label className="field" style={{cursor:'pointer',color:draft.logo?'var(--field-text)':'var(--muted)'}}>
                {draft.logo || 'Choose image\u2026'}
                <input type="file" accept="image/*" hidden onChange={e=>fileName(e,'logo')} />
              </label>
            </div>
            <div className="set-row">
              <span className="lbl wide">Welcome Background Image</span>
              <label className="field" style={{cursor:'pointer',color:draft.welcomeBg?'var(--field-text)':'var(--muted)'}}>
                {draft.welcomeBg || 'Choose image\u2026'}
                <input type="file" accept="image/*" hidden onChange={e=>fileName(e,'welcomeBg')} />
              </label>
            </div>
            <div className="set-row" style={{alignItems:'flex-start'}}>
              <span className="lbl" style={{alignSelf:'flex-start',marginTop:2}}>Users &amp; Access</span>
              <div style={{flex:1}}>
                <UsersManager accounts={accounts} setAccounts={setAccounts} currentUser={currentUser} churchName={draft.name} />
              </div>
            </div>
            <div className="set-row" style={{alignItems:'stretch'}}>
              <span className="lbl">Theme Color</span>
              <div className="theme-grid">
                {themes.map(t=>(
                  <div key={t.id} className={'theme-chip'+(draft.themeId===t.id?' sel':'')}
                    title={t.name} onClick={()=>pickTheme(t.id)}>
                    {t.swatches.map((c,n)=><i key={n} style={{background:c}}></i>)}
                  </div>
                ))}
                <div className="theme-name">{(themes.find(t=>t.id===draft.themeId)||{}).name}</div>
              </div>
            </div>
          </div>

          <div className="set-head">Slides</div>
          <div className="set-body">
            <div className="set-row">
              <label className="lbl" style={{cursor:'pointer'}}>Upload Slides
                <input type="file" accept="image/*" multiple hidden onChange={onSlidesPick} />
              </label>
              <input className="field" value={draft.slidesName} onChange={e=>set('slidesName',e.target.value)} placeholder="Presentation title" />
            </div>
            {(draft.slideImages && draft.slideImages.length>0) ? (
              <React.Fragment>
                <div className="slide-thumbs">
                  {draft.slideImages.map((s,i)=>(
                    <div className="sthumb" key={i}>
                      <img src={s.url} alt={s.name} />
                      <span className="sthumb-n">{i+1}</span>
                      <button className="sthumb-x" title="Remove" onClick={()=>removeSlide(i)}>{'\u00d7'}</button>
                    </div>
                  ))}
                </div>
                <div style={{display:'flex',justifyContent:'space-between',alignItems:'center'}}>
                  <span style={{fontSize:12.5,color:'var(--muted)'}}>{draft.slideImages.length} slide{draft.slideImages.length>1?'s':''} uploaded</span>
                  <button className="pill ghost sm" onClick={clearSlides}>Remove all</button>
                </div>
              </React.Fragment>
            ) : (
              <div style={{fontSize:12.5,color:'var(--muted)'}}>
                Upload slide images (PNG/JPG, multiple allowed). They appear in the Slides tab with play controls. Tip: export your PowerPoint/Canva slides as images.
              </div>
            )}
          </div>

          <div className="set-head">Youtube Account</div>
          <div className="set-body">
            <div className="set-row">
              <span className="lbl">User Name</span>
              <input className="field" value={draft.ytUser} onChange={e=>set('ytUser',e.target.value)} placeholder="account@gmail.com" />
            </div>
            <div className="set-row">
              <span className="lbl">Password</span>
              <input className="field" type="password" value={draft.ytPass} onChange={e=>set('ytPass',e.target.value)} placeholder={'\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022'} />
            </div>
            <div style={{fontSize:12.5,color:'var(--muted)',paddingLeft:2}}>
              Sign in from the Hymns tab. Once this browser is signed into the account, a Premium account plays hymns ad-free.
            </div>
          </div>
        </div>

        {/* RIGHT — Hymns editor */}
        <div className="set-col">
          <div className="set-head">Hymns</div>
          <div className="hymn-edit">
            <div className="he-grid">
              <div className="th">Title</div>
              <div className="th" style={{fontSize:18,textAlign:'left'}}>Youtube Links</div>
              <div></div>
              {draft.hymns.map((h,i)=>(
                <React.Fragment key={i}>
                  <input className="ht field" style={{border:'none',background:'transparent',padding:'4px 0'}}
                    value={h.title} onChange={e=>setHymn(i,'title',e.target.value)} />
                  <input className="field" style={{padding:'6px 10px',fontSize:13}}
                    value={h.url} placeholder="Links" onChange={e=>setHymn(i,'url',e.target.value)} />
                  <button className="he-del" title="Remove hymn" onClick={()=>removeHymn(i)} aria-label="Remove hymn">{'\u00d7'}</button>
                </React.Fragment>
              ))}
            </div>
            <div style={{padding:'0 26px 20px'}}>
              <button className="pill ghost sm" onClick={addHymn}>+ Add Hymn</button>
            </div>
          </div>
        </div>

        {/* FOOTER */}
        <div className="set-foot">
          <button className="pill ghost" onClick={clearAll}>Clear All</button>
          <button className="pill" onClick={()=>onSave(draft)}>Save Update</button>
          <button className="pill ghost" onClick={cancel}>Cancel</button>
        </div>
      </div>
    </div>
  );
}
window.SettingsModal = SettingsModal;
