// Hymns tab — plays a saved YouTube link inline; right rail lists titles from settings.
// "Ad-free" works via the browser's Google session: sign into the saved account once
// (Google blocks programmatic password login), and a Premium account then plays embeds ad-free.
function HymnsTab({ hymns, ytAccount }){
  const [cur, setCur] = React.useState(null); // index
  const [session, setSession] = React.useState(()=> localStorage.getItem('cwa-ytsession') || '');
  const playable = cur!=null ? window.ytId(hymns[cur] && hymns[cur].url) : null;
  const hasAccount = !!(ytAccount && ytAccount.user);
  const signedIn = !!session && session === (ytAccount && ytAccount.user);

  function signIn(){
    const email = (ytAccount && ytAccount.user) || '';
    // Open Google's own secure login with the saved email pre-filled (password is entered by the
    // user on Google's page — it cannot be auto-submitted). Once signed in here, embeds use it.
    const url = 'https://accounts.google.com/AccountChooser?continue=' +
      encodeURIComponent('https://www.youtube.com') +
      (email ? '&Email=' + encodeURIComponent(email) : '');
    window.open(url, '_blank', 'noopener');
    if(email){ localStorage.setItem('cwa-ytsession', email); setSession(email); }
  }
  function signOut(){
    localStorage.removeItem('cwa-ytsession'); setSession('');
    window.open('https://www.youtube.com/logout', '_blank', 'noopener');
  }

  return (
    <div className="hymns-wrap">
      <div className="hymn-stage">
        {cur==null && <div className="hymn-empty">Select a hymn from the list to play its video here.</div>}
        {cur!=null && playable && (
          <iframe key={playable}
            src={`https://www.youtube-nocookie.com/embed/${playable}?rel=0&modestbranding=1&autoplay=1`}
            title={hymns[cur].title}
            allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
            allowFullScreen></iframe>
        )}
        {cur!=null && !playable && (
          <div className="hymn-empty">
            <div style={{fontFamily:'var(--serif)',fontSize:26,color:'#fff',marginBottom:8}}>{hymns[cur].title}</div>
            No YouTube link saved for this hymn yet.<br/>Add one in Settings &rarr; Hymns.
          </div>
        )}
      </div>

      <div className="hymn-side">
        <h3>Hymns</h3>

        <div className="yt-acct">
          <div className="yt-dot" data-on={signedIn}></div>
          <div className="yt-info">
            {signedIn
              ? <React.Fragment><b>Signed in</b> as {session}<br/><span>Premium account plays ad-free.</span></React.Fragment>
              : hasAccount
                ? <React.Fragment><b>Account saved</b> ({ytAccount.user})<br/><span>Sign in once to play ad-free.</span></React.Fragment>
                : <React.Fragment><b>No account set</b><br/><span>Add one in Settings \u2014 ads may appear.</span></React.Fragment>}
          </div>
          {hasAccount && (signedIn
            ? <button className="pill ghost sm" onClick={signOut}>Sign out</button>
            : <button className="pill sm" onClick={signIn}>Sign in</button>)}
        </div>

        <div className="hymn-list">
          {hymns.map((h,n)=>(
            <div key={n} className={'hymn-row'+(n===cur?' playing':'')} onClick={()=>setCur(n)}>
              <span className="ix">{n+1}</span>
              <span className="nm">{h.title}</span>
              <span className="pl">{window.ytId(h.url) ? (n===cur?'\u25b6':'') : '\u2014'}</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}
window.HymnsTab = HymnsTab;
