/* The Upper Room — Sign in + community profile setup. */
const { useState: useAuthState } = React;

const GOOGLE_LOGO = 'https://cdn.simpleicons.org/google';
const APPLE_LOGO = 'https://cdn.simpleicons.org/apple/ffffff';

// Auth endpoints (served same-origin via nginx /api/* -> upper-room-auth).
const AUTH = {
  google: '/api/auth/google',
  apple: '/api/auth/apple',       // Apple Service ID — wired when the key lands
  emailStart: '/api/auth/email/start',
};

function SignIn({ onAuth, onLegal }) {
  const [email, setEmail] = useAuthState('');
  // Real OAuth = a full-page redirect to the auth service; Google bounces back to the SPA.
  const goGoogle = () => { window.location.href = AUTH.google; };
  const goApple = () => { window.location.href = AUTH.apple; };
  const goEmail = () => {
    const e = (email || '').trim();
    if (!e) { try { document.querySelector('.ur-auth-email').focus(); } catch (_) {} return; }
    fetch(AUTH.emailStart, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email: e }) })
      .then(() => { alert('Check your inbox — we sent a sign-in link to ' + e + '.'); })
      .catch(() => { alert('Could not send the link right now. Please try Google.'); });
  };
  return (
    <div className="ur-auth">
      <div className="ur-auth-left">
        <div className="ur-auth-bg ur-bg-1"></div>
        <div className="ur-auth-bg ur-bg-2"></div>
        <div className="ur-auth-bg ur-bg-3"></div>
        <div className="ur-auth-left-inner">
          <div className="ur-auth-cross">✝</div>
          <h1>Where believers <em>gather.</em></h1>
          <p className="tagline">Where believers gather, work, and weigh it against the Word.</p>
          <p className="verse-ref">Acts 2 &nbsp;·&nbsp; The Upper Room</p>
        </div>
      </div>
      <div className="ur-auth-right">
        <div className="ur-auth-card">
          <div className="ur-auth-brand"><RoomBrand /></div>
          <p className="ur-auth-sub">Join the gathering. It only takes a moment.</p>
          <div className="ur-oauth">
            <button className="ur-oauth-btn" onClick={goGoogle}>
              <img className="ur-oauth-logo" src={GOOGLE_LOGO} alt="" />
              Continue with Google
            </button>
            {/* Apple sign-in removed for now — Google only (CEO 2026-06-18). goApple kept for easy re-add. */}
          </div>
          <div className="ur-auth-or">or</div>
          <input className="ur-auth-email" type="email" placeholder="you@example.com" value={email} onChange={(e) => setEmail(e.target.value)} />
          <button className="ur-auth-continue" onClick={goEmail}>Continue with email</button>
          <p className="ur-auth-fine">By continuing you agree to gather in good faith. We’ll never spam you. Read our <a onClick={(e) => { e.preventDefault(); onLegal && onLegal('legal-covenant'); }}>Community Covenant</a> · <a onClick={(e) => { e.preventDefault(); onLegal && onLegal('legal-privacy'); }}>Privacy</a> · <a onClick={(e) => { e.preventDefault(); onLegal && onLegal('legal-terms'); }}>Terms</a>.</p>
        </div>
      </div>
    </div>
  );
}

function ProfileSetup({ onComplete, onSkip, onSignOut, initialName, initialPhoto }) {
  // Prefill from the Google identity (passed down from /api/auth/me) — not a hardcoded CEO.
  const seed = (initialName || '').trim().split(' ');
  const [first, setFirst] = useAuthState(seed[0] || '');
  const [last, setLast] = useAuthState(seed.slice(1).join(' ') || '');
  const [from, setFrom] = useAuthState('');
  const [church, setChurch] = useAuthState('');
  const [walk, setWalk] = useAuthState('');
  // Photo defaults to the user's Google profile picture; they can keep it or upload a new one.
  const [photo, setPhoto] = useAuthState(initialPhoto ? { url: initialPhoto, fromGoogle: true } : null);
  const [busy, setBusy] = useAuthState(false);
  const fileRef = React.useRef(null);
  const fullName = (first + ' ' + last).trim() || 'Friend';

  const pickPhoto = () => { if (fileRef.current) fileRef.current.click(); };
  const onFile = (e) => {
    const f = e.target.files && e.target.files[0]; if (!f) return;
    const fd = new FormData(); fd.append('photo', f);
    setBusy(true);
    fetch('/api/profile/photo', { method: 'POST', body: fd })
      .then(r => r.json()).then(d => { if (d && d.photo_url) setPhoto({ url: d.photo_url }); })
      .catch(() => {/* endpoint lands with Tech's slice; UI still captures the file */})
      .finally(() => setBusy(false));
  };

  // Persist ALL fields (gap #2 fixed), then enter the room as a full member.
  const enterRoom = () => {
    const payload = { first, last, from, church, walk, photo: photo && photo.url };
    setBusy(true);
    fetch('/api/profile', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) })
      .catch(() => {/* profile API lands with Tech's slice; front end still passes the captured data up */})
      .finally(() => { setBusy(false); onComplete && onComplete(payload); });
  };

  return (
    <div className="ur-setup">
      <div className="ur-setup-card card">
        <div className="ur-setup-top">
          <div className="ur-setup-step">Step 1 of 1 · Your profile</div>
          {onSignOut && <button className="ur-setup-signout" type="button" onClick={onSignOut}>Not you? Sign out</button>}
        </div>
        <h2>Set up your community profile</h2>
        <p className="intro">This isn’t a résumé — it’s how the room gets to know you. Tell us where you’re from and where you worship, and we’ll help you find believers near you.</p>

        <div className="ur-photo-row">
          <Avatar name={fullName} photo={photo && photo.url} style={{ width: 64, height: 64, fontSize: '1.4rem' }} />
          <div className="ur-photo-hint">
            <b>Your profile photo</b>
            {photo && photo.fromGoogle ? 'Using your Google photo. Keep it, or upload your own.'
              : photo ? 'Looking good. You can change it anytime.'
              : 'Optional — your initials work just fine for now.'}
            <div className="ur-photo-actions">
              <button className="ur-photo-btn" type="button" onClick={pickPhoto}>{photo ? 'Upload a different photo' : 'Upload a photo'}</button>
              {photo && !photo.fromGoogle && initialPhoto && (
                <button className="ur-photo-btn ghost" type="button" onClick={() => setPhoto({ url: initialPhoto, fromGoogle: true })}>Use Google photo</button>
              )}
              <input ref={fileRef} type="file" accept="image/*" style={{ display: 'none' }} onChange={onFile} />
            </div>
          </div>
        </div>

        <div className="ur-field-row">
          <div className="ur-field">
            <label>First name</label>
            <input value={first} onChange={(e) => setFirst(e.target.value)} placeholder="First" />
          </div>
          <div className="ur-field">
            <label>Last name</label>
            <input value={last} onChange={(e) => setLast(e.target.value)} placeholder="Last" />
          </div>
        </div>

        <div className="ur-field">
          <label>Where are you from?</label>
          <input value={from} onChange={(e) => setFrom(e.target.value)} placeholder="City, State" />
        </div>

        <div className="ur-field">
          <label>What church do you attend?</label>
          <input value={church} onChange={(e) => setChurch(e.target.value)} placeholder="Your home church or fellowship" />
        </div>

        <div className="ur-field">
          <label>Your walk <span className="opt">— optional</span></label>
          <textarea value={walk} onChange={(e) => setWalk(e.target.value)} placeholder="A sentence about your faith, your season, or what you’re believing God for right now."></textarea>
        </div>

        <div className="ur-setup-actions">
          <button className="ur-skip" onClick={onSkip} disabled={busy}>Skip — just looking</button>
          <button className="ur-primary" onClick={enterRoom} disabled={busy}>{busy ? 'One moment…' : 'Enter the Room'}</button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { SignIn, ProfileSetup, AUTH });
